Compare commits

...

31 Commits

Author SHA1 Message Date
2dust 6c38a08f12 up 7.21.1 2026-04-30 20:13:34 +08:00
2dust f8f7fee461 Disable auto-adjust main list column width desktop 2026-04-30 10:03:10 +08:00
2dust 3e157b0d62 Update 'CheckServerSettings' message 2026-04-29 20:23:08 +08:00
Miheichev Aleksandr Sergeevich 49d197e37f i18n(ru): translate new strings and fix terminology casing (#9207)
Translate 11 new strings introduced in upstream and fix casing of
several technical terms in ResUI.ru.resx.

New translations (9 existing + 2 added):
- TbAllowInsecureCertFetch, TbAllowInsecureCertFetchTips — insecure
  certificate fetch checkbox and MITM warning tooltip
- TbHost — host field label
- TbSettingsDefUserAgentTips — updated transport list
  (raw/http, ws, gRPC, xhttp)
- TbSettingsSendThrough, TbSettingsSendThroughTip,
  FillCorrectSendThroughIPv4 — local outbound IPv4 setting
- TbSettingsUdpTestUrl, menuUdpTestServer — UDP test URL and menu item
- TransportExtra, TransportExtraTip — XHTTP Extra raw JSON

Terminology fixes:
- "V2ray" → "v2ray" (core name is lowercase by convention)
- "[Anytls]" → "[AnyTLS]" (canonical protocol spelling)
- "LAN порт" → "LAN-порт" (hyphen per Russian grammar)

All translations use canonical casing for protocols (VMess, VLESS,
Shadowsocks, Trojan, WireGuard, Hysteria, TUIC, AnyTLS), cores
(Xray, sing-box, mihomo, v2ray) and abbreviations (TLS, DNS, UUID,
HTTP, IPv4, MTU, TUN, PAC, SOCKS, gRPC, XHTTP).
2026-04-29 14:43:35 +08:00
DHR60 b6f2912f29 Remove EchForceQuery (#9214) 2026-04-29 14:43:13 +08:00
2dust 05e349e45c Code clean 2026-04-26 19:24:57 +08:00
2dust ae662a628d Remove TbSettingsRemoteDNS and update DNS doc 2026-04-26 17:50:10 +08:00
2dust 6e85f79852 Preserve complex profile items during deduplication
https://github.com/2dust/v2rayN/issues/9184
2026-04-25 10:55:51 +08:00
DHR60 0af29f50c0 UDP Test (#8999)
* UDP Test

Increases UDP test timeout

Pref exception

Fix

Add Minecraft Bedrock Edition Test

* Optimization

* Refactor

* Rename
2026-04-25 10:45:45 +08:00
DHR60 ee6ae3d91d Add kcp mtu (#9178)
* Add kcp mtu

* Typo
2026-04-25 10:39:39 +08:00
2dust c4e071cac3 up 7.21.0 2026-04-24 14:39:38 +08:00
2dust 798831128a Update Directory.Packages.props 2026-04-24 14:34:05 +08:00
DHR60 a2de087aef Fix (#9171) 2026-04-21 17:17:25 +08:00
DHR60 89bc012c95 Fix (#9166) 2026-04-21 09:51:28 +08:00
2dust 39ef5d8174 Default to first sub; update SubIndexId on delete
https://github.com/2dust/v2rayN/issues/9151
2026-04-20 19:23:45 +08:00
DHR60 90b055e364 Remove legacy sing-box dns compatibility (#9163) 2026-04-20 18:58:56 +08:00
DHR60 d67321eed0 Add more test (#9162)
* Add test
Add more test and fmt test

* Update to xunit.v3
2026-04-20 18:58:36 +08:00
Bonjour LI 67592d1922 CI: Sleep 0-2s for race condition between matrix jobs (#9161) 2026-04-20 18:58:26 +08:00
DHR60 c5db319e0e URL test apply fragment (#9157) 2026-04-20 09:19:26 +08:00
Bonjour LI 6a7b359fcc CI: Explicitly define GitHub token permissions in config (#9155)
GitHub has updated its behavior: new forks no longer inherit the original repository's GitHub token permissions. 
To ensure consistent access, this change explicitly defines the required permissions in the configuration file.
2026-04-20 09:15:23 +08:00
DHR60 25d7f393b6 Fetch cert allow insecure (#8998) 2026-04-19 17:16:06 +08:00
DHR60 171ed6f58f Custom MessageBoxDialog (#9147) 2026-04-19 17:06:15 +08:00
Mangoo b604a5b787 fix: remove Save/Cancel from routing settings, save edits immediately (#9133) 2026-04-19 14:25:53 +08:00
DHR60 35b98f945f Support new fragment (#9122) 2026-04-19 13:42:55 +08:00
DHR60 cabd0df282 Support kcp cwndMultiplier (#9113) 2026-04-18 19:19:03 +08:00
DHR60 eeecef4db9 Fix (#9143)
* Adjust XHTTP style

* Add xray tun custom support
2026-04-18 19:18:17 +08:00
DHR60 021e64e20b Fix (#9141) 2026-04-18 15:23:42 +08:00
JieXu 452478434c Fix & Update (#9126)
* Update build-linux.yml

* Update build-all.yml

* Update build-linux.yml

* Update build-linux.yml

* Update build-linux.yml

* Update OptionSettingWindow.axaml.cs

* Update ResUI.fr.resx

* Update package-rhel-riscv.sh

* Update build-linux.yml

* Update build-linux.yml

* Update build-all.yml

---------

Co-authored-by: xujie86 <167618598+xujie86@users.noreply.github.com>
2026-04-17 15:29:51 +08:00
DHR60 5305b0843b Fix (#9128) 2026-04-17 13:36:42 +08:00
DHR60 9f0ef36cc0 Refactor Transport (#9004)
* Refactor transport

* Rename tcp to raw

* Fix

* Fix

Fix raw http ui

Fill xhttp default mode

Fix share uri

Remove RawHost

Fix singbox tcp http path

Fix vmess share uri

* Tidy Resx

* Fix

* Rename TransportExtra to TransportExtraItem

---------

Co-authored-by: 2dust <31833384+2dust@users.noreply.github.com>
2026-04-16 20:21:10 +08:00
DHR60 494b35c1f7 Add xray tun support (#9063)
* Add xray tun support

* Revert mtu list
2026-04-16 19:17:44 +08:00
106 changed files with 5238 additions and 1787 deletions
+3
View File
@@ -7,6 +7,9 @@ on:
required: false
type: string
permissions:
actions: write
jobs:
update:
runs-on: ubuntu-latest
+3 -3
View File
@@ -185,7 +185,7 @@ jobs:
(github.event_name == 'workflow_dispatch' && inputs.release_tag != '') ||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
runs-on: ubuntu-24.04-riscv
container: ghcr.io/xujiegb/fedora-riscv:43-latest
container: rockylinux/rockylinux:10
env:
RELEASE_TAG: ${{ case(inputs.release_tag != '', inputs.release_tag, github.ref_name) }}
@@ -196,8 +196,8 @@ jobs:
set -euo pipefail
dnf -y makecache
dnf -y install \
sudo git rpm-build rpmdevtools dnf-plugins-core rsync findutils tar gzip unzip which curl jq wget file \
ca-certificates desktop-file-utils xdg-utils python3 gcc make glibc-devel kernel-headers libatomic libstdc++
sudo git rpm-build rpmdevtools dnf-plugins-core \
rsync findutils tar gzip unzip which jq
- name: Checkout repo (for scripts)
shell: bash
+3
View File
@@ -61,6 +61,9 @@ jobs:
- name: Package dmg
run: ./package-osx.sh macos-$Arch v2rayN-macos-$Arch ${{ inputs.release_tag }}
- name: Sleep for race condition between matrix jobs
run: sleep $(awk 'BEGIN { srand(); printf "%.3f", rand()*2 }')
- name: Upload dmg to release
uses: svenstaro/upload-release-action@v2
+3
View File
@@ -55,6 +55,9 @@ jobs:
if: inputs.target == 'windows-desktop'
run: mv "v2rayN-$Target-$Arch.zip" "v2rayN-$Target-$Arch-desktop.zip"
- name: Sleep for race condition between matrix jobs
run: sleep $(awk 'BEGIN { srand(); printf "%.3f", rand()*2 }')
- name: Upload zip archive to release
uses: svenstaro/upload-release-action@v2
with:
+4 -4
View File
@@ -37,7 +37,7 @@ DOTNET_RISCV_VERSION="10.0.105"
DOTNET_RISCV_BASE="https://github.com/filipnavara/dotnet-riscv/releases/download"
DOTNET_RISCV_FILE="dotnet-sdk-${DOTNET_RISCV_VERSION}-linux-riscv64.tar.gz"
DOTNET_SDK_URL="${DOTNET_RISCV_BASE}/${DOTNET_RISCV_VERSION}/${DOTNET_RISCV_FILE}"
SKIA_VER="${SKIA_VER:-3.119.1}"
SKIA_VER="${SKIA_VER:-3.119.2}"
HARFBUZZ_VER="${HARFBUZZ_VER:-8.3.1.1}"
# If the first argument starts with --, do not treat it as a version number
@@ -111,9 +111,9 @@ build_sqlite_native_riscv64() {
mkdir -p "$outdir"
workdir="$(mktemp -d)"
# SQLite 3.49.1 amalgamation
sqlite_year="2025"
sqlite_ver="3490100"
# SQLite 3.51.3 amalgamation
sqlite_year="2026"
sqlite_ver="3510300"
sqlite_zip="sqlite-amalgamation-${sqlite_ver}.zip"
echo "[+] Download SQLite amalgamation: ${sqlite_zip}"
+1 -1
View File
@@ -1,7 +1,7 @@
<Project>
<PropertyGroup>
<Version>7.20.4</Version>
<Version>7.21.1</Version>
</PropertyGroup>
<PropertyGroup>
+5 -4
View File
@@ -9,13 +9,14 @@
<PackageVersion Include="Avalonia.Controls.DataGrid" Version="11.3.13" />
<PackageVersion Include="Avalonia.Desktop" Version="11.3.13" />
<PackageVersion Include="Avalonia.Diagnostics" Version="11.3.13" />
<PackageVersion Include="AwesomeAssertions" Version="9.4.0" />
<PackageVersion Include="DialogHost.Avalonia" Version="0.11.0" />
<PackageVersion Include="ReactiveUI.Avalonia" Version="11.4.12" />
<PackageVersion Include="CliWrap" Version="3.10.1" />
<PackageVersion Include="Downloader" Version="5.1.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageVersion Include="Downloader" Version="5.2.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.4.0" />
<PackageVersion Include="H.NotifyIcon.Wpf" Version="2.4.1" />
<PackageVersion Include="MaterialDesignThemes" Version="5.3.1" />
<PackageVersion Include="MessageBox.Avalonia" Version="3.3.1.1" />
<PackageVersion Include="QRCoder" Version="1.8.0" />
<PackageVersion Include="ReactiveUI" Version="23.2.1" />
<PackageVersion Include="ReactiveUI.Fody" Version="19.5.41" />
@@ -27,8 +28,8 @@
<PackageVersion Include="sqlite-net-pcl" Version="1.9.172" />
<PackageVersion Include="TaskScheduler" Version="2.12.2" />
<PackageVersion Include="WebDav.Client" Version="2.9.0" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
<PackageVersion Include="xunit.v3" Version="3.2.2" />
<PackageVersion Include="YamlDotNet" Version="16.3.0" />
<PackageVersion Include="ZXing.Net.Bindings.SkiaSharp" Version="0.16.14" />
</ItemGroup>
@@ -0,0 +1,113 @@
using AwesomeAssertions;
using ServiceLib.Enums;
using ServiceLib.Handler.Builder;
using ServiceLib.Helper;
using ServiceLib.Models;
using Xunit;
namespace ServiceLib.Tests.CoreConfig.Context;
public class CoreConfigContextBuilderTests
{
[Fact]
public async Task ResolveNodeAsync_DirectCycleDependency_ShouldFailWithCycleError()
{
var config = CoreConfigTestFactory.CreateConfig();
CoreConfigTestFactory.BindAppManagerConfig(config);
var groupAId = NewId("group-a");
var groupBId = NewId("group-b");
var groupA = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.Xray, groupAId, "group-a", [groupBId]);
var groupB = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.Xray, groupBId, "group-b", [groupAId]);
await UpsertProfilesAsync(groupA, groupB);
var context = CoreConfigTestFactory.CreateContext(config, groupA, ECoreType.Xray);
context.AllProxiesMap.Clear();
var (_, validatorResult) = await CoreConfigContextBuilder.ResolveNodeAsync(context, groupA, false);
validatorResult.Success.Should().BeFalse();
validatorResult.Errors.Should().Contain(msg => ContainsCycleDependencyMessage(msg));
context.AllProxiesMap.Should().NotContainKey(groupA.IndexId);
context.AllProxiesMap.Should().NotContainKey(groupB.IndexId);
}
[Fact]
public async Task ResolveNodeAsync_IndirectCycleDependency_ShouldFailWithCycleError()
{
var config = CoreConfigTestFactory.CreateConfig();
CoreConfigTestFactory.BindAppManagerConfig(config);
var groupAId = NewId("group-a");
var groupBId = NewId("group-b");
var groupCId = NewId("group-c");
var groupA = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.Xray, groupAId, "group-a", [groupBId]);
var groupB = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.Xray, groupBId, "group-b", [groupCId]);
var groupC = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.Xray, groupCId, "group-c", [groupAId]);
await UpsertProfilesAsync(groupA, groupB, groupC);
var context = CoreConfigTestFactory.CreateContext(config, groupA, ECoreType.Xray);
context.AllProxiesMap.Clear();
var (_, validatorResult) = await CoreConfigContextBuilder.ResolveNodeAsync(context, groupA, false);
validatorResult.Success.Should().BeFalse();
validatorResult.Errors.Should().Contain(msg => ContainsCycleDependencyMessage(msg));
context.AllProxiesMap.Should().NotContainKey(groupA.IndexId);
context.AllProxiesMap.Should().NotContainKey(groupB.IndexId);
context.AllProxiesMap.Should().NotContainKey(groupC.IndexId);
}
[Fact]
public async Task ResolveNodeAsync_CycleWithValidBranch_ShouldSkipCycleAndKeepValidChild()
{
var config = CoreConfigTestFactory.CreateConfig();
CoreConfigTestFactory.BindAppManagerConfig(config);
var groupAId = NewId("group-a");
var groupBId = NewId("group-b");
var leafId = NewId("leaf");
var groupA = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.Xray, groupAId, "group-a", [groupBId, leafId]);
var groupB = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.Xray, groupBId, "group-b", [groupAId]);
var leaf = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, leafId, "leaf");
await UpsertProfilesAsync(groupA, groupB, leaf);
var context = CoreConfigTestFactory.CreateContext(config, groupA, ECoreType.Xray);
context.AllProxiesMap.Clear();
var (_, validatorResult) = await CoreConfigContextBuilder.ResolveNodeAsync(context, groupA, false);
validatorResult.Success.Should().BeTrue();
validatorResult.Errors.Should().BeEmpty();
validatorResult.Warnings.Should().Contain(msg => ContainsCycleDependencyMessage(msg));
context.AllProxiesMap.Should().ContainKey(leaf.IndexId);
context.AllProxiesMap.Should().ContainKey(groupA.IndexId);
context.AllProxiesMap.Should().NotContainKey(groupB.IndexId);
groupA.GetProtocolExtra().ChildItems.Should().Be(leaf.IndexId);
}
private static string NewId(string prefix)
{
return $"{prefix}-{Guid.NewGuid():N}";
}
private static bool ContainsCycleDependencyMessage(string message)
{
return message.Contains("cycle dependency", StringComparison.OrdinalIgnoreCase)
|| message.Contains("循环依赖", StringComparison.Ordinal)
|| message.Contains("循環依賴", StringComparison.Ordinal);
}
private static async Task UpsertProfilesAsync(params ProfileItem[] profiles)
{
SQLiteHelper.Instance.CreateTable<ProfileItem>();
foreach (var profile in profiles)
{
await SQLiteHelper.Instance.ReplaceAsync(profile);
}
}
}
@@ -0,0 +1,209 @@
using System.Reflection;
using ServiceLib.Enums;
using ServiceLib.Manager;
using ServiceLib.Models;
namespace ServiceLib.Tests.CoreConfig;
internal static class CoreConfigTestFactory
{
public static void BindAppManagerConfig(Config config)
{
var field = typeof(AppManager).GetField("_config", BindingFlags.Instance | BindingFlags.NonPublic);
field?.SetValue(AppManager.Instance, config);
}
public static Config CreateConfig(ECoreType vmessCoreType = ECoreType.Xray)
{
return new Config
{
CoreBasicItem = new CoreBasicItem { Loglevel = "warning", MuxEnabled = false },
TunModeItem = new TunModeItem { EnableTun = false, IcmpRouting = "default" },
KcpItem = new KcpItem(),
GrpcItem = new GrpcItem(),
RoutingBasicItem =
new RoutingBasicItem
{
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
RoutingIndexId = string.Empty,
},
GuiItem = new GUIItem { EnableStatistics = false, DisplayRealTimeSpeed = false, EnableLog = false },
MsgUIItem = new MsgUIItem(),
UiItem =
new UIItem
{
CurrentLanguage = "en",
CurrentFontFamily = "sans",
MainColumnItem = [],
WindowSizeItem = []
},
ConstItem = new ConstItem(),
SpeedTestItem = new SpeedTestItem
{
SpeedPingTestUrl = Global.SpeedPingTestUrls.First(),
SpeedTestUrl = Global.SpeedTestUrls.First(),
SpeedTestTimeout = 10,
MixedConcurrencyCount = 1,
IPAPIUrl = string.Empty,
},
Mux4RayItem = new Mux4RayItem { Concurrency = 8, XudpConcurrency = 16, XudpProxyUDP443 = "reject" },
Mux4SboxItem = new Mux4SboxItem { Protocol = Global.SingboxMuxs.First(), MaxConnections = 8 },
HysteriaItem = new HysteriaItem { UpMbps = 100, DownMbps = 100 },
ClashUIItem = new ClashUIItem { ConnectionsColumnItem = [] },
SystemProxyItem =
new SystemProxyItem
{
SystemProxyExceptions = string.Empty,
SystemProxyAdvancedProtocol = string.Empty
},
WebDavItem = new WebDavItem(),
CheckUpdateItem = new CheckUpdateItem(),
Fragment4RayItem = new Fragment4RayItem { Packets = "tlshello", Length = "100-200", Interval = "10-20" },
Inbound =
[
new InItem
{
Protocol = nameof(EInboundProtocol.socks),
LocalPort = 10808,
UdpEnabled = true,
SniffingEnabled = true,
RouteOnly = false,
DestOverride = ["http", "tls"],
}
],
GlobalHotkeys = [],
CoreTypeItem =
[
new CoreTypeItem { ConfigType = EConfigType.VMess, CoreType = vmessCoreType }
],
SimpleDNSItem = new SimpleDNSItem
{
BootstrapDNS = Global.DomainPureIPDNSAddress.FirstOrDefault(),
ServeStale = false,
ParallelQuery = false,
Strategy4Freedom = Global.AsIs,
Strategy4Proxy = Global.AsIs,
},
IndexId = string.Empty,
SubIndexId = string.Empty,
};
}
public static ProfileItem CreateVmessNode(ECoreType coreType, string indexId = "node-1", string remarks = "demo")
{
var node = new ProfileItem
{
IndexId = indexId,
ConfigType = EConfigType.VMess,
CoreType = coreType,
Remarks = remarks,
Address = "example.com",
Port = 443,
Password = Guid.NewGuid().ToString(),
Network = nameof(ETransport.raw),
StreamSecurity = string.Empty,
Subid = string.Empty,
};
node.SetProtocolExtra(node.GetProtocolExtra() with { AlterId = "0", VmessSecurity = Global.DefaultSecurity, });
return node;
}
public static ProfileItem CreateSocksNode(ECoreType coreType, string indexId = "node-socks-1",
string remarks = "demo-socks")
{
return new ProfileItem
{
IndexId = indexId,
ConfigType = EConfigType.SOCKS,
CoreType = coreType,
Remarks = remarks,
Address = "127.0.0.1",
Port = 1080,
Password = "pass",
Username = "user",
Network = nameof(ETransport.raw),
StreamSecurity = string.Empty,
Subid = string.Empty,
};
}
public static ProfileItem CreatePolicyGroupNode(ECoreType coreType, string indexId, string remarks,
IEnumerable<string> childIndexIds)
{
var node = new ProfileItem
{
IndexId = indexId,
ConfigType = EConfigType.PolicyGroup,
CoreType = coreType,
Remarks = remarks,
};
node.SetProtocolExtra(node.GetProtocolExtra() with
{
GroupType = nameof(EConfigType.PolicyGroup),
ChildItems = string.Join(",", childIndexIds),
});
return node;
}
public static ProfileItem CreateProxyChainNode(ECoreType coreType, string indexId, string remarks,
IEnumerable<string> childIndexIds)
{
var node = new ProfileItem
{
IndexId = indexId,
ConfigType = EConfigType.ProxyChain,
CoreType = coreType,
Remarks = remarks,
};
node.SetProtocolExtra(node.GetProtocolExtra() with
{
GroupType = nameof(EConfigType.ProxyChain),
ChildItems = string.Join(",", childIndexIds),
});
return node;
}
public static CoreConfigContext CreateContext(Config config, ProfileItem node, ECoreType runCoreType)
{
return new CoreConfigContext
{
Node = node,
RunCoreType = runCoreType,
AppConfig = config,
RoutingItem = new RoutingItem
{
Id = "r1",
Remarks = "default",
RuleSet = "[]",
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
},
RawDnsItem = null,
SimpleDnsItem = config.SimpleDNSItem,
AllProxiesMap = new Dictionary<string, ProfileItem> { [node.IndexId] = node },
FullConfigTemplate = null,
IsTunEnabled = false,
ProtectDomainList = [],
};
}
public static Config CreateConfigWithDirectExpectedIPs(ECoreType coreType,
string directExpectedIPs = "192.168.0.0/16,geoip:cn")
{
var config = CreateConfig(coreType);
config.SimpleDNSItem.DirectExpectedIPs = directExpectedIPs;
return config;
}
public static Config CreateConfigWithBootstrapDNS(ECoreType coreType, string bootstrapDns = "8.8.8.8")
{
var config = CreateConfig(coreType);
config.SimpleDNSItem.BootstrapDNS = bootstrapDns;
return config;
}
}
@@ -0,0 +1,511 @@
using AwesomeAssertions;
using ServiceLib.Common;
using ServiceLib.Enums;
using ServiceLib.Models;
using ServiceLib.Services.CoreConfig;
using Xunit;
namespace ServiceLib.Tests.CoreConfig.Singbox;
public class CoreConfigSingboxServiceTests
{
[Fact]
public void GenerateClientConfigContent_ShouldGenerateBasicProxyConfig()
{
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 result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
result.Data.Should().NotBeNull();
var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString());
singboxConfig.Should().NotBeNull();
singboxConfig!.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "socks");
singboxConfig.inbounds.Should().Contain(i => i.type == nameof(EInboundProtocol.mixed));
}
[Fact]
public void GenerateClientConfigContent_PolicyGroup_ShouldExpandChildrenAndBuildSelector()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
CoreConfigTestFactory.BindAppManagerConfig(config);
var n1 = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n1", "node-1");
var n2 = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n2", "node-2");
var group = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.sing_box, "g1", "group",
[n1.IndexId, n2.IndexId]);
var context = CoreConfigTestFactory.CreateContext(config, group, ECoreType.sing_box);
context.AllProxiesMap[n1.IndexId] = n1;
context.AllProxiesMap[n2.IndexId] = n2;
context.AllProxiesMap[group.IndexId] = group;
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "selector");
cfg.outbounds.Should().Contain(o => o.tag == $"{Global.ProxyTag}-auto" && o.type == "urltest");
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-1-", StringComparison.Ordinal));
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-2-", StringComparison.Ordinal));
}
[Fact]
public void GenerateClientConfigContent_ProxyChain_ShouldBuildDetourChain()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
CoreConfigTestFactory.BindAppManagerConfig(config);
var n1 = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n1", "node-1");
var n2 = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n2", "node-2");
var chain = CoreConfigTestFactory.CreateProxyChainNode(ECoreType.sing_box, "c1", "chain",
[n1.IndexId, n2.IndexId]);
var context = CoreConfigTestFactory.CreateContext(config, chain, ECoreType.sing_box);
context.AllProxiesMap[n1.IndexId] = n1;
context.AllProxiesMap[n2.IndexId] = n2;
context.AllProxiesMap[chain.IndexId] = chain;
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "socks");
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-", StringComparison.Ordinal));
cfg.outbounds.Should().Contain(o =>
o.tag == Global.ProxyTag &&
(o.detour ?? string.Empty).StartsWith("chain-proxy-1-", StringComparison.Ordinal));
}
[Fact]
public void GenerateClientConfigContent_PolicyGroupWithProxyChain_ShouldBuildCombinedOutbounds()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
CoreConfigTestFactory.BindAppManagerConfig(config);
var n1 = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n1", "node-1");
var n2 = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n2", "node-2");
var n3 = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n3", "node-3");
var chain = CoreConfigTestFactory.CreateProxyChainNode(ECoreType.sing_box, "c1", "chain",
[n1.IndexId, n2.IndexId]);
var group = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.sing_box, "g1", "group",
[chain.IndexId, n3.IndexId]);
var context = CoreConfigTestFactory.CreateContext(config, group, ECoreType.sing_box);
context.AllProxiesMap[n1.IndexId] = n1;
context.AllProxiesMap[n2.IndexId] = n2;
context.AllProxiesMap[n3.IndexId] = n3;
context.AllProxiesMap[chain.IndexId] = chain;
context.AllProxiesMap[group.IndexId] = group;
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "selector");
cfg.outbounds.Should().Contain(o => o.tag == $"{Global.ProxyTag}-auto" && o.type == "urltest");
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-1-", StringComparison.Ordinal));
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-", StringComparison.Ordinal));
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-2-", StringComparison.Ordinal));
}
[Fact]
public void GenerateClientConfigContent_ProxyChainWithPolicyGroup_ShouldBuildClonedChainBranches()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
CoreConfigTestFactory.BindAppManagerConfig(config);
var n1 = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n1", "node-1");
var n2 = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n2", "node-2");
var n3 = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n3", "node-3");
var group = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.sing_box, "g1", "group",
[n1.IndexId, n2.IndexId]);
var chain = CoreConfigTestFactory.CreateProxyChainNode(ECoreType.sing_box, "c1", "chain",
[group.IndexId, n3.IndexId]);
var context = CoreConfigTestFactory.CreateContext(config, chain, ECoreType.sing_box);
context.AllProxiesMap[n1.IndexId] = n1;
context.AllProxiesMap[n2.IndexId] = n2;
context.AllProxiesMap[n3.IndexId] = n3;
context.AllProxiesMap[group.IndexId] = group;
context.AllProxiesMap[chain.IndexId] = chain;
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "selector");
cfg.outbounds.Should().Contain(o => o.tag == $"{Global.ProxyTag}-auto" && o.type == "urltest");
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-group-1-", StringComparison.Ordinal));
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-group-2-", StringComparison.Ordinal));
var proxyCloneCount = cfg.outbounds.Count(o => o.tag.StartsWith("proxy-clone-", StringComparison.Ordinal));
proxyCloneCount.Should().Be(2);
var allCloneDetoursPointToGroupBranches = cfg.outbounds
.Where(o => o.tag.StartsWith("proxy-clone-", StringComparison.Ordinal))
.All(o => (o.detour ?? string.Empty).StartsWith("chain-proxy-1-group-", StringComparison.Ordinal));
allCloneDetoursPointToGroupBranches.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_RoutingSplit_DirectAndBlock_ShouldApplyRules()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
{
RoutingItem = new RoutingItem
{
Id = "r-split-1",
Remarks = "split-direct-block",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true,
RuleType = ERuleType.Routing,
OutboundTag = Global.DirectTag,
Domain = ["full:direct.example.com"],
},
new()
{
Enabled = true,
RuleType = ERuleType.Routing,
OutboundTag = Global.BlockTag,
Domain = ["full:block.example.com"],
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
var hasDirectRule = cfg.route.rules.Any(r =>
r.domain != null
&& r.domain.Contains("direct.example.com")
&& r.outbound == Global.DirectTag);
hasDirectRule.Should().BeTrue();
var hasBlockRule = cfg.route.rules.Any(r =>
r.domain != null
&& r.domain.Contains("block.example.com")
&& r.action == "reject");
hasBlockRule.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_RoutingSplit_ByRemark_ShouldGenerateTargetOutbound()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
var routeNode = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-route", "route-node");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
{
RoutingItem = new RoutingItem
{
Id = "r-split-2",
Remarks = "split-remark",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true,
RuleType = ERuleType.Routing,
OutboundTag = routeNode.Remarks,
Domain = ["full:route.example.com"],
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
context.AllProxiesMap[$"remark:{routeNode.Remarks}"] = routeNode;
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
var expectedPrefix = $"{routeNode.IndexId}-{Global.ProxyTag}-{routeNode.Remarks}";
cfg.outbounds.Should().Contain(o => o.tag.StartsWith(expectedPrefix, StringComparison.Ordinal));
var hasRouteRule = cfg.route.rules.Any(r =>
r.domain != null
&& r.domain.Contains("route.example.com")
&& (r.outbound ?? string.Empty).StartsWith(expectedPrefix, StringComparison.Ordinal));
hasRouteRule.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_DirectExpectedIPs_ShouldApplyGeoipAndCidrToDirectDnsRule()
{
var config = CoreConfigTestFactory.CreateConfigWithDirectExpectedIPs(
ECoreType.sing_box,
"192.168.0.0/16,geoip:cn");
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
{
RoutingItem = new RoutingItem
{
Id = "r-dns-direct-expected",
Remarks = "dns-direct-expected",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true,
RuleType = ERuleType.DNS,
OutboundTag = Global.DirectTag,
Domain = ["geosite:cn"],
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
var hasExpectedRule = cfg.dns.rules?.Any(r =>
r.server == Global.SingboxDirectDNSTag
&& r.ip_cidr?.Contains("192.168.0.0/16") == true
&& r.rule_set?.Contains("geosite-cn") == true
&& r.rule_set?.Contains("geoip-cn") == true) ?? false;
hasExpectedRule.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_BootstrapDNS_ShouldConfigurePureIPResolver()
{
var bootstrapDns = "8.8.8.8";
var config = CoreConfigTestFactory.CreateConfigWithBootstrapDNS(ECoreType.sing_box, bootstrapDns);
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box);
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
config.SimpleDNSItem.BootstrapDNS.Should().Be(bootstrapDns);
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
var bootstrapServer = cfg.dns.servers?.FirstOrDefault(s => s.tag == Global.SingboxLocalDNSTag);
bootstrapServer.Should().NotBeNull();
(bootstrapServer?.server ?? string.Empty).Should().Contain(bootstrapDns);
}
[Fact]
public void GenerateClientConfigContent_DnsFallback_LastRuleDirect_ShouldUseDirectFinalDns()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
config.SimpleDNSItem.DirectDNS = "1.1.1.1";
config.SimpleDNSItem.RemoteDNS = "9.9.9.9";
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
{
RoutingItem = new RoutingItem
{
Id = "r-direct-final",
Remarks = "direct-final",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true,
RuleType = ERuleType.Routing,
OutboundTag = Global.DirectTag,
Ip = ["0.0.0.0/0"],
Port = "0-65535",
Network = "tcp,udp",
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
cfg.dns.final.Should().Be(Global.SingboxDirectDNSTag);
}
[Fact]
public void GenerateClientConfigContent_DirectExpectedIPs_NonMatchingRegion_ShouldNotApplyExpectedRule()
{
var config =
CoreConfigTestFactory.CreateConfigWithDirectExpectedIPs(ECoreType.sing_box, "192.168.0.0/16,geoip:cn");
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
{
RoutingItem = new RoutingItem
{
Id = "r-dns-direct-unmatched",
Remarks = "dns-direct-unmatched",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true,
RuleType = ERuleType.DNS,
OutboundTag = Global.DirectTag,
Domain = ["geosite:us"],
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
var hasExpectedRule = cfg.dns.rules?.Any(r =>
r.server == Global.SingboxDirectDNSTag
&& r.ip_cidr?.Contains("192.168.0.0/16") == true
&& r.rule_set?.Contains("geoip-cn") == true) ?? false;
hasExpectedRule.Should().BeFalse();
}
[Theory]
[InlineData("geosite:cn", "geosite-cn")]
[InlineData("geosite:geolocation-cn", "geosite-geolocation-cn")]
[InlineData("geosite:tld-cn", "geosite-tld-cn")]
public void GenerateClientConfigContent_DirectExpectedIPs_RegionVariant_ShouldApplyExpectedRule(string domainTag,
string expectedRuleSetTag)
{
var config =
CoreConfigTestFactory.CreateConfigWithDirectExpectedIPs(ECoreType.sing_box, "192.168.0.0/16,geoip:cn");
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
{
RoutingItem = new RoutingItem
{
Id = "r-dns-direct-variant",
Remarks = "dns-direct-variant",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true, RuleType = ERuleType.DNS, OutboundTag = Global.DirectTag, Domain = [domainTag],
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
var hasExpectedRule = cfg.dns.rules?.Any(r =>
r.server == Global.SingboxDirectDNSTag
&& r.ip_cidr?.Contains("192.168.0.0/16") == true
&& r.rule_set?.Contains(expectedRuleSetTag) == true
&& r.rule_set?.Contains("geoip-cn") == true) ?? false;
hasExpectedRule.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_Hosts_ShouldPopulateHostsServerAndDomainResolver()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
config.SimpleDNSItem.Hosts = "resolver.example 1.1.1.1";
config.SimpleDNSItem.DirectDNS = "https://resolver.example/dns-query";
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box);
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
var hostsServer = cfg.dns.servers.FirstOrDefault(s => s.tag == Global.SingboxHostsDNSTag);
hostsServer.Should().NotBeNull();
hostsServer!.predefined.Should().ContainKey("resolver.example");
hostsServer.predefined!["resolver.example"].Should().Contain("1.1.1.1");
var directServer = cfg.dns.servers.FirstOrDefault(s => s.tag == Global.SingboxDirectDNSTag);
directServer.Should().NotBeNull();
directServer!.domain_resolver.Should().Be(Global.SingboxHostsDNSTag);
}
[Fact]
public void GenerateClientConfigContent_RawDnsEnabled_ShouldUseCustomDnsAndInjectLocalResolver()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
var rawDns = new Dns4Sbox
{
servers =
[
new Server4Sbox { tag = "remote", type = "udp", server = "8.8.8.8", detour = Global.ProxyTag, }
],
rules = [],
};
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
{
RawDnsItem = new DNSItem
{
Id = "dns-raw-1",
Remarks = "raw",
Enabled = true,
CoreType = ECoreType.sing_box,
NormalDNS = JsonUtils.Serialize(rawDns),
DomainDNSAddress = "1.1.1.1",
}
};
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
cfg.dns.servers.Should().Contain(s => s.tag == "remote" && s.type == "udp" && s.server == "8.8.8.8");
cfg.dns.servers.Should().Contain(s => s.tag == Global.SingboxLocalDNSTag);
cfg.dns.rules.Should().Contain(r => r.clash_mode == ERuleMode.Global.ToString());
cfg.dns.rules.Should().Contain(r => r.clash_mode == ERuleMode.Direct.ToString());
}
}
@@ -0,0 +1,539 @@
using AwesomeAssertions;
using ServiceLib.Common;
using ServiceLib.Enums;
using ServiceLib.Models;
using ServiceLib.Services.CoreConfig;
using Xunit;
namespace ServiceLib.Tests.CoreConfig.V2ray;
public class CoreConfigV2rayServiceTests
{
[Fact]
public void GenerateClientConfigContent_ShouldGenerateBasicProxyConfig()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray);
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray);
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
result.Data.Should().NotBeNull();
var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString());
v2rayConfig.Should().NotBeNull();
v2rayConfig!.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.protocol == "vmess");
v2rayConfig.inbounds.Should().Contain(i => i.protocol == nameof(EInboundProtocol.mixed));
}
[Fact]
public void GenerateClientConfigContent_PolicyGroup_ShouldExpandChildrenAndBuildBalancer()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
CoreConfigTestFactory.BindAppManagerConfig(config);
var n1 = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n1", "node-1");
var n2 = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n2", "node-2");
var group = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.Xray, "g1", "group",
[n1.IndexId, n2.IndexId]);
var context = CoreConfigTestFactory.CreateContext(config, group, ECoreType.Xray);
context.AllProxiesMap[n1.IndexId] = n1;
context.AllProxiesMap[n2.IndexId] = n2;
context.AllProxiesMap[group.IndexId] = group;
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-1-", StringComparison.Ordinal));
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-2-", StringComparison.Ordinal));
cfg.routing.balancers.Should().NotBeNull();
cfg.routing.balancers!.Should().Contain(b => b.tag == Global.ProxyTag + Global.BalancerTagSuffix);
}
[Fact]
public void GenerateClientConfigContent_ProxyChain_ShouldBuildDialerProxyChain()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
CoreConfigTestFactory.BindAppManagerConfig(config);
var n1 = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n1", "node-1");
var n2 = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n2", "node-2");
var chain = CoreConfigTestFactory.CreateProxyChainNode(ECoreType.Xray, "c1", "chain", [n1.IndexId, n2.IndexId]);
var context = CoreConfigTestFactory.CreateContext(config, chain, ECoreType.Xray);
context.AllProxiesMap[n1.IndexId] = n1;
context.AllProxiesMap[n2.IndexId] = n2;
context.AllProxiesMap[chain.IndexId] = chain;
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-", StringComparison.Ordinal));
var hasDialerChain = cfg.outbounds.Any(o =>
o.tag == Global.ProxyTag
&& o.streamSettings is not null
&& o.streamSettings.sockopt is not null
&& (o.streamSettings.sockopt.dialerProxy ?? string.Empty).StartsWith("chain-proxy-1-",
StringComparison.Ordinal));
hasDialerChain.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_PolicyGroupWithProxyChain_ShouldBuildCombinedOutbounds()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
CoreConfigTestFactory.BindAppManagerConfig(config);
var n1 = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n1", "node-1");
var n2 = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n2", "node-2");
var n3 = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n3", "node-3");
var chain = CoreConfigTestFactory.CreateProxyChainNode(ECoreType.Xray, "c1", "chain", [n1.IndexId, n2.IndexId]);
var group = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.Xray, "g1", "group",
[chain.IndexId, n3.IndexId]);
var context = CoreConfigTestFactory.CreateContext(config, group, ECoreType.Xray);
context.AllProxiesMap[n1.IndexId] = n1;
context.AllProxiesMap[n2.IndexId] = n2;
context.AllProxiesMap[n3.IndexId] = n3;
context.AllProxiesMap[chain.IndexId] = chain;
context.AllProxiesMap[group.IndexId] = group;
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-1-", StringComparison.Ordinal));
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-", StringComparison.Ordinal));
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-2-", StringComparison.Ordinal));
cfg.routing.balancers.Should().NotBeNull();
cfg.routing.balancers!.Should().Contain(b => b.tag == Global.ProxyTag + Global.BalancerTagSuffix);
}
[Fact]
public void GenerateClientConfigContent_ProxyChainWithPolicyGroup_ShouldBuildClonedChainBranches()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
CoreConfigTestFactory.BindAppManagerConfig(config);
var n1 = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n1", "node-1");
var n2 = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n2", "node-2");
var n3 = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n3", "node-3");
var group = CoreConfigTestFactory.CreatePolicyGroupNode(ECoreType.Xray, "g1", "group",
[n1.IndexId, n2.IndexId]);
var chain = CoreConfigTestFactory.CreateProxyChainNode(ECoreType.Xray, "c1", "chain",
[group.IndexId, n3.IndexId]);
var context = CoreConfigTestFactory.CreateContext(config, chain, ECoreType.Xray);
context.AllProxiesMap[n1.IndexId] = n1;
context.AllProxiesMap[n2.IndexId] = n2;
context.AllProxiesMap[n3.IndexId] = n3;
context.AllProxiesMap[group.IndexId] = group;
context.AllProxiesMap[chain.IndexId] = chain;
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-group-1-", StringComparison.Ordinal));
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-group-2-", StringComparison.Ordinal));
var proxyCloneCount = cfg.outbounds.Count(o => o.tag.StartsWith("proxy-clone-", StringComparison.Ordinal));
proxyCloneCount.Should().Be(2);
var allCloneDialersPointToGroupBranches = cfg.outbounds
.Where(o => o.tag.StartsWith("proxy-clone-", StringComparison.Ordinal))
.All(o => (o.streamSettings?.sockopt?.dialerProxy ?? string.Empty).StartsWith("chain-proxy-1-group-",
StringComparison.Ordinal));
allCloneDialersPointToGroupBranches.Should().BeTrue();
cfg.routing.balancers.Should().NotBeNull();
cfg.routing.balancers!.Should().Contain(b => b.tag == Global.ProxyTag + Global.BalancerTagSuffix);
}
[Fact]
public void GenerateClientConfigContent_RoutingSplit_DirectAndBlock_ShouldApplyRules()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray) with
{
RoutingItem = new RoutingItem
{
Id = "r-split-1",
Remarks = "split-direct-block",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true,
RuleType = ERuleType.Routing,
OutboundTag = Global.DirectTag,
Domain = ["full:direct.example.com"],
},
new()
{
Enabled = true,
RuleType = ERuleType.Routing,
OutboundTag = Global.BlockTag,
Domain = ["full:block.example.com"],
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
var hasDirectRule = cfg.routing.rules.Any(r =>
r.domain != null
&& r.domain.Contains("full:direct.example.com")
&& r.outboundTag == Global.DirectTag);
hasDirectRule.Should().BeTrue();
var hasBlockRule = cfg.routing.rules.Any(r =>
r.domain != null
&& r.domain.Contains("full:block.example.com")
&& r.outboundTag == Global.BlockTag);
hasBlockRule.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_RoutingSplit_ByRemark_ShouldGenerateTargetOutbound()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "n-main", "main");
var routeNode = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "n-route", "route-node");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray) with
{
RoutingItem = new RoutingItem
{
Id = "r-split-2",
Remarks = "split-remark",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true,
RuleType = ERuleType.Routing,
OutboundTag = routeNode.Remarks,
Domain = ["full:route.example.com"],
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
context.AllProxiesMap[$"remark:{routeNode.Remarks}"] = routeNode;
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
var expectedPrefix = $"{routeNode.IndexId}-{Global.ProxyTag}-{routeNode.Remarks}";
cfg.outbounds.Should().Contain(o => o.tag.StartsWith(expectedPrefix, StringComparison.Ordinal));
var hasRouteRule = cfg.routing.rules.Any(r =>
r.domain != null
&& r.domain.Contains("full:route.example.com")
&& (r.outboundTag ?? string.Empty).StartsWith(expectedPrefix, StringComparison.Ordinal));
hasRouteRule.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_DirectExpectedIPs_ShouldApplyExpectedIPsToDirectDnsServer()
{
var config = CoreConfigTestFactory.CreateConfigWithDirectExpectedIPs(ECoreType.Xray, "192.168.0.0/16,geoip:cn");
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray) with
{
RoutingItem = new RoutingItem
{
Id = "r-dns-direct-expected",
Remarks = "dns-direct-expected",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true,
RuleType = ERuleType.DNS,
OutboundTag = Global.DirectTag,
Domain = ["geosite:cn"],
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
var dns = JsonUtils.Deserialize<Dns4Ray>(JsonUtils.Serialize(cfg.dns))!;
var dnsServers = dns.servers
.Select(s => JsonUtils.Deserialize<DnsServer4Ray>(JsonUtils.Serialize(s)))
.Where(s => s is not null)
.Cast<DnsServer4Ray>()
.ToList();
var hasExpectedServer = dnsServers.Any(s =>
(s.tag ?? string.Empty).StartsWith(Global.DirectDnsTag, StringComparison.Ordinal)
&& s.domains?.Contains("geosite:cn") == true
&& s.expectedIPs?.Contains("192.168.0.0/16") == true
&& s.expectedIPs?.Contains("geoip:cn") == true);
hasExpectedServer.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_BootstrapDNS_ShouldApplyToDnsServerDomains()
{
var bootstrapDns = "8.8.8.8";
var config = CoreConfigTestFactory.CreateConfigWithBootstrapDNS(ECoreType.Xray, bootstrapDns);
config.SimpleDNSItem.DirectDNS = "https://dns-direct.example/dns-query";
config.SimpleDNSItem.RemoteDNS = "https://dns-remote.example/dns-query";
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray);
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
var dns = JsonUtils.Deserialize<Dns4Ray>(JsonUtils.Serialize(cfg.dns))!;
var dnsServers = dns.servers
.Select(s => JsonUtils.Deserialize<DnsServer4Ray>(JsonUtils.Serialize(s)))
.Where(s => s is not null)
.Cast<DnsServer4Ray>()
.ToList();
var hasBootstrapServer = dnsServers.Any(s =>
s.address == bootstrapDns
&& s.domains?.Contains("full:dns-direct.example") == true
&& s.domains?.Contains("full:dns-remote.example") == true);
hasBootstrapServer.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_DnsFallback_LastRuleDirect_ShouldUseDirectDnsServers()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
config.SimpleDNSItem.DirectDNS = "1.1.1.1";
config.SimpleDNSItem.RemoteDNS = "9.9.9.9";
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray) with
{
RoutingItem = new RoutingItem
{
Id = "r-direct-final",
Remarks = "direct-final",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true,
RuleType = ERuleType.Routing,
OutboundTag = Global.DirectTag,
Ip = ["0.0.0.0/0"],
Port = "0-65535",
Network = "tcp,udp",
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
var dns = JsonUtils.Deserialize<Dns4Ray>(JsonUtils.Serialize(cfg.dns))!;
var dnsServers = dns.servers
.Select(s => JsonUtils.Deserialize<DnsServer4Ray>(JsonUtils.Serialize(s)))
.Where(s => s is not null)
.Cast<DnsServer4Ray>()
.ToList();
var hasDirectFallback = dnsServers.Any(s =>
(s.tag ?? string.Empty).StartsWith(Global.DirectDnsTag, StringComparison.Ordinal)
&& s.address == "1.1.1.1");
hasDirectFallback.Should().BeTrue();
var hasRemoteFallback = dnsServers.Any(s => s.address == "9.9.9.9");
hasRemoteFallback.Should().BeFalse();
}
[Fact]
public void GenerateClientConfigContent_DirectExpectedIPs_NonMatchingRegion_ShouldNotApplyExpectedIPs()
{
var config = CoreConfigTestFactory.CreateConfigWithDirectExpectedIPs(ECoreType.Xray, "192.168.0.0/16,geoip:cn");
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray) with
{
RoutingItem = new RoutingItem
{
Id = "r-dns-direct-unmatched",
Remarks = "dns-direct-unmatched",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true,
RuleType = ERuleType.DNS,
OutboundTag = Global.DirectTag,
Domain = ["geosite:us"],
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
var dns = JsonUtils.Deserialize<Dns4Ray>(JsonUtils.Serialize(cfg.dns))!;
var dnsServers = dns.servers
.Select(s => JsonUtils.Deserialize<DnsServer4Ray>(JsonUtils.Serialize(s)))
.Where(s => s is not null)
.Cast<DnsServer4Ray>()
.ToList();
var hasExpectedIPs = dnsServers.Any(s =>
s.expectedIPs?.Contains("192.168.0.0/16") == true
|| s.expectedIPs?.Contains("geoip:cn") == true);
hasExpectedIPs.Should().BeFalse();
}
[Theory]
[InlineData("geosite:cn")]
[InlineData("geosite:geolocation-cn")]
[InlineData("geosite:tld-cn")]
public void GenerateClientConfigContent_DirectExpectedIPs_RegionVariant_ShouldApplyExpectedIPs(string domainTag)
{
var config = CoreConfigTestFactory.CreateConfigWithDirectExpectedIPs(ECoreType.Xray, "192.168.0.0/16,geoip:cn");
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray) with
{
RoutingItem = new RoutingItem
{
Id = "r-dns-direct-variant",
Remarks = "dns-direct-variant",
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new()
{
Enabled = true, RuleType = ERuleType.DNS, OutboundTag = Global.DirectTag, Domain = [domainTag],
}
}),
DomainStrategy = Global.AsIs,
DomainStrategy4Singbox = string.Empty,
}
};
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
var dns = JsonUtils.Deserialize<Dns4Ray>(JsonUtils.Serialize(cfg.dns))!;
var dnsServers = dns.servers
.Select(s => JsonUtils.Deserialize<DnsServer4Ray>(JsonUtils.Serialize(s)))
.Where(s => s is not null)
.Cast<DnsServer4Ray>()
.ToList();
var hasExpectedServer = dnsServers.Any(s =>
(s.tag ?? string.Empty).StartsWith(Global.DirectDnsTag, StringComparison.Ordinal)
&& s.domains?.Contains(domainTag) == true
&& s.expectedIPs?.Contains("192.168.0.0/16") == true
&& s.expectedIPs?.Contains("geoip:cn") == true);
hasExpectedServer.Should().BeTrue();
}
[Fact]
public void GenerateClientConfigContent_Hosts_ShouldPopulateDnsHosts()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
config.SimpleDNSItem.Hosts = "resolver.example 1.1.1.1";
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray);
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
var dns = JsonUtils.Deserialize<Dns4Ray>(JsonUtils.Serialize(cfg.dns))!;
dns.hosts.Should().NotBeNull();
dns.hosts!.Should().ContainKey("resolver.example");
JsonUtils.Serialize(dns.hosts!["resolver.example"]).Should().Contain("1.1.1.1");
}
[Fact]
public void GenerateClientConfigContent_RawDnsEnabled_ShouldUseCustomDnsConfig()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "n-main", "main");
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray) with
{
RawDnsItem = new DNSItem
{
Id = "dns-raw-1",
Remarks = "raw",
Enabled = true,
CoreType = ECoreType.Xray,
NormalDNS = "{\"servers\":[\"8.8.8.8\"],\"hosts\":{\"raw.example\":\"1.1.1.1\"}}",
DomainStrategy4Freedom = "UseIPv4",
}
};
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
result.Success.Should().BeTrue();
var cfg = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
var dns = JsonUtils.Deserialize<Dns4Ray>(JsonUtils.Serialize(cfg.dns))!;
JsonUtils.Serialize(dns.servers).Should().Contain("8.8.8.8");
dns.hosts.Should().NotBeNull();
dns.hosts!.Should().ContainKey("raw.example");
JsonUtils.Serialize(dns.hosts!["raw.example"]).Should().Contain("1.1.1.1");
var directOutbound = cfg.outbounds.FirstOrDefault(o => o.tag == Global.DirectTag && o.protocol == "freedom");
directOutbound.Should().NotBeNull();
directOutbound!.settings.domainStrategy.Should().Be("UseIPv4");
}
}
@@ -1,228 +0,0 @@
using System.Text.Json.Nodes;
using ServiceLib;
using ServiceLib.Enums;
using ServiceLib.Models;
using ServiceLib.Services.CoreConfig;
using Xunit;
namespace ServiceLib.Tests;
public class CoreConfigV2rayServiceTests
{
private const string SendThrough = "198.51.100.10";
[Fact]
public void GenerateClientConfigContent_OnlyAppliesSendThroughToRemoteProxyOutbounds()
{
var node = CreateProxyNode("proxy-1", "198.51.100.1", 443);
var service = new CoreConfigV2rayService(CreateContext(node));
var result = service.GenerateClientConfigContent();
Assert.True(result.Success);
var outbounds = GetOutbounds(result.Data?.ToString());
var proxyOutbound = outbounds.Single(outbound => outbound["tag"]!.GetValue<string>() == Global.ProxyTag);
var directOutbound = outbounds.Single(outbound => outbound["tag"]!.GetValue<string>() == Global.DirectTag);
var blockOutbound = outbounds.Single(outbound => outbound["tag"]!.GetValue<string>() == Global.BlockTag);
Assert.Equal(SendThrough, proxyOutbound["sendThrough"]?.GetValue<string>());
Assert.Null(directOutbound["sendThrough"]);
Assert.Null(blockOutbound["sendThrough"]);
}
[Fact]
public void GenerateClientConfigContent_OnlyAppliesSendThroughToChainExitOutbounds()
{
var exitNode = CreateProxyNode("exit", "198.51.100.2", 443);
var entryNode = CreateProxyNode("entry", "198.51.100.3", 443);
var chainNode = CreateChainNode("chain", exitNode, entryNode);
var service = new CoreConfigV2rayService(CreateContext(
chainNode,
allProxiesMap: new Dictionary<string, ProfileItem>
{
[exitNode.IndexId] = exitNode,
[entryNode.IndexId] = entryNode,
}));
var result = service.GenerateClientConfigContent();
Assert.True(result.Success);
var outbounds = GetOutbounds(result.Data?.ToString())
.Where(outbound => outbound["protocol"]?.GetValue<string>() is not ("freedom" or "blackhole" or "dns"))
.ToList();
var sendThroughOutbounds = outbounds
.Where(outbound => outbound["sendThrough"]?.GetValue<string>() == SendThrough)
.ToList();
var chainedOutbounds = outbounds
.Where(outbound => outbound["streamSettings"]?["sockopt"]?["dialerProxy"] is not null)
.ToList();
Assert.Single(sendThroughOutbounds);
Assert.All(chainedOutbounds, outbound => Assert.Null(outbound["sendThrough"]));
}
[Fact]
public void GenerateClientConfigContent_DoesNotApplySendThroughToTunRelayLoopbackOutbound()
{
var node = CreateProxyNode("proxy-1", "198.51.100.4", 443);
var config = CreateConfig();
config.TunModeItem.EnableLegacyProtect = false;
var service = new CoreConfigV2rayService(CreateContext(
node,
config,
isTunEnabled: true,
tunProtectSsPort: 10811,
proxyRelaySsPort: 10812));
var result = service.GenerateClientConfigContent();
Assert.True(result.Success);
var outbounds = GetOutbounds(result.Data?.ToString());
Assert.DoesNotContain(outbounds, outbound => outbound["sendThrough"]?.GetValue<string>() == SendThrough);
}
private static CoreConfigContext CreateContext(
ProfileItem node,
Config? config = null,
Dictionary<string, ProfileItem>? allProxiesMap = null,
bool isTunEnabled = false,
int tunProtectSsPort = 0,
int proxyRelaySsPort = 0)
{
return new CoreConfigContext
{
Node = node,
RunCoreType = ECoreType.Xray,
AppConfig = config ?? CreateConfig(),
AllProxiesMap = allProxiesMap ?? new(),
SimpleDnsItem = new SimpleDNSItem(),
IsTunEnabled = isTunEnabled,
TunProtectSocksPort = tunProtectSsPort,
ProxyRelaySocksPort = proxyRelaySsPort,
};
}
private static Config CreateConfig()
{
return new Config
{
IndexId = string.Empty,
SubIndexId = string.Empty,
CoreBasicItem = new()
{
LogEnabled = false,
Loglevel = "warning",
MuxEnabled = false,
DefAllowInsecure = false,
DefFingerprint = Global.Fingerprints.First(),
DefUserAgent = string.Empty,
SendThrough = SendThrough,
EnableFragment = false,
EnableCacheFile4Sbox = true,
},
TunModeItem = new()
{
EnableTun = false,
AutoRoute = true,
StrictRoute = true,
Stack = string.Empty,
Mtu = 9000,
EnableIPv6Address = false,
IcmpRouting = Global.TunIcmpRoutingPolicies.First(),
EnableLegacyProtect = false,
},
KcpItem = new(),
GrpcItem = new(),
RoutingBasicItem = new()
{
DomainStrategy = Global.DomainStrategies.First(),
DomainStrategy4Singbox = Global.DomainStrategies4Sbox.First(),
RoutingIndexId = string.Empty,
},
GuiItem = new(),
MsgUIItem = new(),
UiItem = new()
{
CurrentLanguage = "en",
CurrentFontFamily = string.Empty,
MainColumnItem = [],
WindowSizeItem = [],
},
ConstItem = new(),
SpeedTestItem = new(),
Mux4RayItem = new()
{
Concurrency = 8,
XudpConcurrency = 8,
XudpProxyUDP443 = "reject",
},
Mux4SboxItem = new()
{
Protocol = string.Empty,
},
HysteriaItem = new(),
ClashUIItem = new()
{
ConnectionsColumnItem = [],
},
SystemProxyItem = new(),
WebDavItem = new(),
CheckUpdateItem = new(),
Fragment4RayItem = null,
Inbound = [new InItem
{
Protocol = EInboundProtocol.socks.ToString(),
LocalPort = 10808,
UdpEnabled = true,
SniffingEnabled = true,
RouteOnly = false,
}],
GlobalHotkeys = [],
CoreTypeItem = [],
SimpleDNSItem = new(),
};
}
private static ProfileItem CreateProxyNode(string indexId, string address, int port)
{
return new ProfileItem
{
IndexId = indexId,
Remarks = indexId,
ConfigType = EConfigType.SOCKS,
CoreType = ECoreType.Xray,
Address = address,
Port = port,
};
}
private static ProfileItem CreateChainNode(string indexId, params ProfileItem[] nodes)
{
var chainNode = new ProfileItem
{
IndexId = indexId,
Remarks = indexId,
ConfigType = EConfigType.ProxyChain,
CoreType = ECoreType.Xray,
};
chainNode.SetProtocolExtra(new ProtocolExtraItem
{
ChildItems = string.Join(',', nodes.Select(node => node.IndexId)),
});
return chainNode;
}
private static List<JsonObject> GetOutbounds(string? json)
{
var root = JsonNode.Parse(json ?? throw new InvalidOperationException("Config JSON is missing"))?.AsObject()
?? throw new InvalidOperationException("Failed to parse config JSON");
return root["outbounds"]?.AsArray().Select(node => node!.AsObject()).ToList()
?? throw new InvalidOperationException("Config JSON does not contain outbounds");
}
}
@@ -0,0 +1,173 @@
using AwesomeAssertions;
using ServiceLib.Enums;
using ServiceLib.Handler.Fmt;
using ServiceLib.Models;
using Xunit;
namespace ServiceLib.Tests.Fmt;
public class FmtHandlerTests
{
[Fact]
public void GetShareUriAndResolveConfig_Vmess_ShouldRoundTripBasicFields()
{
var source = CreateVmessProfile();
var resolved = ExportThenImport(source);
resolved.ConfigType.Should().Be(EConfigType.VMess);
resolved.Remarks.Should().Be(source.Remarks);
resolved.Address.Should().Be(source.Address);
resolved.Port.Should().Be(source.Port);
resolved.Password.Should().Be(source.Password);
resolved.GetProtocolExtra().AlterId.Should().Be(source.GetProtocolExtra().AlterId);
}
[Fact]
public void GetShareUriAndResolveConfig_Vless_ShouldRoundTripBasicFields()
{
var source = CreateVlessProfile();
var resolved = ExportThenImport(source);
resolved.ConfigType.Should().Be(EConfigType.VLESS);
resolved.Remarks.Should().Be(source.Remarks);
resolved.Address.Should().Be(source.Address);
resolved.Port.Should().Be(source.Port);
resolved.Password.Should().Be(source.Password);
resolved.GetProtocolExtra().VlessEncryption.Should().Be(Global.None);
}
[Fact]
public void GetShareUriAndResolveConfig_Shadowsocks_ShouldRoundTripBasicFields()
{
var source = CreateShadowsocksProfile();
var resolved = ExportThenImport(source);
resolved.ConfigType.Should().Be(EConfigType.Shadowsocks);
resolved.Remarks.Should().Be(source.Remarks);
resolved.Address.Should().Be(source.Address);
resolved.Port.Should().Be(source.Port);
resolved.Password.Should().Be(source.Password);
resolved.GetProtocolExtra().SsMethod.Should().Be(source.GetProtocolExtra().SsMethod);
}
[Fact]
public void GetShareUriAndResolveConfig_Socks_ShouldRoundTripBasicFields()
{
var source = CreateSocksProfile();
var resolved = ExportThenImport(source);
resolved.ConfigType.Should().Be(EConfigType.SOCKS);
resolved.Remarks.Should().Be(source.Remarks);
resolved.Address.Should().Be(source.Address);
resolved.Port.Should().Be(source.Port);
resolved.Username.Should().Be(source.Username);
resolved.Password.Should().Be(source.Password);
}
[Fact]
public void ResolveConfig_UnsupportedProtocol_ShouldReturnNull()
{
var resolved = FmtHandler.ResolveConfig("not-a-share-uri", out var msg);
resolved.Should().BeNull();
msg.Should().NotBeNullOrWhiteSpace();
}
[Fact]
public void GetShareUri_UnsupportedConfigType_ShouldReturnNull()
{
var item = new ProfileItem { ConfigType = EConfigType.PolicyGroup, Remarks = "group", };
var uri = FmtHandler.GetShareUri(item);
uri.Should().BeNull();
}
private static ProfileItem ExportThenImport(ProfileItem source)
{
var uri = FmtHandler.GetShareUri(source);
uri.Should().NotBeNullOrWhiteSpace();
uri!.StartsWith(Global.ProtocolShares[source.ConfigType], StringComparison.OrdinalIgnoreCase).Should()
.BeTrue();
var resolved = FmtHandler.ResolveConfig(uri, out var msg);
resolved.Should().NotBeNull($"uri: {uri}, msg: {msg}");
return resolved!;
}
private static ProfileItem CreateVmessProfile()
{
var item = new ProfileItem
{
ConfigType = EConfigType.VMess,
Remarks = "vmess demo",
Address = "example.com",
Port = 443,
Password = Guid.NewGuid().ToString(),
Network = nameof(ETransport.raw),
StreamSecurity = string.Empty,
};
item.SetProtocolExtra(new ProtocolExtraItem { AlterId = "0", VmessSecurity = Global.DefaultSecurity, });
item.SetTransportExtra(new TransportExtraItem { RawHeaderType = Global.None, });
return item;
}
private static ProfileItem CreateVlessProfile()
{
var item = new ProfileItem
{
ConfigType = EConfigType.VLESS,
Remarks = "vless demo",
Address = "vless.example",
Port = 8443,
Password = Guid.NewGuid().ToString(),
Network = nameof(ETransport.raw),
StreamSecurity = string.Empty,
};
item.SetProtocolExtra(new ProtocolExtraItem { VlessEncryption = Global.None, });
item.SetTransportExtra(new TransportExtraItem { RawHeaderType = Global.None, });
return item;
}
private static ProfileItem CreateShadowsocksProfile()
{
var item = new ProfileItem
{
ConfigType = EConfigType.Shadowsocks,
Remarks = "ss demo",
Address = "1.2.3.4",
Port = 8388,
Password = "pass123",
Network = nameof(ETransport.raw),
StreamSecurity = string.Empty,
};
item.SetProtocolExtra(new ProtocolExtraItem { SsMethod = "aes-128-gcm", });
item.SetTransportExtra(new TransportExtraItem { RawHeaderType = Global.None, });
return item;
}
private static ProfileItem CreateSocksProfile()
{
return new ProfileItem
{
ConfigType = EConfigType.SOCKS,
Remarks = "socks demo",
Address = "127.0.0.1",
Port = 1080,
Username = "user",
Password = "pass",
};
}
}
@@ -1,17 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AwesomeAssertions" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit.v3" />
</ItemGroup>
<ItemGroup>
@@ -0,0 +1,5 @@
global using System.Buffers.Binary;
global using System.Diagnostics;
global using System.Net;
global using System.Net.Sockets;
global using System.Text;
@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
</PropertyGroup>
</Project>
@@ -0,0 +1,420 @@
namespace ServiceLib.UdpTest;
public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposable
{
private TcpClient _tcpClient;
private UdpClient _udpClient;
private IPEndPoint _relayEndPoint;
private bool _initialized = false;
/// <summary>
/// Send UDP data to a remote endpoint (IP address)
/// </summary>
public async Task SendAsync(IPEndPoint remote, byte[] data)
{
var addrData = new Socks5AddressData
{
AddressType = remote.Address.AddressFamily == AddressFamily.InterNetwork
? Socks5AddressData.AddrTypeIPv4
: Socks5AddressData.AddrTypeIPv6,
Host = remote.Address.ToString(),
Port = (ushort)remote.Port
};
var packet = BuildSocks5UdpPacket(addrData, data);
await _udpClient.SendAsync(packet, packet.Length, _relayEndPoint);
}
/// <summary>
/// Send UDP data to a remote endpoint (domain name or IP address)
/// </summary>
/// <param name="host">Domain name or IP address</param>
/// <param name="port">Port number</param>
/// <param name="data">Data to send</param>
public async Task SendAsync(string host, ushort port, byte[] data)
{
var addrData = new Socks5AddressData();
// Try to parse as IP address first
if (IPAddress.TryParse(host, out var ipAddr))
{
addrData.AddressType = ipAddr.AddressFamily == AddressFamily.InterNetwork
? Socks5AddressData.AddrTypeIPv4
: Socks5AddressData.AddrTypeIPv6;
addrData.Host = ipAddr.ToString();
}
else
{
// Treat as domain name
addrData.AddressType = Socks5AddressData.AddrTypeDomain;
addrData.Host = host;
}
addrData.Port = port;
var packet = BuildSocks5UdpPacket(addrData, data);
await _udpClient.SendAsync(packet, packet.Length, _relayEndPoint);
}
/// <summary>
/// Receive UDP data from remote endpoint
/// </summary>
/// <param name="cancellationToken">Cancellation token to cancel the receive operation</param>
/// <returns>Remote endpoint information and received data</returns>
public async Task<(Socks5RemoteEndpoint Remote, byte[] Data)> ReceiveAsync(
CancellationToken cancellationToken = default)
{
var result = await _udpClient.ReceiveAsync(cancellationToken).ConfigureAwait(false);
var (remote, payload) = ParseSocks5UdpPacket(result.Buffer);
return (remote, payload);
}
/// <summary>
/// Represents a remote endpoint that can be either an IP address or a domain name
/// </summary>
public class Socks5RemoteEndpoint(string host, ushort port, bool isDomain)
{
public string Host { get; set; } = host;
public ushort Port { get; set; } = port;
public bool IsDomain { get; set; } = isDomain;
}
private static byte[] BuildSocks5UdpPacket(Socks5AddressData addressData, byte[] data)
{
using var ms = new MemoryStream();
// RSV (2 bytes) + FRAG (1 byte) - Reserved and Fragment fields
ms.WriteByte(0x00);
ms.WriteByte(0x00);
ms.WriteByte(0x00);
// Write address (ATYP + address + port)
ms.Write(addressData.ToBytes());
// User data payload
ms.Write(data);
return ms.ToArray();
}
private static (Socks5RemoteEndpoint Remote, byte[] Data) ParseSocks5UdpPacket(byte[] packet)
{
if (packet.Length < 10) // Minimum length: RSV(2) + FRAG(1) + ATYP(1) + IPv4(4) + Port(2) = 10
{
throw new ArgumentException("Invalid SOCKS5 UDP packet: too short");
}
var offset = 0;
// RSV (2 bytes) - Reserved field, skip
offset += 2;
// FRAG (1 byte) - Fragment number, currently only support 0 (no fragmentation)
var frag = packet[offset++];
if (frag != 0x00)
{
throw new NotSupportedException("SOCKS5 UDP fragmentation is not supported");
}
// ATYP (1 byte) - Address type
var addressType = packet[offset++];
string host;
int addressLength;
bool isDomain;
switch (addressType)
{
case Socks5AddressData.AddrTypeIPv4:
if (packet.Length < offset + 4)
{
throw new ArgumentException("Invalid SOCKS5 UDP packet: IPv4 address incomplete");
}
var ipv4Bytes = new byte[4];
Array.Copy(packet, offset, ipv4Bytes, 0, 4);
host = new IPAddress(ipv4Bytes).ToString();
addressLength = 4;
isDomain = false;
break;
case Socks5AddressData.AddrTypeIPv6:
if (packet.Length < offset + 16)
{
throw new ArgumentException("Invalid SOCKS5 UDP packet: IPv6 address incomplete");
}
var ipv6Bytes = new byte[16];
Array.Copy(packet, offset, ipv6Bytes, 0, 16);
host = new IPAddress(ipv6Bytes).ToString();
addressLength = 16;
isDomain = false;
break;
case Socks5AddressData.AddrTypeDomain:
if (packet.Length < offset + 1)
{
throw new ArgumentException("Invalid SOCKS5 UDP packet: domain length missing");
}
var domainLength = packet[offset++];
if (packet.Length < offset + domainLength)
{
throw new ArgumentException("Invalid SOCKS5 UDP packet: domain incomplete");
}
host = Encoding.ASCII.GetString(packet, offset, domainLength);
addressLength = domainLength;
isDomain = true;
break;
default:
throw new NotSupportedException($"Unsupported SOCKS5 address type: {addressType}");
}
offset += addressLength;
// Port (2 bytes, big-endian)
if (packet.Length < offset + 2)
{
throw new ArgumentException("Invalid SOCKS5 UDP packet: port incomplete");
}
var port = BinaryPrimitives.ReadUInt16BigEndian(packet.AsSpan(offset, 2));
offset += 2;
// Data (remaining bytes)
var dataLength = packet.Length - offset;
var data = new byte[dataLength];
if (dataLength > 0)
{
Array.Copy(packet, offset, data, 0, dataLength);
}
// Create remote endpoint without DNS resolution
var remote = new Socks5RemoteEndpoint(host, port, isDomain);
return (remote, data);
}
public void Dispose()
{
_tcpClient.Dispose();
_udpClient.Dispose();
}
#region SOCKS5 Connection Handling
private const byte Socks5Version = 0x05;
private const byte SocksCmdUdpAssociate = 0x03;
public async Task<bool> EstablishUdpAssociationAsync(CancellationToken cancellationToken)
{
if (_initialized)
{
Dispose();
_initialized = false;
}
_udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
_tcpClient = new TcpClient();
try
{
await _tcpClient.ConnectAsync(socks5Host, socks5TcpPort, cancellationToken).ConfigureAwait(false);
}
catch (SocketException)
{
return false;
}
var tcpControlStream = _tcpClient.GetStream();
byte[] handshakeRequest = [Socks5Version, 0x01, 0x00];
await tcpControlStream.WriteAsync(handshakeRequest, cancellationToken).ConfigureAwait(false);
var handshakeResponse = new byte[2];
if (await tcpControlStream.ReadAsync(handshakeResponse, cancellationToken).ConfigureAwait(false) < 2 ||
handshakeResponse[0] != Socks5Version || handshakeResponse[1] != 0x00)
{
return false;
}
var clientAddrForSocks = new Socks5AddressData
{
AddressType = Socks5AddressData.AddrTypeIPv4,
Host = "0.0.0.0",
Port = 0
};
using var udpAssociateReqMs = new MemoryStream();
udpAssociateReqMs.WriteByte(Socks5Version);
udpAssociateReqMs.WriteByte(SocksCmdUdpAssociate);
udpAssociateReqMs.WriteByte(0x00);
udpAssociateReqMs.Write(clientAddrForSocks.ToBytes());
await tcpControlStream.WriteAsync(udpAssociateReqMs.ToArray(), cancellationToken).ConfigureAwait(false);
var verRepRsv = new byte[3];
if (await tcpControlStream.ReadAsync(verRepRsv, cancellationToken).ConfigureAwait(false) < 3 ||
verRepRsv[0] != Socks5Version || verRepRsv[1] != 0x00)
{
return false;
}
var proxyRelaySocksAddr =
await Socks5AddressData.ParseAsync(tcpControlStream, cancellationToken).ConfigureAwait(false);
if (proxyRelaySocksAddr == null || !IPAddress.TryParse(proxyRelaySocksAddr.Host, out var proxyRelayIp))
{
return false;
}
_relayEndPoint = new IPEndPoint(proxyRelayIp, proxyRelaySocksAddr.Port);
_initialized = true;
return true;
}
#endregion SOCKS5 Connection Handling
#region SOCKS5 Address Handling
private class Socks5AddressData
{
public const byte AddrTypeIPv4 = 0x01;
public const byte AddrTypeDomain = 0x03;
public const byte AddrTypeIPv6 = 0x04;
public byte AddressType { get; set; }
public string Host { get; set; } = string.Empty;
public ushort Port { get; set; }
public byte[] ToBytes()
{
using var ms = new MemoryStream();
ms.WriteByte(AddressType);
switch (AddressType)
{
case AddrTypeIPv4:
if (IPAddress.TryParse(Host, out var ip) && ip.AddressFamily == AddressFamily.InterNetwork)
{
ms.Write(ip.GetAddressBytes(), 0, 4);
}
else
{
ms.Write([0, 0, 0, 0]);
}
break;
case AddrTypeDomain:
if (string.IsNullOrEmpty(Host))
{
ms.WriteByte(0);
}
else
{
var domainBytes = Encoding.ASCII.GetBytes(Host);
ms.WriteByte((byte)domainBytes.Length);
ms.Write(domainBytes);
}
break;
case AddrTypeIPv6:
if (IPAddress.TryParse(Host, out var ip6) && ip6.AddressFamily == AddressFamily.InterNetworkV6)
{
ms.Write(ip6.GetAddressBytes(), 0, 16);
}
else
{
ms.Write(new byte[16]);
}
break;
default:
throw new NotSupportedException($"SOCKS5 address type {AddressType} not supported.");
}
var portBytes = new byte[2];
BinaryPrimitives.WriteUInt16BigEndian(portBytes, Port);
ms.Write(portBytes);
return ms.ToArray();
}
public static async Task<Socks5AddressData?> ParseAsync(Stream stream, CancellationToken ct)
{
var addr = new Socks5AddressData();
var typeByte = new byte[1];
try
{
if (await stream.ReadAsync(typeByte.AsMemory(0, 1), ct).ConfigureAwait(false) < 1)
{
return null;
}
addr.AddressType = typeByte[0];
switch (addr.AddressType)
{
case AddrTypeIPv4:
var ipv4Bytes = new byte[4];
if (await stream.ReadAsync(ipv4Bytes.AsMemory(0, 4), ct).ConfigureAwait(false) < 4)
{
return null;
}
addr.Host = new IPAddress(ipv4Bytes).ToString();
break;
case AddrTypeDomain:
var lenByte = new byte[1];
if (await stream.ReadAsync(lenByte.AsMemory(0, 1), ct).ConfigureAwait(false) < 1)
{
return null;
}
if (lenByte[0] == 0)
{
addr.Host = string.Empty;
}
else
{
var domainBytes = new byte[lenByte[0]];
if (await stream.ReadAsync(domainBytes.AsMemory(0, domainBytes.Length), ct)
.ConfigureAwait(false) < domainBytes.Length)
{
return null;
}
addr.Host = Encoding.ASCII.GetString(domainBytes);
}
break;
case AddrTypeIPv6:
var ipv6Bytes = new byte[16];
if (await stream.ReadAsync(ipv6Bytes.AsMemory(0, 16), ct).ConfigureAwait(false) < 16)
{
return null;
}
addr.Host = new IPAddress(ipv6Bytes).ToString();
break;
default:
return null;
}
var portBytes = new byte[2];
if (await stream.ReadAsync(portBytes.AsMemory(0, 2), ct).ConfigureAwait(false) < 2)
{
return null;
}
addr.Port = BinaryPrimitives.ReadUInt16BigEndian(portBytes);
return addr;
}
catch (Exception ex) when (ex is IOException or ObjectDisposedException)
{
return null;
}
}
}
#endregion SOCKS5 Address Handling
}
@@ -0,0 +1,77 @@
namespace ServiceLib.UdpTest.Tester;
public class DnsService : IUdpTest
{
private const int DnsDefaultPort = 53;
private const string DnsDefaultServer = "8.8.8.8"; // Google Public DNS
private static readonly byte[] DnsQueryPacket =
[
// Header: ID=0x1234, Standard query with RD set, QDCOUNT=1
0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// Question: www.google.com, Type A, Class IN
0x03, 0x77, 0x77, 0x77, 0x06, 0x67, 0x6F, 0x6F,
0x67, 0x6C, 0x65, 0x03, 0x63, 0x6F, 0x6D, 0x00,
0x00, 0x01, 0x00, 0x01
];
public byte[] BuildUdpRequestPacket()
{
return (byte[])DnsQueryPacket.Clone();
}
public bool VerifyAndExtractUdpResponse(byte[] dnsResponseBytes)
{
if (dnsResponseBytes.Length < 12)
{
return false;
}
try
{
// Check transaction ID (should match 0x1234)
var transactionId = BinaryPrimitives.ReadUInt16BigEndian(dnsResponseBytes.AsSpan(0, 2));
if (transactionId != 0x1234)
{
return false;
}
// Check flags - should be a response (QR=1)
var flags = BinaryPrimitives.ReadUInt16BigEndian(dnsResponseBytes.AsSpan(2, 2));
if ((flags & 0x8000) == 0)
{
return false; // Not a response
}
// Check response code (RCODE) - should be 0 (no error)
if ((flags & 0x000F) != 0)
{
return false; // DNS error
}
// Check answer count
var answerCount = BinaryPrimitives.ReadUInt16BigEndian(dnsResponseBytes.AsSpan(6, 2));
if (answerCount == 0)
{
return false; // No answers
}
return true;
}
catch
{
return false;
}
}
public ushort GetDefaultTargetPort()
{
return DnsDefaultPort;
}
public string GetDefaultTargetHost()
{
return DnsDefaultServer;
}
}
@@ -0,0 +1,12 @@
namespace ServiceLib.UdpTest.Tester;
public interface IUdpTest
{
public byte[] BuildUdpRequestPacket();
public bool VerifyAndExtractUdpResponse(byte[] udpResponseBytes);
public ushort GetDefaultTargetPort();
public string GetDefaultTargetHost();
}
@@ -0,0 +1,84 @@
namespace ServiceLib.UdpTest.Tester;
public class McBeService : IUdpTest
{
private const int McBeDefaultPort = 19132;
private const string McBeDefaultServer = "pms.mc-complex.com";
// 0x01 | client alive time in ms (unsigned long long) | magic | client GUID
private static readonly byte[] McBeQueryPacket =
[
// 0x01
0x01,
// Client alive time (1000 ms)
0x27, 0xC4, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00,
// Magic
0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE,
0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78,
// Client GUID (random 16 bytes)
0x66, 0x0E, 0xAB, 0xBC, 0x61, 0x0D, 0x1F, 0x4E,
0xA4, 0x40, 0x8C, 0x65, 0xC1, 0xBE, 0xF5, 0x4B
];
private static readonly byte[] McBeMagicBytes =
[
0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE,
0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78
];
private static readonly List<string> ValidGameModes =
[
"Survival",
"Creative",
"Adventure",
"Spectator"
];
public byte[] BuildUdpRequestPacket()
{
return (byte[])McBeQueryPacket.Clone();
}
public bool VerifyAndExtractUdpResponse(byte[] mcbeResponseBytes)
{
// 0x1c | client alive time in ms (recorded from previous ping) |
// server GUID | Magic | string length | Edition
//
// Edition Example:
//
// MCPE;Dedicated Server;527;1.19.1;0;10;13253860892328930865;Bedrock level;Survival;1;19132;19133;
if (mcbeResponseBytes.Length < 48)
{
return false;
}
if (mcbeResponseBytes[0] != 0x1C)
{
return false; // Invalid packet type
}
var pongMagic = mcbeResponseBytes.Skip(17).Take(16).ToArray();
if (!pongMagic.SequenceEqual(McBeMagicBytes))
{
return false; // Magic bytes do not match
}
var stringLength = (ushort)((mcbeResponseBytes[33] << 8) | mcbeResponseBytes[34]);
var stringData = Encoding.UTF8.GetString(mcbeResponseBytes.Skip(35).Take(stringLength).ToArray());
var stringParts = stringData.Split(';');
// check Game Mode str
var gameMode = stringParts.Length > 8 ? stringParts[8] : "";
if (!ValidGameModes.Contains(gameMode))
{
return false; // Invalid game mode
}
return true;
}
public ushort GetDefaultTargetPort()
{
return McBeDefaultPort;
}
public string GetDefaultTargetHost()
{
return McBeDefaultServer;
}
}
@@ -0,0 +1,37 @@
namespace ServiceLib.UdpTest.Tester;
public class NtpService : IUdpTest
{
private const int NtpDefaultPort = 123;
private const string NtpDefaultServer = "pool.ntp.org";
public byte[] BuildUdpRequestPacket()
{
var ntpReq = new byte[48];
ntpReq[0] = 0x23; // LI=0, VN=4, Mode=3
return ntpReq;
}
public bool VerifyAndExtractUdpResponse(byte[] ntpResponseBytes)
{
if (ntpResponseBytes.Length < 48)
{
return false;
}
if ((ntpResponseBytes[0] & 0x07) != 4)
{
return false;
}
return true;
}
public ushort GetDefaultTargetPort()
{
return NtpDefaultPort;
}
public string GetDefaultTargetHost()
{
return NtpDefaultServer;
}
}
@@ -0,0 +1,52 @@
namespace ServiceLib.UdpTest.Tester;
public class StunService : IUdpTest
{
private const int StunDefaultPort = 3478;
private const string StunDefaultServer = "stun.voztovoice.org";
private static readonly byte[] StunBindingRequestPacket =
[
// STUN Binding Request
0x00, 0x01, // Message Type: Binding Request (0x0001)
0x00, 0x00, // Message Length: 0 (no attributes)
0x21, 0x12, 0xA4, 0x42, // Magic Cookie: 0x2112A442
// Transaction ID: 96 bits (12 bytes) random
0x66, 0x0E, 0xAB, 0xBC, 0x61, 0x0D,
0xA4, 0x40, 0x8C, 0x65, 0xC1, 0xBE,
];
public byte[] BuildUdpRequestPacket()
{
return (byte[])StunBindingRequestPacket.Clone();
}
public bool VerifyAndExtractUdpResponse(byte[] stunResponseBytes)
{
if (stunResponseBytes.Length < 20)
{
return false;
}
if (stunResponseBytes.Length >= 2)
{
var messageType = (stunResponseBytes[0] << 8) | stunResponseBytes[1];
if (messageType is 0x0101 or 0x0111)
{
return true;
}
}
return true;
}
public ushort GetDefaultTargetPort()
{
return StunDefaultPort;
}
public string GetDefaultTargetHost()
{
return StunDefaultServer;
}
}
+154
View File
@@ -0,0 +1,154 @@
using ServiceLib.UdpTest.Tester;
namespace ServiceLib.UdpTest;
public class UdpTestService
{
private const string DefaultUdpTestType = "ntp";
private readonly IUdpTest _udpTest;
private static readonly IReadOnlyDictionary<string, Func<IUdpTest>> UdpTestFactories =
new Dictionary<string, Func<IUdpTest>>(StringComparer.OrdinalIgnoreCase)
{
["ntp"] = () => new NtpService(),
["dns"] = () => new DnsService(),
["stun"] = () => new StunService(),
["mcbe"] = () => new McBeService(),
};
private UdpTestService(IUdpTest udpTest)
{
_udpTest = udpTest;
}
public static UdpTestService Create(string? udpTestType)
{
if (string.IsNullOrEmpty(udpTestType))
{
return new UdpTestService(UdpTestFactories[DefaultUdpTestType]());
}
return UdpTestFactories.TryGetValue(udpTestType, out var factory)
? new UdpTestService(factory())
: new UdpTestService(UdpTestFactories[DefaultUdpTestType]());
}
public static UdpTestService CreateFromTarget(string? udpTestTarget, out string targetServerHost)
{
var parts = udpTestTarget?.Split(':', 2);
var udpTestType = parts?.Length > 0 ? parts[0] : DefaultUdpTestType;
var udpService = Create(udpTestType);
targetServerHost = parts?.Length > 1 && !string.IsNullOrEmpty(parts[1])
? parts[1]
: udpService._udpTest.GetDefaultTargetHost();
return udpService;
}
private (string host, ushort port) ParseHostAndPort(string targetServerHost)
{
if (string.IsNullOrEmpty(targetServerHost))
{
return (_udpTest.GetDefaultTargetHost(), _udpTest.GetDefaultTargetPort());
}
// Handle IPv6 format: [::1]:port or [2001:db8::1]:port
if (targetServerHost.StartsWith('['))
{
var closeBracketIndex = targetServerHost.IndexOf(']');
if (closeBracketIndex > 0)
{
var host = targetServerHost.Substring(1, closeBracketIndex - 1);
if (closeBracketIndex < targetServerHost.Length - 1 && targetServerHost[closeBracketIndex + 1] == ':')
{
var portStr = targetServerHost.Substring(closeBracketIndex + 2);
if (ushort.TryParse(portStr, out var port))
{
return (host, port);
}
}
return (host, _udpTest.GetDefaultTargetPort());
}
}
// Handle IPv4 or domain format: 1.1.1.1:53 or exam.com:333
var lastColonIndex = targetServerHost.LastIndexOf(':');
if (lastColonIndex > 0)
{
var host = targetServerHost.Substring(0, lastColonIndex);
var portStr = targetServerHost.Substring(lastColonIndex + 1);
if (ushort.TryParse(portStr, out var port))
{
return (host, port);
}
}
// No port specified, use default
return (targetServerHost, _udpTest.GetDefaultTargetPort());
}
public async Task<TimeSpan> SendUdpRequestAsync(string targetServerHost, int socks5Port, TimeSpan operationTimeout)
{
using var cts = new CancellationTokenSource(operationTimeout);
var cancellationToken = cts.Token;
var udpRequestPacket = _udpTest.BuildUdpRequestPacket();
if (udpRequestPacket == null || udpRequestPacket.Length == 0)
{
throw new InvalidOperationException("Failed to build UDP request packet.");
}
using var channel = new Socks5UdpChannel("127.0.0.1", socks5Port);
if (!await channel.EstablishUdpAssociationAsync(cancellationToken).ConfigureAwait(false))
{
throw new Exception("Failed to establish UDP association with SOCKS5 proxy.");
}
var (targetHost, targetPort) = ParseHostAndPort(targetServerHost);
byte[] udpReceiveResult = null;
// Get minimum round trip time from two attempts
var roundTripTime = TimeSpan.MaxValue;
for (var attempt = 0; attempt < 2; attempt++)
{
try
{
var stopwatch = new Stopwatch();
stopwatch.Start();
await channel.SendAsync(targetHost, targetPort, udpRequestPacket).ConfigureAwait(false);
var (_, receiveResult) = await channel.ReceiveAsync(cancellationToken).ConfigureAwait(false);
stopwatch.Stop();
udpReceiveResult = receiveResult;
var currentRoundTripTime = stopwatch.Elapsed;
if (currentRoundTripTime < roundTripTime)
{
roundTripTime = currentRoundTripTime;
}
}
catch
{
if (attempt == 1 && roundTripTime == TimeSpan.MaxValue)
{
throw;
}
}
}
if ((udpReceiveResult?.Length ?? 0) < 4 + 1 + 4 + 2)
{
throw new Exception("Received NTP response is too short.");
}
if (udpReceiveResult != null && _udpTest.VerifyAndExtractUdpResponse(udpReceiveResult))
{
return roundTripTime;
}
else
{
throw new Exception("Failed to verify and extract UDP response.");
}
}
}
+15 -11
View File
@@ -53,19 +53,23 @@ internal static class WindowsUtils
public static async Task RemoveTunDevice()
{
try
var tunNameList = new List<string> { "wintunsingbox_tun", "xray_tun" };
foreach (var tunName in tunNameList)
{
var sum = MD5.HashData(Encoding.UTF8.GetBytes("wintunsingbox_tun"));
var guid = new Guid(sum);
var pnpUtilPath = @"C:\Windows\System32\pnputil.exe";
var arg = $$""" /remove-device "SWD\Wintun\{{{guid}}}" """;
try
{
var sum = MD5.HashData(Encoding.UTF8.GetBytes(tunName));
var guid = new Guid(sum);
var pnpUtilPath = @"C:\Windows\System32\pnputil.exe";
var arg = $$""" /remove-device "SWD\Wintun\{{{guid}}}" """;
// Try to remove the device
_ = await Utils.GetCliWrapOutput(pnpUtilPath, arg);
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
// Try to remove the device
_ = await Utils.GetCliWrapOutput(pnpUtilPath, arg);
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
}
}
}
}
@@ -4,6 +4,7 @@ public enum ESpeedActionType
{
Tcping,
Realping,
UdpTest,
Speedtest,
Mixedtest,
FastRealping
+1 -1
View File
@@ -2,7 +2,7 @@ namespace ServiceLib.Enums;
public enum ETransport
{
tcp,
raw,
kcp,
ws,
httpupgrade,
+33 -20
View File
@@ -24,6 +24,8 @@ public class Global
public const string V2raySampleHttpResponseFileName = NamespaceSample + "SampleHttpResponse";
public const string V2raySampleInbound = NamespaceSample + "SampleInbound";
public const string V2raySampleOutbound = NamespaceSample + "SampleOutbound";
public const string V2raySampleTunInbound = NamespaceSample + "SampleTunInbound";
public const string V2raySampleTunRules = NamespaceSample + "SampleTunRules";
public const string SingboxSampleOutbound = NamespaceSample + "SingboxSampleOutbound";
public const string CustomRoutingFileName = NamespaceSample + "custom_routing_";
public const string TunSingboxDNSFileName = NamespaceSample + "tun_singbox_dns";
@@ -42,12 +44,15 @@ public class Global
public const string SingboxFakeIPFilterFileName = NamespaceSample + "singbox_fakeip_filter";
public const string DefaultSecurity = "auto";
public const string DefaultNetwork = "tcp";
public const string TcpHeaderHttp = "http";
public const string DefaultNetwork = "raw";
public const string RawHeaderHttp = "http";
public const string None = "none";
public const string RawNetworkAlias = "tcp";
public const string DefaultXhttpMode = "auto";
public const string ProxyTag = "proxy";
public const string DirectTag = "direct";
public const string BlockTag = "block";
public const string DnsOutboundTag = "dns";
public const string DnsTag = "dns-module";
public const string DirectDnsTag = "direct-dns";
public const string BalancerTagSuffix = "-round";
@@ -89,7 +94,7 @@ public class Global
public const string SingboxHostsDNSTag = "hosts_dns";
public const string SingboxFakeDNSTag = "fake_dns";
public const int Hysteria2DefaultHopInt = 10;
public const int Hysteria2DefaultHopInt = 30;
public const string PolicyGroupExcludeKeywords = @"剩余|过期|到期|重置|[Rr]emaining|[Ee]xpir|[Rr]eset";
@@ -182,7 +187,7 @@ public class Global
@"https://raw.githubusercontent.com/Chocolate4U/Iran-v2ray-rules/main/v2rayN/"
];
public static readonly Dictionary<string, string> TcpHttpUserAgentTexts = new()
public static readonly Dictionary<string, string> RawHttpUserAgentTexts = new()
{
{"chrome","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36" },
{"firefox","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0" },
@@ -293,14 +298,12 @@ public class Global
public static readonly List<string> Networks =
[
"tcp",
"kcp",
"ws",
"httpupgrade",
"raw",
"xhttp",
"h2",
"quic",
"grpc"
"kcp",
"grpc",
"ws",
"httpupgrade"
];
public static readonly List<string> KcpHeaderTypes =
@@ -508,6 +511,7 @@ public class Global
[
"http",
"tls",
"quic",
"bittorrent"
];
@@ -525,7 +529,6 @@ public class Global
"tls",
"quic",
"fakedns",
"fakedns+others"
];
public static readonly List<int> TunMtus =
@@ -637,6 +640,24 @@ public class Global
@""
];
public static readonly List<string> UdpTestTargets =
[
"ntp:pool.ntp.org",
"ntp:time.google.com",
"dns:1.1.1.1",
"dns:8.8.8.8",
"dns:dns.google",
"stun:stun.voztovoice.org",
"stun:stun.cloudflare.com",
"stun:stun.l.google.com:19302",
"mcbe:pms.mc-complex.com",
"mcbe:bedrock.opblocks.com",
"mcbe:opsucht.net",
"mcbe:play.craftersmc.net",
"mcbe:mps.lemoncloud.net",
"mcbe:bedrock.talonmc.net",
];
public static readonly List<string> OutboundTags =
[
ProxyTag,
@@ -670,14 +691,6 @@ public class Global
""
];
public static readonly List<string> EchForceQuerys =
[
"none",
"half",
"full",
""
];
public static readonly List<string> TunIcmpRoutingPolicies =
[
"rule",
@@ -23,19 +23,6 @@ public record CoreConfigContextBuilderAllResult(
public NodeValidatorResult CombinedValidatorResult => new(
[.. MainResult.ValidatorResult.Errors, .. PreSocksResult?.ValidatorResult.Errors ?? []],
[.. MainResult.ValidatorResult.Warnings, .. PreSocksResult?.ValidatorResult.Warnings ?? []]);
/// <summary>
/// The main context with TunProtectSocksPort/ProxyRelaySocksPort and ProtectDomainList merged in
/// from the pre-socks result (if any). Pass this to the core runner.
/// </summary>
public CoreConfigContext ResolvedMainContext => PreSocksResult is not null
? MainResult.Context with
{
TunProtectSocksPort = PreSocksResult.Context.TunProtectSocksPort,
ProxyRelaySocksPort = PreSocksResult.Context.ProxyRelaySocksPort,
ProtectDomainList = [.. MainResult.Context.ProtectDomainList ?? [], .. PreSocksResult.Context.ProtectDomainList ?? []],
}
: MainResult.Context;
}
public class CoreConfigContextBuilder
@@ -58,8 +45,6 @@ public class CoreConfigContextBuilder
IsTunEnabled = config.TunModeItem.EnableTun,
SimpleDnsItem = config.SimpleDNSItem,
ProtectDomainList = [],
TunProtectSocksPort = 0,
ProxyRelaySocksPort = 0,
RawDnsItem = await AppManager.Instance.GetDNSItem(coreType),
RoutingItem = await ConfigHandler.GetDefaultRouting(config),
};
@@ -122,7 +107,20 @@ public class CoreConfigContextBuilder
}
var preResult = await BuildPreSocksIfNeeded(mainResult.Context);
return new CoreConfigContextBuilderAllResult(mainResult, preResult);
if (preResult is null)
{
return new CoreConfigContextBuilderAllResult(mainResult, null);
}
var resolvedMainResult = mainResult with
{
Context = mainResult.Context with
{
IsTunEnabled = false, // main core doesn't handle tun directly when pre-socks is used
ProtectDomainList = [.. mainResult.Context.ProtectDomainList, .. preResult.Context.ProtectDomainList],
}
};
return new CoreConfigContextBuilderAllResult(resolvedMainResult, preResult);
}
/// <summary>
@@ -148,32 +146,7 @@ public class CoreConfigContextBuilder
};
}
if (!nodeContext.IsTunEnabled
|| coreType != ECoreType.Xray
|| node.ConfigType == EConfigType.Custom)
{
return null;
}
var tunProtectSocksPort = Utils.GetFreePort();
var proxyRelaySocksPort = Utils.GetFreePort();
var preItem = new ProfileItem()
{
CoreType = ECoreType.sing_box,
ConfigType = EConfigType.SOCKS,
Address = Global.Loopback,
Port = proxyRelaySocksPort,
};
var preResult2 = await Build(nodeContext.AppConfig, preItem);
return preResult2 with
{
Context = preResult2.Context with
{
ProtectDomainList = [.. nodeContext.ProtectDomainList ?? [], .. preResult2.Context.ProtectDomainList ?? []],
TunProtectSocksPort = tunProtectSocksPort,
ProxyRelaySocksPort = proxyRelaySocksPort,
}
};
return null;
}
/// <summary>
@@ -340,8 +313,9 @@ public class CoreConfigContextBuilder
}
// xhttp downloadSettings address protect
if (!string.IsNullOrEmpty(node.Extra)
&& JsonUtils.ParseJson(node.Extra) is JsonObject extra
var xhttpExtra = node.GetTransportExtra().XhttpExtra;
if (!string.IsNullOrEmpty(xhttpExtra)
&& JsonUtils.ParseJson(xhttpExtra) is JsonObject extra
&& extra.TryGetPropertyValue("downloadSettings", out var dsNode)
&& dsNode is JsonObject downloadSettings
&& downloadSettings.TryGetPropertyValue("address", out var dAddrNode)
@@ -20,7 +20,7 @@ public class NodeValidator
[EConfigType.VMess, EConfigType.VLESS, EConfigType.Trojan, EConfigType.Shadowsocks];
private static readonly HashSet<string> SingboxShadowsocksAllowedTransports =
[nameof(ETransport.tcp), nameof(ETransport.ws), nameof(ETransport.quic)];
[nameof(ETransport.raw), nameof(ETransport.ws)];
public static NodeValidatorResult Validate(ProfileItem item, ECoreType coreType)
{
@@ -141,9 +141,10 @@ public class NodeValidator
v.Assert(!item.PublicKey.IsNullOrEmpty(), string.Format(ResUI.MsgInvalidProperty, "PublicKey"));
}
if (item.Network == nameof(ETransport.xhttp) && !item.Extra.IsNullOrEmpty())
var transport = item.GetTransportExtra();
if (item.Network == nameof(ETransport.xhttp) && !transport.XhttpExtra.IsNullOrEmpty())
{
if (JsonUtils.ParseJson(item.Extra) is not JsonObject)
if (JsonUtils.ParseJson(transport.XhttpExtra) is not JsonObject)
{
v.Error(string.Format(ResUI.MsgInvalidProperty, "XHTTP Extra"));
}
@@ -167,7 +168,7 @@ public class NodeValidator
}
// sing-box does not support non-tcp transports for protocols other than vmess/trojan/vless/shadowsocks
if (!SingboxTransportSupportedProtocols.Contains(configType) && net != nameof(ETransport.tcp))
if (!SingboxTransportSupportedProtocols.Contains(configType) && net != nameof(ETransport.raw))
{
return string.Format(ResUI.MsgCoreNotSupportProtocolTransport,
nameof(ECoreType.sing_box), configType.ToString(), net);
+44 -24
View File
@@ -77,10 +77,11 @@ public static class ConfigHandler
Tti = 50,
UplinkCapacity = 12,
DownlinkCapacity = 100,
ReadBufferSize = 2,
WriteBufferSize = 2,
Congestion = false
CwndMultiplier = 1,
MaxSendingWindow = 2 * 1024 * 1024,
};
config.KcpItem.CwndMultiplier = config.KcpItem.CwndMultiplier <= 0 ? 1 : config.KcpItem.CwndMultiplier;
config.KcpItem.MaxSendingWindow = config.KcpItem.MaxSendingWindow <= 0 ? (2 * 1024 * 1024) : config.KcpItem.MaxSendingWindow;
config.GrpcItem ??= new GrpcItem
{
IdleTimeout = 60,
@@ -134,6 +135,10 @@ public static class ConfigHandler
{
config.SpeedTestItem.MixedConcurrencyCount = 5;
}
if (config.SpeedTestItem.UdpTestTarget.IsNullOrEmpty())
{
config.SpeedTestItem.UdpTestTarget = Global.UdpTestTargets.First();
}
config.Mux4RayItem ??= new()
{
@@ -161,7 +166,7 @@ public static class ConfigHandler
config.Fragment4RayItem ??= new()
{
Packets = "tlshello",
Length = "100-200",
Length = "50-100",
Interval = "10-20"
};
config.GlobalHotkeys ??= new();
@@ -236,9 +241,6 @@ public static class ConfigHandler
item.Password = profileItem.Password;
item.Network = profileItem.Network;
item.HeaderType = profileItem.HeaderType;
item.RequestHost = profileItem.RequestHost;
item.Path = profileItem.Path;
item.StreamSecurity = profileItem.StreamSecurity;
item.Sni = profileItem.Sni;
@@ -250,14 +252,13 @@ public static class ConfigHandler
item.ShortId = profileItem.ShortId;
item.SpiderX = profileItem.SpiderX;
item.Mldsa65Verify = profileItem.Mldsa65Verify;
item.Extra = profileItem.Extra;
item.MuxEnabled = profileItem.MuxEnabled;
item.Cert = profileItem.Cert;
item.CertSha = profileItem.CertSha;
item.EchConfigList = profileItem.EchConfigList;
item.EchForceQuery = profileItem.EchForceQuery;
item.Finalmask = profileItem.Finalmask;
item.ProtoExtra = profileItem.ProtoExtra;
item.TransportExtra = profileItem.TransportExtra;
}
var ret = item.ConfigType switch
@@ -297,9 +298,6 @@ public static class ConfigHandler
VmessSecurity = profileItem.GetProtocolExtra().VmessSecurity?.TrimEx()
});
profileItem.Network = profileItem.Network.TrimEx();
profileItem.HeaderType = profileItem.HeaderType.TrimEx();
profileItem.RequestHost = profileItem.RequestHost.TrimEx();
profileItem.Path = profileItem.Path.TrimEx();
profileItem.StreamSecurity = profileItem.StreamSecurity.TrimEx();
if (!Global.VmessSecurities.Contains(profileItem.GetProtocolExtra().VmessSecurity))
@@ -751,10 +749,12 @@ public static class ConfigHandler
profileItem.Password = profileItem.Password.TrimEx();
profileItem.Network = string.Empty;
if (!Global.TuicCongestionControls.Contains(profileItem.HeaderType))
var congestionControl = profileItem.GetProtocolExtra().CongestionControl;
if (!Global.TuicCongestionControls.Contains(congestionControl))
{
profileItem.HeaderType = Global.TuicCongestionControls.FirstOrDefault()!;
congestionControl = Global.TuicCongestionControls.FirstOrDefault()!;
}
profileItem.SetProtocolExtra(profileItem.GetProtocolExtra() with { CongestionControl = congestionControl });
if (profileItem.StreamSecurity.IsNullOrEmpty())
{
@@ -996,9 +996,6 @@ public static class ConfigHandler
profileItem.Address = profileItem.Address.TrimEx();
profileItem.Password = profileItem.Password.TrimEx();
profileItem.Network = profileItem.Network.TrimEx();
profileItem.HeaderType = profileItem.HeaderType.TrimEx();
profileItem.RequestHost = profileItem.RequestHost.TrimEx();
profileItem.Path = profileItem.Path.TrimEx();
profileItem.StreamSecurity = profileItem.StreamSecurity.TrimEx();
var vlessEncryption = profileItem.GetProtocolExtra().VlessEncryption?.TrimEx();
@@ -1043,13 +1040,19 @@ public static class ConfigHandler
foreach (var item in lstProfile)
{
if (!lstKeep.Exists(i => CompareProfileItem(i, item, false)))
if (item.IsComplex())
{
lstKeep.Add(item);
continue;
}
if (lstKeep.Exists(i => CompareProfileItem(i, item, false)))
{
lstRemove.Add(item);
}
else
{
lstRemove.Add(item);
lstKeep.Add(item);
}
}
await RemoveServers(config, lstRemove);
@@ -1067,7 +1070,7 @@ public static class ConfigHandler
/// <returns>0 if successful</returns>
public static async Task<int> AddServerCommon(Config config, ProfileItem profileItem, bool toFile = true)
{
profileItem.ConfigVersion = 3;
profileItem.ConfigVersion = 4;
if (profileItem.StreamSecurity.IsNotEmpty())
{
@@ -1135,6 +1138,8 @@ public static class ConfigHandler
var oProtocolExtra = o.GetProtocolExtra();
var nProtocolExtra = n.GetProtocolExtra();
var oTransport = o.GetTransportExtra();
var nTransport = n.GetTransportExtra();
return o.ConfigType == n.ConfigType
&& AreEqual(o.Address, n.Address)
@@ -1145,9 +1150,16 @@ public static class ConfigHandler
&& AreEqual(oProtocolExtra.SsMethod, nProtocolExtra.SsMethod)
&& AreEqual(oProtocolExtra.VmessSecurity, nProtocolExtra.VmessSecurity)
&& AreEqual(o.Network, n.Network)
&& AreEqual(o.HeaderType, n.HeaderType)
&& AreEqual(o.RequestHost, n.RequestHost)
&& AreEqual(o.Path, n.Path)
&& AreEqual(oTransport.RawHeaderType, nTransport.RawHeaderType)
&& AreEqual(oTransport.Host, nTransport.Host)
&& AreEqual(oTransport.Path, nTransport.Path)
&& AreEqual(oTransport.XhttpMode, nTransport.XhttpMode)
&& AreEqual(oTransport.XhttpExtra, nTransport.XhttpExtra)
&& AreEqual(oTransport.GrpcAuthority, nTransport.GrpcAuthority)
&& AreEqual(oTransport.GrpcServiceName, nTransport.GrpcServiceName)
&& AreEqual(oTransport.GrpcMode, nTransport.GrpcMode)
&& AreEqual(oTransport.KcpHeaderType, nTransport.KcpHeaderType)
&& AreEqual(oTransport.KcpSeed, nTransport.KcpSeed)
&& (o.ConfigType == EConfigType.Trojan || o.StreamSecurity == n.StreamSecurity)
&& AreEqual(oProtocolExtra.Flow, nProtocolExtra.Flow)
&& AreEqual(oProtocolExtra.SalamanderPass, nProtocolExtra.SalamanderPass)
@@ -1417,10 +1429,12 @@ public static class ConfigHandler
public static ProfileItem? GetPreSocksItem(Config config, ProfileItem node, ECoreType coreType)
{
ProfileItem? itemSocks = null;
var enableLegacyProtect = config.TunModeItem.EnableLegacyProtect
|| Utils.IsNonWindows();
if (node.ConfigType != EConfigType.Custom
&& coreType != ECoreType.sing_box
&& config.TunModeItem.EnableTun
&& config.TunModeItem.EnableLegacyProtect)
&& enableLegacyProtect)
{
itemSocks = new ProfileItem()
{
@@ -1931,6 +1945,12 @@ public static class ConfigHandler
await SQLiteHelper.Instance.DeleteAsync(item);
await RemoveServersViaSubid(config, id, false);
if (item.Id == config.SubIndexId)
{
var subs = await AppManager.Instance.SubItems();
config.SubIndexId = subs.LastOrDefault()?.Id;
}
return 0;
}
+103 -79
View File
@@ -6,6 +6,8 @@ public class BaseFmt
{
private static readonly string[] _allowInsecureArray = new[] { "insecure", "allowInsecure", "allow_insecure" };
private static string UrlEncodeSafe(string? value) => Utils.UrlEncode(value ?? string.Empty);
protected static string GetIpv6(string address)
{
if (Utils.IsIpv6(address))
@@ -21,6 +23,8 @@ public class BaseFmt
protected static int ToUriQuery(ProfileItem item, string? securityDef, ref Dictionary<string, string> dicQuery)
{
var transport = item.GetTransportExtra();
if (item.StreamSecurity.IsNotEmpty())
{
dicQuery.Add("security", item.StreamSecurity);
@@ -87,54 +91,69 @@ public class BaseFmt
dicQuery.Add("fm", Utils.UrlEncode(finalmask));
}
dicQuery.Add("type", item.Network.IsNotEmpty() ? item.Network : nameof(ETransport.tcp));
switch (item.Network)
var network = item.GetNetwork();
if (!Global.Networks.Contains(network))
{
case nameof(ETransport.tcp):
dicQuery.Add("headerType", item.HeaderType.IsNotEmpty() ? item.HeaderType : Global.None);
if (item.RequestHost.IsNotEmpty())
network = nameof(ETransport.raw);
}
//dicQuery.Add("type", network);
dicQuery.Add("type", network == nameof(ETransport.raw) ? Global.RawNetworkAlias : network);
switch (network)
{
case nameof(ETransport.raw):
dicQuery.Add("headerType", transport.RawHeaderType.IsNotEmpty() ? transport.RawHeaderType : Global.None);
if (transport.Host.IsNotEmpty())
{
dicQuery.Add("host", Utils.UrlEncode(item.RequestHost));
dicQuery.Add("host", UrlEncodeSafe(transport.Host));
}
if (transport.Path.IsNotEmpty())
{
dicQuery.Add("path", UrlEncodeSafe(transport.Path));
}
break;
case nameof(ETransport.kcp):
dicQuery.Add("headerType", item.HeaderType.IsNotEmpty() ? item.HeaderType : Global.None);
if (item.Path.IsNotEmpty())
dicQuery.Add("headerType", transport.KcpHeaderType.IsNotEmpty() ? transport.KcpHeaderType : Global.None);
if (transport.KcpSeed.IsNotEmpty())
{
dicQuery.Add("seed", Utils.UrlEncode(item.Path));
dicQuery.Add("seed", UrlEncodeSafe(transport.KcpSeed));
}
if (transport.KcpMtu > 0)
{
dicQuery.Add("mtu", transport.KcpMtu.ToString());
}
break;
case nameof(ETransport.ws):
case nameof(ETransport.httpupgrade):
if (item.RequestHost.IsNotEmpty())
if (transport.Host.IsNotEmpty())
{
dicQuery.Add("host", Utils.UrlEncode(item.RequestHost));
dicQuery.Add("host", UrlEncodeSafe(transport.Host));
}
if (item.Path.IsNotEmpty())
if (transport.Path.IsNotEmpty())
{
dicQuery.Add("path", Utils.UrlEncode(item.Path));
dicQuery.Add("path", UrlEncodeSafe(transport.Path));
}
break;
case nameof(ETransport.xhttp):
if (item.RequestHost.IsNotEmpty())
if (transport.Host.IsNotEmpty())
{
dicQuery.Add("host", Utils.UrlEncode(item.RequestHost));
dicQuery.Add("host", UrlEncodeSafe(transport.Host));
}
if (item.Path.IsNotEmpty())
if (transport.Path.IsNotEmpty())
{
dicQuery.Add("path", Utils.UrlEncode(item.Path));
dicQuery.Add("path", UrlEncodeSafe(transport.Path));
}
if (item.HeaderType.IsNotEmpty() && Global.XhttpMode.Contains(item.HeaderType))
if (transport.XhttpMode.IsNotEmpty() && Global.XhttpMode.Contains(transport.XhttpMode))
{
dicQuery.Add("mode", Utils.UrlEncode(item.HeaderType));
dicQuery.Add("mode", UrlEncodeSafe(transport.XhttpMode));
}
if (item.Extra.IsNotEmpty())
if (transport.XhttpExtra.IsNotEmpty())
{
var node = JsonUtils.ParseJson(item.Extra);
var node = JsonUtils.ParseJson(transport.XhttpExtra);
var extra = node != null
? JsonUtils.Serialize(node, new JsonSerializerOptions
{
@@ -142,38 +161,19 @@ public class BaseFmt
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
})
: item.Extra;
dicQuery.Add("extra", Utils.UrlEncode(extra));
: transport.XhttpExtra;
dicQuery.Add("extra", UrlEncodeSafe(extra));
}
break;
case nameof(ETransport.http):
case nameof(ETransport.h2):
dicQuery["type"] = nameof(ETransport.http);
if (item.RequestHost.IsNotEmpty())
{
dicQuery.Add("host", Utils.UrlEncode(item.RequestHost));
}
if (item.Path.IsNotEmpty())
{
dicQuery.Add("path", Utils.UrlEncode(item.Path));
}
break;
case nameof(ETransport.quic):
dicQuery.Add("headerType", item.HeaderType.IsNotEmpty() ? item.HeaderType : Global.None);
dicQuery.Add("quicSecurity", Utils.UrlEncode(item.RequestHost));
dicQuery.Add("key", Utils.UrlEncode(item.Path));
break;
case nameof(ETransport.grpc):
if (item.Path.IsNotEmpty())
if (transport.GrpcServiceName.IsNotEmpty())
{
dicQuery.Add("authority", Utils.UrlEncode(item.RequestHost));
dicQuery.Add("serviceName", Utils.UrlEncode(item.Path));
if (item.HeaderType is Global.GrpcGunMode or Global.GrpcMultiMode)
dicQuery.Add("authority", UrlEncodeSafe(transport.GrpcAuthority));
dicQuery.Add("serviceName", UrlEncodeSafe(transport.GrpcServiceName));
if (transport.GrpcMode is Global.GrpcGunMode or Global.GrpcMultiMode)
{
dicQuery.Add("mode", Utils.UrlEncode(item.HeaderType));
dicQuery.Add("mode", UrlEncodeSafe(transport.GrpcMode));
}
}
break;
@@ -216,6 +216,8 @@ public class BaseFmt
protected static int ResolveUriQuery(NameValueCollection query, ref ProfileItem item)
{
var transport = item.GetTransportExtra();
item.StreamSecurity = GetQueryValue(query, "security");
item.Sni = GetQueryValue(query, "sni");
item.Alpn = GetQueryDecoded(query, "alpn");
@@ -258,36 +260,57 @@ public class BaseFmt
item.AllowInsecure = string.Empty;
}
item.Network = GetQueryValue(query, "type", nameof(ETransport.tcp));
var net = GetQueryValue(query, "type", nameof(ETransport.raw));
if (net == Global.RawNetworkAlias)
{
net = nameof(ETransport.raw);
}
if (!Global.Networks.Contains(net))
{
net = nameof(ETransport.raw);
}
item.Network = net;
switch (item.Network)
{
case nameof(ETransport.tcp):
item.HeaderType = GetQueryValue(query, "headerType", Global.None);
item.RequestHost = GetQueryDecoded(query, "host");
case nameof(ETransport.raw):
transport = transport with
{
RawHeaderType = GetQueryValue(query, "headerType", Global.None),
Host = GetQueryDecoded(query, "host"),
Path = GetQueryDecoded(query, "path"),
};
break;
case nameof(ETransport.kcp):
item.HeaderType = GetQueryValue(query, "headerType", Global.None);
item.Path = GetQueryDecoded(query, "seed");
var kcpSeed = GetQueryDecoded(query, "seed");
var kcpMtuStr = GetQueryValue(query, "mtu");
var kcpMtu = int.TryParse(kcpMtuStr, out var mtu) ? mtu : 0;
transport = transport with
{
KcpHeaderType = GetQueryValue(query, "headerType", Global.None),
KcpSeed = kcpSeed,
KcpMtu = kcpMtu > 0 ? mtu : null,
};
break;
case nameof(ETransport.ws):
case nameof(ETransport.httpupgrade):
item.RequestHost = GetQueryDecoded(query, "host");
item.Path = GetQueryDecoded(query, "path", "/");
transport = transport with
{
Host = GetQueryDecoded(query, "host"),
Path = GetQueryDecoded(query, "path", "/"),
};
break;
case nameof(ETransport.xhttp):
item.RequestHost = GetQueryDecoded(query, "host");
item.Path = GetQueryDecoded(query, "path", "/");
item.HeaderType = GetQueryDecoded(query, "mode");
var extraDecoded = GetQueryDecoded(query, "extra");
if (extraDecoded.IsNotEmpty())
var xhttpExtra = GetQueryDecoded(query, "extra");
if (xhttpExtra.IsNotEmpty())
{
var node = JsonUtils.ParseJson(extraDecoded);
var node = JsonUtils.ParseJson(xhttpExtra);
if (node != null)
{
extraDecoded = JsonUtils.Serialize(node, new JsonSerializerOptions
xhttpExtra = JsonUtils.Serialize(node, new JsonSerializerOptions
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
@@ -295,31 +318,32 @@ public class BaseFmt
});
}
}
item.Extra = extraDecoded;
break;
case nameof(ETransport.http):
case nameof(ETransport.h2):
item.Network = nameof(ETransport.h2);
item.RequestHost = GetQueryDecoded(query, "host");
item.Path = GetQueryDecoded(query, "path", "/");
break;
case nameof(ETransport.quic):
item.HeaderType = GetQueryValue(query, "headerType", Global.None);
item.RequestHost = GetQueryValue(query, "quicSecurity", Global.None);
item.Path = GetQueryDecoded(query, "key");
transport = transport with
{
Host = GetQueryDecoded(query, "host"),
Path = GetQueryDecoded(query, "path", "/"),
XhttpMode = GetQueryDecoded(query, "mode"),
XhttpExtra = xhttpExtra,
};
break;
case nameof(ETransport.grpc):
item.RequestHost = GetQueryDecoded(query, "authority");
item.Path = GetQueryDecoded(query, "serviceName");
item.HeaderType = GetQueryDecoded(query, "mode", Global.GrpcGunMode);
transport = transport with
{
GrpcAuthority = GetQueryDecoded(query, "authority"),
GrpcServiceName = GetQueryDecoded(query, "serviceName"),
GrpcMode = GetQueryDecoded(query, "mode", Global.GrpcGunMode),
};
break;
default:
item.Network = nameof(ETransport.raw);
break;
}
item.SetTransportExtra(transport);
return 0;
}
+16 -17
View File
@@ -42,31 +42,28 @@ public class ShadowsocksFmt : BaseFmt
//url = Utile.Base64Encode(url);
//new Sip002
var pw = Utils.Base64Encode($"{item.GetProtocolExtra().SsMethod}:{item.Password}", true);
var transport = item.GetTransportExtra();
// plugin
var plugin = string.Empty;
var pluginArgs = string.Empty;
if (item.Network == nameof(ETransport.tcp) && item.HeaderType == Global.TcpHeaderHttp)
if (item.Network == nameof(ETransport.raw) && transport.RawHeaderType == Global.RawHeaderHttp)
{
plugin = "obfs-local";
pluginArgs = $"obfs=http;obfs-host={item.RequestHost};";
pluginArgs = $"obfs=http;obfs-host={transport.Host};";
}
else
{
if (item.Network == nameof(ETransport.ws))
{
pluginArgs += "mode=websocket;";
pluginArgs += $"host={item.RequestHost};";
pluginArgs += $"host={transport.Host};";
// https://github.com/shadowsocks/v2ray-plugin/blob/e9af1cdd2549d528deb20a4ab8d61c5fbe51f306/args.go#L172
// Equal signs and commas [and backslashes] must be escaped with a backslash.
var path = item.Path.Replace("\\", "\\\\").Replace("=", "\\=").Replace(",", "\\,");
var path = (transport.Path ?? string.Empty).Replace("\\", "\\\\").Replace("=", "\\=").Replace(",", "\\,");
pluginArgs += $"path={path};";
}
else if (item.Network == nameof(ETransport.quic))
{
pluginArgs += "mode=quic;";
}
if (item.StreamSecurity == Global.StreamSecurity)
{
pluginArgs += "tls;";
@@ -213,8 +210,11 @@ public class ShadowsocksFmt : BaseFmt
{
obfsHost = obfsHost.Replace("obfs-host=", "");
item.Network = Global.DefaultNetwork;
item.HeaderType = Global.TcpHeaderHttp;
item.RequestHost = obfsHost;
item.SetTransportExtra(item.GetTransportExtra() with
{
RawHeaderType = Global.RawHeaderHttp,
Host = obfsHost,
});
}
}
// Parse v2ray-plugin
@@ -231,21 +231,20 @@ public class ShadowsocksFmt : BaseFmt
if (modeValue == "websocket")
{
item.Network = nameof(ETransport.ws);
var t = item.GetTransportExtra();
if (!host.IsNullOrEmpty())
{
item.RequestHost = host.Replace("host=", "");
item.Sni = item.RequestHost;
var wsHost = host.Replace("host=", "");
t = t with { Host = wsHost };
item.Sni = wsHost;
}
if (!path.IsNullOrEmpty())
{
var pathValue = path.Replace("path=", "");
pathValue = pathValue.Replace("\\=", "=").Replace("\\,", ",").Replace("\\\\", "\\");
item.Path = pathValue;
t = t with { Path = pathValue };
}
}
else if (modeValue == "quic")
{
item.Network = nameof(ETransport.quic);
item.SetTransportExtra(t);
}
if (hasTls)
+54 -11
View File
@@ -26,6 +26,7 @@ public class VmessFmt : BaseFmt
var vmessQRCode = new VmessQRCode
{
// vmess link keeps shared transport keys; map from new transport model on export.
v = 2,
ps = item.Remarks.TrimEx(),
add = item.Address,
@@ -33,10 +34,34 @@ public class VmessFmt : BaseFmt
id = item.Password,
aid = int.TryParse(item.GetProtocolExtra()?.AlterId, out var result) ? result : 0,
scy = item.GetProtocolExtra().VmessSecurity ?? "",
net = item.Network,
type = item.HeaderType,
host = item.RequestHost,
path = item.Path,
net = item.GetNetwork() == nameof(ETransport.raw) ? Global.RawNetworkAlias : item.Network,
type = item.GetNetwork() switch
{
nameof(ETransport.raw) => item.GetTransportExtra().RawHeaderType,
nameof(ETransport.kcp) => item.GetTransportExtra().KcpHeaderType,
nameof(ETransport.xhttp) => item.GetTransportExtra().XhttpMode,
nameof(ETransport.grpc) => item.GetTransportExtra().GrpcMode,
_ => Global.None,
},
host = item.GetNetwork() switch
{
nameof(ETransport.raw) => item.GetTransportExtra().Host,
nameof(ETransport.ws) => item.GetTransportExtra().Host,
nameof(ETransport.httpupgrade) => item.GetTransportExtra().Host,
nameof(ETransport.xhttp) => item.GetTransportExtra().Host,
nameof(ETransport.grpc) => item.GetTransportExtra().GrpcAuthority,
_ => null,
},
path = item.GetNetwork() switch
{
nameof(ETransport.raw) => item.GetTransportExtra().Path,
nameof(ETransport.kcp) => item.GetTransportExtra().KcpSeed,
nameof(ETransport.ws) => item.GetTransportExtra().Path,
nameof(ETransport.httpupgrade) => item.GetTransportExtra().Path,
nameof(ETransport.xhttp) => item.GetTransportExtra().Path,
nameof(ETransport.grpc) => item.GetTransportExtra().GrpcServiceName,
_ => null,
},
tls = item.StreamSecurity,
sni = item.Sni,
alpn = item.Alpn,
@@ -70,7 +95,10 @@ public class VmessFmt : BaseFmt
}
item.Network = Global.DefaultNetwork;
item.HeaderType = Global.None;
var transport = new TransportExtraItem
{
RawHeaderType = Global.None,
};
//item.ConfigVersion = vmessQRCode.v;
item.Remarks = Utils.ToString(vmessQRCode.ps);
@@ -84,15 +112,30 @@ public class VmessFmt : BaseFmt
});
if (vmessQRCode.net.IsNotEmpty())
{
item.Network = vmessQRCode.net;
item.Network = vmessQRCode.net == Global.RawNetworkAlias ? nameof(ETransport.raw) : vmessQRCode.net;
}
if (vmessQRCode.type.IsNotEmpty())
{
item.HeaderType = vmessQRCode.type;
transport = item.GetNetwork() switch
{
nameof(ETransport.raw) => transport with { RawHeaderType = vmessQRCode.type },
nameof(ETransport.kcp) => transport with { KcpHeaderType = vmessQRCode.type },
nameof(ETransport.xhttp) => transport with { XhttpMode = vmessQRCode.type },
nameof(ETransport.grpc) => transport with { GrpcMode = vmessQRCode.type },
_ => transport,
};
}
item.RequestHost = Utils.ToString(vmessQRCode.host);
item.Path = Utils.ToString(vmessQRCode.path);
transport = item.GetNetwork() switch
{
nameof(ETransport.raw) => transport with { Host = Utils.ToString(vmessQRCode.host), Path = Utils.ToString(vmessQRCode.path) },
nameof(ETransport.kcp) => transport with { KcpSeed = Utils.ToString(vmessQRCode.path) },
nameof(ETransport.ws) => transport with { Host = Utils.ToString(vmessQRCode.host), Path = Utils.ToString(vmessQRCode.path) },
nameof(ETransport.httpupgrade) => transport with { Host = Utils.ToString(vmessQRCode.host), Path = Utils.ToString(vmessQRCode.path) },
nameof(ETransport.xhttp) => transport with { Host = Utils.ToString(vmessQRCode.host), Path = Utils.ToString(vmessQRCode.path) },
nameof(ETransport.grpc) => transport with { GrpcAuthority = Utils.ToString(vmessQRCode.host), GrpcServiceName = Utils.ToString(vmessQRCode.path) },
_ => transport,
};
item.SetTransportExtra(transport);
item.StreamSecurity = Utils.ToString(vmessQRCode.tls);
item.Sni = Utils.ToString(vmessQRCode.sni);
item.Alpn = Utils.ToString(vmessQRCode.alpn);
@@ -122,7 +165,7 @@ public class VmessFmt : BaseFmt
item.SetProtocolExtra(new ProtocolExtraItem
{
VmessSecurity = "auto",
VmessSecurity = Global.DefaultSecurity,
});
var query = Utils.ParseQueryString(url.Query);
+124 -4
View File
@@ -309,8 +309,15 @@ public sealed class AppManager
public async Task MigrateProfileExtra()
{
await MigrateProfileExtraGroup();
await MigrateProfileExtraGroupV2ToV3();
await MigrateProfileExtraV2ToV3();
await MigrateProfileTransportV3ToV4();
}
private async Task MigrateProfileExtraV2ToV3()
{
const int pageSize = 100;
var offset = 0;
@@ -326,7 +333,7 @@ public sealed class AppManager
break;
}
var batchSuccessCount = await MigrateProfileExtraSub(batch);
var batchSuccessCount = await MigrateProfileExtraV2ToV3Sub(batch);
// Only increment offset by the number of failed items that remain in the result set
// Successfully updated items are automatically excluded from future queries due to ConfigVersion = 3
@@ -336,7 +343,120 @@ public sealed class AppManager
//await ProfileGroupItemManager.Instance.ClearAll();
}
private async Task<int> MigrateProfileExtraSub(List<ProfileItem> batch)
private async Task MigrateProfileTransportV3ToV4()
{
const int pageSize = 100;
var offset = 0;
while (true)
{
var sql = $"SELECT * FROM ProfileItem WHERE ConfigVersion = 3 LIMIT {pageSize} OFFSET {offset}";
var batch = await SQLiteHelper.Instance.QueryAsync<ProfileItem>(sql);
if (batch is null || batch.Count == 0)
{
break;
}
var updateProfileItems = new List<ProfileItem>();
foreach (var item in batch)
{
try
{
if (item.Network == Global.RawNetworkAlias)
{
item.Network = nameof(ETransport.raw);
}
var transport = item.GetTransportExtra();
var network = item.GetNetwork();
switch (network)
{
case nameof(ETransport.raw):
transport = transport with
{
RawHeaderType = item.HeaderType.NullIfEmpty(),
Host = item.RequestHost.NullIfEmpty(),
Path = item.Path.NullIfEmpty(),
};
break;
case nameof(ETransport.ws):
case nameof(ETransport.httpupgrade):
transport = transport with
{
Host = item.RequestHost.NullIfEmpty(),
Path = item.Path.NullIfEmpty(),
};
break;
case nameof(ETransport.xhttp):
transport = transport with
{
Host = item.RequestHost.NullIfEmpty(),
Path = item.Path.NullIfEmpty(),
XhttpMode = item.HeaderType.NullIfEmpty(),
XhttpExtra = item.Extra.NullIfEmpty(),
};
break;
case nameof(ETransport.grpc):
transport = transport with
{
GrpcAuthority = item.RequestHost.NullIfEmpty(),
GrpcServiceName = item.Path.NullIfEmpty(),
GrpcMode = item.HeaderType.NullIfEmpty(),
};
break;
case nameof(ETransport.kcp):
transport = transport with
{
KcpHeaderType = item.HeaderType.NullIfEmpty(),
KcpSeed = item.Path.NullIfEmpty(),
};
break;
default:
item.Network = Global.DefaultNetwork;
transport = transport with
{
RawHeaderType = item.HeaderType.NullIfEmpty(),
Host = item.RequestHost.NullIfEmpty(),
};
break;
}
item.SetTransportExtra(transport);
item.ConfigVersion = 4;
updateProfileItems.Add(item);
}
catch (Exception ex)
{
Logging.SaveLog($"MigrateProfileTransportV3ToV4 Error: {ex}");
}
}
if (updateProfileItems.Count > 0)
{
try
{
var count = await SQLiteHelper.Instance.UpdateAllAsync(updateProfileItems);
offset += batch.Count - count;
}
catch (Exception ex)
{
Logging.SaveLog($"MigrateProfileTransportV3ToV4 update error: {ex}");
offset += batch.Count;
}
}
else
{
offset += batch.Count;
}
}
}
private async Task<int> MigrateProfileExtraV2ToV3Sub(List<ProfileItem> batch)
{
var updateProfileItems = new List<ProfileItem>();
@@ -434,7 +554,7 @@ public sealed class AppManager
}
}
private async Task<bool> MigrateProfileExtraGroup()
private async Task<bool> MigrateProfileExtraGroupV2ToV3()
{
var list = await SQLiteHelper.Instance.TableAsync<ProfileGroupItem>().ToListAsync();
var groupItems = new ConcurrentDictionary<string, ProfileGroupItem>(list.Where(t => !string.IsNullOrEmpty(t.IndexId)).ToDictionary(t => t.IndexId!));
+19 -8
View File
@@ -203,7 +203,7 @@ public class CertPemManager
/// <summary>
/// Get certificate in PEM format from a server with CA pinning validation
/// </summary>
public async Task<(string?, string?)> GetCertPemAsync(string target, string serverName, int timeout = 4)
public async Task<(string?, string?)> GetCertPemAsync(string target, string serverName, int timeout = 4, bool allowInsecure = false)
{
try
{
@@ -215,12 +215,14 @@ public class CertPemManager
using var client = new TcpClient();
await client.ConnectAsync(domain, port > 0 ? port : 443, cts.Token);
await using var ssl = new SslStream(client.GetStream(), false, ValidateServerCertificate);
var callback = new RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) =>
ValidateServerCertificate(sender, certificate, chain, sslPolicyErrors, allowInsecure));
await using var ssl = new SslStream(client.GetStream(), false, callback);
var sslOptions = new SslClientAuthenticationOptions
{
TargetHost = serverName,
RemoteCertificateValidationCallback = ValidateServerCertificate
RemoteCertificateValidationCallback = callback
};
await ssl.AuthenticateAsClientAsync(sslOptions, cts.Token);
@@ -249,7 +251,7 @@ public class CertPemManager
/// <summary>
/// Get certificate chain in PEM format from a server with CA pinning validation
/// </summary>
public async Task<(List<string>, string?)> GetCertChainPemAsync(string target, string serverName, int timeout = 4)
public async Task<(List<string>, string?)> GetCertChainPemAsync(string target, string serverName, int timeout = 4, bool allowInsecure = false)
{
var pemList = new List<string>();
try
@@ -262,12 +264,14 @@ public class CertPemManager
using var client = new TcpClient();
await client.ConnectAsync(domain, port > 0 ? port : 443, cts.Token);
await using var ssl = new SslStream(client.GetStream(), false, ValidateServerCertificate);
var callback = new RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) =>
ValidateServerCertificate(sender, certificate, chain, sslPolicyErrors, allowInsecure));
await using var ssl = new SslStream(client.GetStream(), false, callback);
var sslOptions = new SslClientAuthenticationOptions
{
TargetHost = serverName,
RemoteCertificateValidationCallback = ValidateServerCertificate
RemoteCertificateValidationCallback = callback
};
await ssl.AuthenticateAsClientAsync(sslOptions, cts.Token);
@@ -300,16 +304,23 @@ public class CertPemManager
/// Validate server certificate with CA pinning
/// </summary>
private bool ValidateServerCertificate(
object sender,
object _,
X509Certificate? certificate,
X509Chain? chain,
SslPolicyErrors sslPolicyErrors)
SslPolicyErrors sslPolicyErrors,
bool allowInsecure)
{
if (certificate == null)
{
return false;
}
// In insecure mode, accept any certificate so self-signed certs can be fetched.
if (allowInsecure)
{
return true;
}
// Check certificate name mismatch
if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
{
+4 -5
View File
@@ -49,11 +49,9 @@ public class KcpItem
public int DownlinkCapacity { get; set; }
public bool Congestion { get; set; }
public int CwndMultiplier { get; set; }
public int ReadBufferSize { get; set; }
public int WriteBufferSize { get; set; }
public int MaxSendingWindow { get; set; }
}
[Serializable]
@@ -158,6 +156,7 @@ public class SpeedTestItem
public string SpeedPingTestUrl { get; set; }
public int MixedConcurrencyCount { get; set; }
public string IPAPIUrl { get; set; }
public string UdpTestTarget { get; set; }
}
[Serializable]
@@ -197,7 +196,7 @@ public class HysteriaItem
{
public int UpMbps { get; set; }
public int DownMbps { get; set; }
public int HopInterval { get; set; } = 30;
public int HopInterval { get; set; } = Global.Hysteria2DefaultHopInt;
}
[Serializable]
@@ -16,10 +16,5 @@ public record CoreConfigContext
// TUN Compatibility
public bool IsTunEnabled { get; init; } = false;
public HashSet<string> ProtectDomainList { get; init; } = new();
// -> tun inbound --(if routing proxy)--> relay outbound
// -> proxy core (relay inbound --> proxy outbound --(dialerProxy)--> protect outbound)
// -> protect inbound -> direct proxy outbound data -> internet
public int TunProtectSocksPort { get; init; } = 0;
public int ProxyRelaySocksPort { get; init; } = 0;
public HashSet<string> ProtectDomainList { get; init; } = [];
}
+23 -9
View File
@@ -4,12 +4,13 @@ namespace ServiceLib.Models;
public class ProfileItem
{
private ProtocolExtraItem? _protocolExtraCache;
private TransportExtraItem? _transportExtraCache;
public ProfileItem()
{
IndexId = string.Empty;
ConfigType = EConfigType.VMess;
ConfigVersion = 3;
ConfigVersion = 4;
Subid = string.Empty;
Address = string.Empty;
Port = 0;
@@ -17,9 +18,6 @@ public class ProfileItem
Username = string.Empty;
Network = string.Empty;
Remarks = string.Empty;
HeaderType = string.Empty;
RequestHost = string.Empty;
Path = string.Empty;
StreamSecurity = string.Empty;
AllowInsecure = string.Empty;
}
@@ -126,20 +124,26 @@ public class ProfileItem
return true;
}
public ProtocolExtraItem GetProtocolExtra()
{
return _protocolExtraCache ??= JsonUtils.Deserialize<ProtocolExtraItem>(ProtoExtra) ?? new ProtocolExtraItem();
}
public void SetProtocolExtra(ProtocolExtraItem extraItem)
{
_protocolExtraCache = extraItem;
ProtoExtra = JsonUtils.Serialize(extraItem, false);
}
public void SetProtocolExtra()
public TransportExtraItem GetTransportExtra()
{
ProtoExtra = JsonUtils.Serialize(_protocolExtraCache, false);
return _transportExtraCache ??= JsonUtils.Deserialize<TransportExtraItem>(TransportExtra) ?? new TransportExtraItem();
}
public ProtocolExtraItem GetProtocolExtra()
public void SetTransportExtra(TransportExtraItem transportExtra)
{
return _protocolExtraCache ??= JsonUtils.Deserialize<ProtocolExtraItem>(ProtoExtra) ?? new ProtocolExtraItem();
_transportExtraCache = transportExtra;
TransportExtra = JsonUtils.Serialize(transportExtra, false);
}
#endregion function
@@ -160,9 +164,16 @@ public class ProfileItem
public string Password { get; set; }
public string Username { get; set; }
public string Network { get; set; }
[Obsolete("Use TransportExtra.RawHeaderType/XhttpMode/GrpcMode/KcpHeaderType instead.")]
public string HeaderType { get; set; }
[Obsolete("Use TransportExtra.Host/GrpcAuthority instead.")]
public string RequestHost { get; set; }
[Obsolete("Use TransportExtra.Path/GrpcServiceName/KcpSeed instead.")]
public string Path { get; set; }
public string StreamSecurity { get; set; }
public string AllowInsecure { get; set; }
public string Sni { get; set; }
@@ -172,15 +183,18 @@ public class ProfileItem
public string ShortId { get; set; }
public string SpiderX { get; set; }
public string Mldsa65Verify { get; set; }
[Obsolete("Use TransportExtra.XhttpExtra instead.")]
public string Extra { get; set; }
public bool? MuxEnabled { get; set; }
public string Cert { get; set; }
public string CertSha { get; set; }
public string EchConfigList { get; set; }
public string EchForceQuery { get; set; }
public string Finalmask { get; set; }
public string ProtoExtra { get; set; }
public string TransportExtra { get; set; }
[Obsolete("Use ProtocolExtraItem.Ports instead.")]
public string Ports { get; set; }
+1 -8
View File
@@ -237,6 +237,7 @@ public class Transport4Sbox
public class Headers4Sbox
{
public string? Host { get; set; }
[JsonPropertyName("User-Agent")]
public string UserAgent { get; set; }
}
@@ -261,14 +262,6 @@ public class Server4Sbox : BaseServer4Sbox
// public List<string>? path { get; set; } // hosts
public Dictionary<string, List<string>>? predefined { get; set; }
// Deprecated in sing-box 1.12.0 , kept for backward compatibility
public string? address { get; set; }
public string? address_resolver { get; set; }
public string? address_strategy { get; set; }
public string? strategy { get; set; }
// Deprecated End
}
public class Experimental4Sbox
@@ -0,0 +1,19 @@
namespace ServiceLib.Models;
public record TransportExtraItem
{
public string? RawHeaderType { get; init; }
public string? Host { get; init; }
public string? Path { get; init; }
public string? XhttpMode { get; init; }
public string? XhttpExtra { get; init; }
public string? GrpcAuthority { get; init; }
public string? GrpcServiceName { get; init; }
public string? GrpcMode { get; init; }
public string? KcpHeaderType { get; init; }
public string? KcpSeed { get; init; }
public int? KcpMtu { get; init; }
}
+40 -11
View File
@@ -47,9 +47,9 @@ public class Inbounds4Ray
{
public string tag { get; set; }
public int port { get; set; }
public int? port { get; set; }
public string listen { get; set; }
public string? listen { get; set; }
public string protocol { get; set; }
@@ -75,6 +75,18 @@ public class Inboundsettings4Ray
public bool? allowTransparent { get; set; }
public List<AccountsItem4Ray>? accounts { get; set; }
public string? name { get; set; }
public int? MTU { get; set; }
public List<string>? gateway { get; set; }
public List<string>? autoSystemRoutingTable { get; set; }
public string? autoOutboundsInterface { get; set; }
// public List<string>? dns { get; set; }
}
public class UsersItem4Ray
@@ -128,11 +140,10 @@ public class Outboundsettings4Ray
public int? userLevel { get; set; }
public FragmentItem4Ray? fragment { get; set; }
public string? secretKey { get; set; }
public Object? address { get; set; }
public object? address { get; set; }
public int? port { get; set; }
public List<WireguardPeer4Ray>? peers { get; set; }
@@ -319,7 +330,7 @@ public class StreamSettings4Ray
public TlsSettings4Ray? tlsSettings { get; set; }
public TcpSettings4Ray? tcpSettings { get; set; }
public RawSettings4Ray? rawSettings { get; set; }
public KcpSettings4Ray? kcpSettings { get; set; }
@@ -373,7 +384,7 @@ public class CertificateSettings4Ray
public string? usage { get; set; }
}
public class TcpSettings4Ray
public class RawSettings4Ray
{
public Header4Ray header { get; set; }
}
@@ -397,11 +408,9 @@ public class KcpSettings4Ray
public int downlinkCapacity { get; set; }
public bool congestion { get; set; }
public int cwndMultiplier { get; set; }
public int readBufferSize { get; set; }
public int writeBufferSize { get; set; }
public int maxSendingWindow { get; set; }
}
public class WsSettings4Ray
@@ -491,6 +500,23 @@ public class MaskSettings4Ray
{
public string? password { get; set; }
public string? domain { get; set; }
// fragment
public string? packets { get; set; }
public string? length { get; set; }
public string? delay { get; set; }
// noise
public int? reset { get; set; }
public List<NoiseMask4Ray>? noise { get; set; }
}
public class NoiseMask4Ray
{
public string? rand { get; set; }
public string? delay { get; set; }
}
public class QuicParams4Ray
@@ -511,6 +537,9 @@ public class AccountsItem4Ray
public class Sockopt4Ray
{
public string? dialerProxy { get; set; }
[JsonPropertyName("interface")]
public string? Interface { get; set; }
}
public class FragmentItem4Ray
+85 -49
View File
@@ -106,7 +106,7 @@ namespace ServiceLib.Resx {
}
/// <summary>
/// 查找类似 Please check the Configuration settings first. 的本地化字符串。
/// 查找类似 Invalid configuration, please check or reselect 的本地化字符串。
/// </summary>
public static string CheckServerSettings {
get {
@@ -1860,6 +1860,15 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 Test Configurations UDP Delay 的本地化字符串。
/// </summary>
public static string menuUdpTestServer {
get {
return ResourceManager.GetString("menuUdpTestServer", resourceCulture);
}
}
/// <summary>
/// 查找类似 {0} Website 的本地化字符串。
/// </summary>
@@ -2580,6 +2589,24 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 Allow insecure cert fetch (self-signed) 的本地化字符串。
/// </summary>
public static string TbAllowInsecureCertFetch {
get {
return ResourceManager.GetString("TbAllowInsecureCertFetch", resourceCulture);
}
}
/// <summary>
/// 查找类似 Only for fetching self-signed certificates. This may expose you to MITM risks. 的本地化字符串。
/// </summary>
public static string TbAllowInsecureCertFetchTips {
get {
return ResourceManager.GetString("TbAllowInsecureCertFetchTips", resourceCulture);
}
}
/// <summary>
/// 查找类似 ALPN 的本地化字符串。
/// </summary>
@@ -2670,6 +2697,15 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 Camouflage domain 的本地化字符串。
/// </summary>
public static string TbCamouflageDomain {
get {
return ResourceManager.GetString("TbCamouflageDomain", resourceCulture);
}
}
/// <summary>
/// 查找类似 Cancel 的本地化字符串。
/// </summary>
@@ -2845,7 +2881,7 @@ namespace ServiceLib.Resx {
}
/// <summary>
/// 查找类似 Supports DNS Object; Click to view documentation 的本地化字符串。
/// 查找类似 Please fill in DNS Object; Click to view documentation 的本地化字符串。
/// </summary>
public static string TbDnsObjectDoc {
get {
@@ -2907,15 +2943,6 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 EchForceQuery 的本地化字符串。
/// </summary>
public static string TbEchForceQuery {
get {
return ResourceManager.GetString("TbEchForceQuery", resourceCulture);
}
}
/// <summary>
/// 查找类似 Edit 的本地化字符串。
/// </summary>
@@ -3087,6 +3114,15 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 Host 的本地化字符串。
/// </summary>
public static string TbHost {
get {
return ResourceManager.GetString("TbHost", resourceCulture);
}
}
/// <summary>
/// 查找类似 ICMP routing policy 的本地化字符串。
/// </summary>
@@ -3393,15 +3429,6 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 Camouflage domain(host) 的本地化字符串。
/// </summary>
public static string TbRequestHost {
get {
return ResourceManager.GetString("TbRequestHost", resourceCulture);
}
}
/// <summary>
/// 查找类似 Reserved (2,3,4) 的本地化字符串。
/// </summary>
@@ -3772,7 +3799,7 @@ namespace ServiceLib.Resx {
}
/// <summary>
/// 查找类似 This parameter is valid only for tcp/http, ws, gRPC and xhttp 的本地化字符串。
/// 查找类似 This parameter is valid only for raw/http, ws, gRPC and xhttp 的本地化字符串。
/// </summary>
public static string TbSettingsDefUserAgentTips {
get {
@@ -4122,15 +4149,6 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 Custom DNS (multiple, separated by commas (,)) 的本地化字符串。
/// </summary>
public static string TbSettingsRemoteDNS {
get {
return ResourceManager.GetString("TbSettingsRemoteDNS", resourceCulture);
}
}
/// <summary>
/// 查找类似 Route Only 的本地化字符串。
/// </summary>
@@ -4365,6 +4383,15 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 UDP Test Url 的本地化字符串。
/// </summary>
public static string TbSettingsUdpTestUrl {
get {
return ResourceManager.GetString("TbSettingsUdpTestUrl", resourceCulture);
}
}
/// <summary>
/// 查找类似 Auth user 的本地化字符串。
/// </summary>
@@ -4654,7 +4681,7 @@ namespace ServiceLib.Resx {
}
/// <summary>
/// 查找类似 *Default value tcp 的本地化字符串。
/// 查找类似 *Default value raw 的本地化字符串。
/// </summary>
public static string TipNetwork {
get {
@@ -4672,7 +4699,16 @@ namespace ServiceLib.Resx {
}
/// <summary>
/// 查找类似 XHTTP Extra raw JSON, format: { XHTTP Object } 的本地化字符串。
/// 查找类似 XHTTP Extra 的本地化字符串。
/// </summary>
public static string TransportExtra {
get {
return ResourceManager.GetString("TransportExtra", resourceCulture);
}
}
/// <summary>
/// 查找类似 Raw JSON, format: { XHTTP Object } 的本地化字符串。
/// </summary>
public static string TransportExtraTip {
get {
@@ -4681,47 +4717,47 @@ namespace ServiceLib.Resx {
}
/// <summary>
/// 查找类似 *tcp camouflage type 的本地化字符串。
/// 查找类似 raw camouflage type 的本地化字符串。
/// </summary>
public static string TransportHeaderTypeTip1 {
public static string TransportHeaderType1 {
get {
return ResourceManager.GetString("TransportHeaderTypeTip1", resourceCulture);
return ResourceManager.GetString("TransportHeaderType1", resourceCulture);
}
}
/// <summary>
/// 查找类似 *kcp camouflage type 的本地化字符串。
/// 查找类似 kcp camouflage type 的本地化字符串。
/// </summary>
public static string TransportHeaderTypeTip2 {
public static string TransportHeaderType2 {
get {
return ResourceManager.GetString("TransportHeaderTypeTip2", resourceCulture);
return ResourceManager.GetString("TransportHeaderType2", resourceCulture);
}
}
/// <summary>
/// 查找类似 *QUIC camouflage type 的本地化字符串。
/// 查找类似 QUIC camouflage type 的本地化字符串。
/// </summary>
public static string TransportHeaderTypeTip3 {
public static string TransportHeaderType3 {
get {
return ResourceManager.GetString("TransportHeaderTypeTip3", resourceCulture);
return ResourceManager.GetString("TransportHeaderType3", resourceCulture);
}
}
/// <summary>
/// 查找类似 *grpc mode 的本地化字符串。
/// 查找类似 gRPC mode 的本地化字符串。
/// </summary>
public static string TransportHeaderTypeTip4 {
public static string TransportHeaderType4 {
get {
return ResourceManager.GetString("TransportHeaderTypeTip4", resourceCulture);
return ResourceManager.GetString("TransportHeaderType4", resourceCulture);
}
}
/// <summary>
/// 查找类似 *xhttp mode 的本地化字符串。
/// 查找类似 xhttp mode 的本地化字符串。
/// </summary>
public static string TransportHeaderTypeTip5 {
public static string TransportHeaderType5 {
get {
return ResourceManager.GetString("TransportHeaderTypeTip5", resourceCulture);
return ResourceManager.GetString("TransportHeaderType5", resourceCulture);
}
}
@@ -4753,7 +4789,7 @@ namespace ServiceLib.Resx {
}
/// <summary>
/// 查找类似 *grpc service name 的本地化字符串。
/// 查找类似 gRPC service name 的本地化字符串。
/// </summary>
public static string TransportPathTip4 {
get {
@@ -4807,7 +4843,7 @@ namespace ServiceLib.Resx {
}
/// <summary>
/// 查找类似 *grpc Authority 的本地化字符串。
/// 查找类似 gRPC Authority 的本地化字符串。
/// </summary>
public static string TransportRequestHostTip5 {
get {
+36 -24
View File
@@ -343,7 +343,7 @@
<value>*QUIC key/Kcp seed</value>
</data>
<data name="TransportPathTip4" xml:space="preserve">
<value>*grpc serviceName</value>
<value>gRPC serviceName</value>
</data>
<data name="TransportRequestHostTip1" xml:space="preserve">
<value>*هاست http جدا شده با کاما (،)</value>
@@ -357,17 +357,17 @@
<data name="TransportRequestHostTip4" xml:space="preserve">
<value>*QUIC securty</value>
</data>
<data name="TransportHeaderTypeTip1" xml:space="preserve">
<value>*tcp camouflage type</value>
<data name="TransportHeaderType1" xml:space="preserve">
<value>raw camouflage type</value>
</data>
<data name="TransportHeaderTypeTip2" xml:space="preserve">
<value>*kcp camouflage type</value>
<data name="TransportHeaderType2" xml:space="preserve">
<value>kcp camouflage type</value>
</data>
<data name="TransportHeaderTypeTip3" xml:space="preserve">
<value>*QUIC camouflage type</value>
<data name="TransportHeaderType3" xml:space="preserve">
<value>QUIC camouflage type</value>
</data>
<data name="TransportHeaderTypeTip4" xml:space="preserve">
<value>*حالت grpc</value>
<data name="TransportHeaderType4" xml:space="preserve">
<value>حالت grpc</value>
</data>
<data name="LvTLS" xml:space="preserve">
<value>TLS</value>
@@ -606,9 +606,6 @@
<data name="TbRemarks" xml:space="preserve">
<value>نام مستعار (ملاحظات)</value>
</data>
<data name="TbRequestHost" xml:space="preserve">
<value>Camouflage domain(host)</value>
</data>
<data name="TbSecurity" xml:space="preserve">
<value>روش رمزگذاری (امنیتی)</value>
</data>
@@ -619,7 +616,7 @@
<value>TLS</value>
</data>
<data name="TipNetwork" xml:space="preserve">
<value>*مقدار پیش فرض tcp</value>
<value>*مقدار پیش فرض raw</value>
</data>
<data name="TbCoreType" xml:space="preserve">
<value>نوع هسته</value>
@@ -723,9 +720,6 @@
<data name="TbSettingsPass" xml:space="preserve">
<value>مجوز احراز هویت</value>
</data>
<data name="TbSettingsRemoteDNS" xml:space="preserve">
<value>سفارشی DNS (multiple, separated by commas (,))</value>
</data>
<data name="TbSettingsSetUWP" xml:space="preserve">
<value>تنظیم کردن Win10 UWP Loopback</value>
</data>
@@ -937,7 +931,7 @@
<value>User-Agent</value>
</data>
<data name="TbSettingsDefUserAgentTips" xml:space="preserve">
<value>This parameter is valid only for tcp/http, ws, gRPC and xhttp</value>
<value>This parameter is valid only for raw/http, ws, gRPC and xhttp</value>
</data>
<data name="TbSettingsCurrentFontFamily" xml:space="preserve">
<value>FontFamily (نیاز به راه اندازی مجدد)</value>
@@ -1102,7 +1096,7 @@
<value>پایان تست...</value>
</data>
<data name="TransportRequestHostTip5" xml:space="preserve">
<value>*grpc Authority</value>
<value>RPC Authority</value>
</data>
<data name="menuAddHttpServer" xml:space="preserve">
<value>افزودن سرور [HTTP]</value>
@@ -1320,11 +1314,11 @@
<data name="TbSettingsLinuxSudoPasswordTip" xml:space="preserve">
<value>The password will be validated via the command line. If a validation error causes the application to malfunction, please restart the application. The password will not be stored and must be entered again after each restart.</value>
</data>
<data name="TransportHeaderTypeTip5" xml:space="preserve">
<value>*حالت xhttp</value>
<data name="TransportHeaderType5" xml:space="preserve">
<value>حالت xhttp</value>
</data>
<data name="TransportExtraTip" xml:space="preserve">
<value>جیسون خام XHTTP Extra, فرمت: { XHTTPObject }</value>
<value>Raw JSON, format: { XHTTP Object }</value>
</data>
<data name="TbSettingsHide2TrayWhenClose" xml:space="preserve">
<value>هنگام بستن پنجره در سینی پنهان شوید</value>
@@ -1587,9 +1581,6 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if
<data name="TbEchConfigList" xml:space="preserve">
<value>EchConfigList</value>
</data>
<data name="TbEchForceQuery" xml:space="preserve">
<value>EchForceQuery</value>
</data>
<data name="TbFullCertTips" xml:space="preserve">
<value>Full certificate (chain), PEM format</value>
</data>
@@ -1701,4 +1692,25 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if
<data name="TbSettingsSendThroughTip" xml:space="preserve">
<value>For multi-interface environments, enter the local machine's IPv4 address</value>
</data>
<data name="TbCamouflageDomain" xml:space="preserve">
<value>Camouflage domain</value>
</data>
<data name="TbHost" xml:space="preserve">
<value>Host</value>
</data>
<data name="TransportExtra" xml:space="preserve">
<value>XHTTP Extra</value>
</data>
<data name="TbAllowInsecureCertFetch" xml:space="preserve">
<value>Allow insecure cert fetch (self-signed)</value>
</data>
<data name="TbAllowInsecureCertFetchTips" xml:space="preserve">
<value>Only for fetching self-signed certificates. This may expose you to MITM risks.</value>
</data>
<data name="menuUdpTestServer" xml:space="preserve">
<value>Test Configurations UDP Delay</value>
</data>
<data name="TbSettingsUdpTestUrl" xml:space="preserve">
<value>UDP Test Url</value>
</data>
</root>
+31 -28
View File
@@ -343,7 +343,7 @@
<value>*clé de chiffrement QUIC</value>
</data>
<data name="TransportPathTip4" xml:space="preserve">
<value>*nom de service gRPC</value>
<value>nom de service gRPC</value>
</data>
<data name="TransportRequestHostTip1" xml:space="preserve">
<value>*hôte http, séparés par des virgules (,)</value>
@@ -357,17 +357,17 @@
<data name="TransportRequestHostTip4" xml:space="preserve">
<value>*méthode de chiffrement QUIC</value>
</data>
<data name="TransportHeaderTypeTip1" xml:space="preserve">
<value>*type de camouflage tcp</value>
<data name="TransportHeaderType1" xml:space="preserve">
<value>type de camouflage raw</value>
</data>
<data name="TransportHeaderTypeTip2" xml:space="preserve">
<value>*type de camouflage kcp</value>
<data name="TransportHeaderType2" xml:space="preserve">
<value>type de camouflage kcp</value>
</data>
<data name="TransportHeaderTypeTip3" xml:space="preserve">
<value>*type de camouflage QUIC</value>
<data name="TransportHeaderType3" xml:space="preserve">
<value>type de camouflage QUIC</value>
</data>
<data name="TransportHeaderTypeTip4" xml:space="preserve">
<value>*mode gRPC</value>
<data name="TransportHeaderType4" xml:space="preserve">
<value>mode gRPC</value>
</data>
<data name="LvTLS" xml:space="preserve">
<value>TLS</value>
@@ -606,9 +606,6 @@
<data name="TbRemarks" xml:space="preserve">
<value>Alias (remarks)</value>
</data>
<data name="TbRequestHost" xml:space="preserve">
<value>Domaine de camouflage (host)</value>
</data>
<data name="TbSecurity" xml:space="preserve">
<value>Méthode de chiffrement (security)</value>
</data>
@@ -619,7 +616,7 @@
<value>Sécurité couche transport (TLS)</value>
</data>
<data name="TipNetwork" xml:space="preserve">
<value>*tcp par défaut ; un mauvais choix bloque la connexion</value>
<value>*raw par défaut ; un mauvais choix bloque la connexion</value>
</data>
<data name="TbCoreType" xml:space="preserve">
<value>Type de Core</value>
@@ -723,9 +720,6 @@
<data name="TbSettingsPass" xml:space="preserve">
<value>Mot de passe dauthentification</value>
</data>
<data name="TbSettingsRemoteDNS" xml:space="preserve">
<value>DNS perso (plusieurs configurables, séparés par virgules)</value>
</data>
<data name="TbSettingsSetUWP" xml:space="preserve">
<value>Lever la restriction de proxy en boucle locale pour les applications Win10 UWP</value>
</data>
@@ -937,7 +931,7 @@
<value>Agent utilisateur (User-Agent)</value>
</data>
<data name="TbSettingsDefUserAgentTips" xml:space="preserve">
<value>This parameter is valid only for tcp/http, ws, gRPC and xhttp</value>
<value>This parameter is valid only for raw/http, ws, gRPC and xhttp</value>
</data>
<data name="TbSettingsCurrentFontFamily" xml:space="preserve">
<value>Police actuelle (redémarrage requis)</value>
@@ -1099,7 +1093,7 @@
<value>Arrêt du test en cours...</value>
</data>
<data name="TransportRequestHostTip5" xml:space="preserve">
<value>*Autorité gRPC</value>
<value>Autorité gRPC</value>
</data>
<data name="menuAddHttpServer" xml:space="preserve">
<value>Ajouter [HTTP]</value>
@@ -1321,16 +1315,16 @@
<value>Adresse sortante locale (SendThrough)</value>
</data>
<data name="TbSettingsSendThroughTip" xml:space="preserve">
<value>Pour environnement multi-interfaces, veuillez saisir ladresse IPv4 de la machine locale.</value>
<value>Pour environnements multi-interfaces, entrez l'adresse IPv4 de la machine locale.</value>
</data>
<data name="FillCorrectSendThroughIPv4" xml:space="preserve">
<value>Veuillez saisir ladresse IPv4 correcte de SendThrough.</value>
</data>
<data name="TransportHeaderTypeTip5" xml:space="preserve">
<value>*Mode XHTTP</value>
<data name="TransportHeaderType5" xml:space="preserve">
<value>Mode XHTTP</value>
</data>
<data name="TransportExtraTip" xml:space="preserve">
<value>JSON brut XHTTP Extra, format : { XHTTPObject }</value>
<value>Raw JSON, format: { XHTTP Object }</value>
</data>
<data name="TbSettingsHide2TrayWhenClose" xml:space="preserve">
<value>Masquer dans la barre d’état à la fermeture de la fenêtre</value>
@@ -1593,9 +1587,6 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if
<data name="TbEchConfigList" xml:space="preserve">
<value>EchConfigList</value>
</data>
<data name="TbEchForceQuery" xml:space="preserve">
<value>EchForceQuery</value>
</data>
<data name="TbFullCertTips" xml:space="preserve">
<value>Certificat complet (chaîne), format PEM</value>
</data>
@@ -1704,7 +1695,19 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if
<data name="TbLegacyProtect" xml:space="preserve">
<value>Protection TUN héritée</value>
</data>
<data name="TbSettingsSendThroughTip" xml:space="preserve">
<value>Pour environnements multi-interfaces, entrez ladresse IPv4 de la machine locale.</value>
<data name="TbCamouflageDomain" xml:space="preserve">
<value>Domaine de camouflage</value>
</data>
</root>
<data name="TbHost" xml:space="preserve">
<value>Host</value>
</data>
<data name="TransportExtra" xml:space="preserve">
<value>XHTTP Extra</value>
</data>
<data name="TbAllowInsecureCertFetch" xml:space="preserve">
<value>Allow insecure cert fetch (self-signed)</value>
</data>
<data name="TbAllowInsecureCertFetchTips" xml:space="preserve">
<value>Only for fetching self-signed certificates. This may expose you to MITM risks.</value>
</data>
</root>
+36 -24
View File
@@ -343,7 +343,7 @@
<value>*QUIC kulcs/KCP seed</value>
</data>
<data name="TransportPathTip4" xml:space="preserve">
<value>*grpc szolgáltatásnév</value>
<value>gRPC szolgáltatásnév</value>
</data>
<data name="TransportRequestHostTip1" xml:space="preserve">
<value>*http host vesszővel elválasztva (,)</value>
@@ -357,17 +357,17 @@
<data name="TransportRequestHostTip4" xml:space="preserve">
<value>*QUIC biztonság</value>
</data>
<data name="TransportHeaderTypeTip1" xml:space="preserve">
<value>*tcp álcázási típus</value>
<data name="TransportHeaderType1" xml:space="preserve">
<value>raw álcázási típus</value>
</data>
<data name="TransportHeaderTypeTip2" xml:space="preserve">
<value>*kcp álcázási típus</value>
<data name="TransportHeaderType2" xml:space="preserve">
<value>kcp álcázási típus</value>
</data>
<data name="TransportHeaderTypeTip3" xml:space="preserve">
<value>*QUIC álcázási típus</value>
<data name="TransportHeaderType3" xml:space="preserve">
<value>QUIC álcázási típus</value>
</data>
<data name="TransportHeaderTypeTip4" xml:space="preserve">
<value>*grpc mód</value>
<data name="TransportHeaderType4" xml:space="preserve">
<value>gRPC mód</value>
</data>
<data name="LvTLS" xml:space="preserve">
<value>TLS</value>
@@ -606,9 +606,6 @@
<data name="TbRemarks" xml:space="preserve">
<value>Alias (megjegyzések)</value>
</data>
<data name="TbRequestHost" xml:space="preserve">
<value>Álcázási tartomány(host)</value>
</data>
<data name="TbSecurity" xml:space="preserve">
<value>Titkosítási módszer (biztonság)</value>
</data>
@@ -619,7 +616,7 @@
<value>TLS</value>
</data>
<data name="TipNetwork" xml:space="preserve">
<value>*Alapértelmezett érték tcp</value>
<value>*Alapértelmezett érték raw</value>
</data>
<data name="TbCoreType" xml:space="preserve">
<value>Core Típus</value>
@@ -723,9 +720,6 @@
<data name="TbSettingsPass" xml:space="preserve">
<value>Hitelesítési jelszó</value>
</data>
<data name="TbSettingsRemoteDNS" xml:space="preserve">
<value>Egyéni DNS (több, vesszővel (,) elválasztva)</value>
</data>
<data name="TbSettingsSetUWP" xml:space="preserve">
<value>Win10 UWP Loopback beállítása</value>
</data>
@@ -937,7 +931,7 @@
<value>User-Agent</value>
</data>
<data name="TbSettingsDefUserAgentTips" xml:space="preserve">
<value>This parameter is valid only for tcp/http, ws, gRPC and xhttp</value>
<value>This parameter is valid only for raw/http, ws, gRPC and xhttp</value>
</data>
<data name="TbSettingsCurrentFontFamily" xml:space="preserve">
<value>Betűtípus (újraindítást igényel)</value>
@@ -1102,7 +1096,7 @@
<value>Teszt megszakítása...</value>
</data>
<data name="TransportRequestHostTip5" xml:space="preserve">
<value>*grpc Authority</value>
<value>gRPC Authority</value>
</data>
<data name="menuAddHttpServer" xml:space="preserve">
<value>HTTP konfiguráció hozzáadása</value>
@@ -1320,11 +1314,11 @@
<data name="TbSettingsLinuxSudoPasswordTip" xml:space="preserve">
<value>A jelszót a parancssoron keresztül ellenőrizzük. Ha egy érvényesítési hiba miatt az alkalmazás hibásan működik, indítsa újra az alkalmazást. A jelszó nem kerül tárolásra, és minden újraindítás után újra meg kell adni.</value>
</data>
<data name="TransportHeaderTypeTip5" xml:space="preserve">
<value>*xhttp mód</value>
<data name="TransportHeaderType5" xml:space="preserve">
<value>xhttp mód</value>
</data>
<data name="TransportExtraTip" xml:space="preserve">
<value>XHTTP Extra nyers JSON, formátum: { XHTTP Objektum }</value>
<value>Raw JSON, format: { XHTTP Object }</value>
</data>
<data name="TbSettingsHide2TrayWhenClose" xml:space="preserve">
<value>Ablak bezárásakor a tálcára rejtés</value>
@@ -1587,9 +1581,6 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if
<data name="TbEchConfigList" xml:space="preserve">
<value>EchConfigList</value>
</data>
<data name="TbEchForceQuery" xml:space="preserve">
<value>EchForceQuery</value>
</data>
<data name="TbFullCertTips" xml:space="preserve">
<value>Full certificate (chain), PEM format</value>
</data>
@@ -1701,4 +1692,25 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if
<data name="TbSettingsSendThroughTip" xml:space="preserve">
<value>For multi-interface environments, enter the local machine's IPv4 address</value>
</data>
<data name="TbCamouflageDomain" xml:space="preserve">
<value>Álcázási tartomány</value>
</data>
<data name="TbHost" xml:space="preserve">
<value>Host</value>
</data>
<data name="TransportExtra" xml:space="preserve">
<value>XHTTP Extra</value>
</data>
<data name="TbAllowInsecureCertFetch" xml:space="preserve">
<value>Allow insecure cert fetch (self-signed)</value>
</data>
<data name="TbAllowInsecureCertFetchTips" xml:space="preserve">
<value>Only for fetching self-signed certificates. This may expose you to MITM risks.</value>
</data>
<data name="menuUdpTestServer" xml:space="preserve">
<value>Test Configurations UDP Delay</value>
</data>
<data name="TbSettingsUdpTestUrl" xml:space="preserve">
<value>UDP Test Url</value>
</data>
</root>
+39 -27
View File
@@ -121,7 +121,7 @@
<value>Export share link to clipboard successfully</value>
</data>
<data name="CheckServerSettings" xml:space="preserve">
<value>Please check the Configuration settings first.</value>
<value>Invalid configuration, please check or reselect</value>
</data>
<data name="ConfigurationFormatIncorrect" xml:space="preserve">
<value>Invalid configuration format.</value>
@@ -343,7 +343,7 @@
<value>*QUIC key/KCP seed</value>
</data>
<data name="TransportPathTip4" xml:space="preserve">
<value>*grpc service name</value>
<value>gRPC service name</value>
</data>
<data name="TransportRequestHostTip1" xml:space="preserve">
<value>*http host separated by commas (,)</value>
@@ -357,17 +357,17 @@
<data name="TransportRequestHostTip4" xml:space="preserve">
<value>*QUIC security</value>
</data>
<data name="TransportHeaderTypeTip1" xml:space="preserve">
<value>*tcp camouflage type</value>
<data name="TransportHeaderType1" xml:space="preserve">
<value>raw camouflage type</value>
</data>
<data name="TransportHeaderTypeTip2" xml:space="preserve">
<value>*kcp camouflage type</value>
<data name="TransportHeaderType2" xml:space="preserve">
<value>kcp camouflage type</value>
</data>
<data name="TransportHeaderTypeTip3" xml:space="preserve">
<value>*QUIC camouflage type</value>
<data name="TransportHeaderType3" xml:space="preserve">
<value>QUIC camouflage type</value>
</data>
<data name="TransportHeaderTypeTip4" xml:space="preserve">
<value>*grpc mode</value>
<data name="TransportHeaderType4" xml:space="preserve">
<value>gRPC mode</value>
</data>
<data name="LvTLS" xml:space="preserve">
<value>TLS</value>
@@ -606,9 +606,6 @@
<data name="TbRemarks" xml:space="preserve">
<value>Alias (remarks)</value>
</data>
<data name="TbRequestHost" xml:space="preserve">
<value>Camouflage domain(host)</value>
</data>
<data name="TbSecurity" xml:space="preserve">
<value>Encryption method (security)</value>
</data>
@@ -619,7 +616,7 @@
<value>TLS</value>
</data>
<data name="TipNetwork" xml:space="preserve">
<value>*Default value tcp</value>
<value>*Default value raw</value>
</data>
<data name="TbCoreType" xml:space="preserve">
<value>Core Type</value>
@@ -723,9 +720,6 @@
<data name="TbSettingsPass" xml:space="preserve">
<value>Auth pass</value>
</data>
<data name="TbSettingsRemoteDNS" xml:space="preserve">
<value>Custom DNS (multiple, separated by commas (,))</value>
</data>
<data name="TbSettingsSetUWP" xml:space="preserve">
<value>Set Win10 UWP Loopback</value>
</data>
@@ -865,7 +859,7 @@
<value>Rule object Doc</value>
</data>
<data name="TbDnsObjectDoc" xml:space="preserve">
<value>Supports DNS Object; Click to view documentation</value>
<value>Please fill in DNS Object; Click to view documentation</value>
</data>
<data name="SubUrlTips" xml:space="preserve">
<value>For group please leave blank here</value>
@@ -937,7 +931,7 @@
<value>User-Agent</value>
</data>
<data name="TbSettingsDefUserAgentTips" xml:space="preserve">
<value>This parameter is valid only for tcp/http, ws, gRPC and xhttp</value>
<value>This parameter is valid only for raw/http, ws, gRPC and xhttp</value>
</data>
<data name="TbSettingsCurrentFontFamily" xml:space="preserve">
<value>Font family (requires restart)</value>
@@ -1102,7 +1096,7 @@
<value>Test terminating...</value>
</data>
<data name="TransportRequestHostTip5" xml:space="preserve">
<value>*grpc Authority</value>
<value>gRPC Authority</value>
</data>
<data name="menuAddHttpServer" xml:space="preserve">
<value>Add [HTTP]</value>
@@ -1329,11 +1323,11 @@
<data name="FillCorrectSendThroughIPv4" xml:space="preserve">
<value>Please fill in the correct IPv4 address for SendThrough.</value>
</data>
<data name="TransportHeaderTypeTip5" xml:space="preserve">
<value>*xhttp mode</value>
<data name="TransportHeaderType5" xml:space="preserve">
<value>xhttp mode</value>
</data>
<data name="TransportExtraTip" xml:space="preserve">
<value>XHTTP Extra raw JSON, format: { XHTTP Object }</value>
<value>Raw JSON, format: { XHTTP Object }</value>
</data>
<data name="TbSettingsHide2TrayWhenClose" xml:space="preserve">
<value>Hide to tray when closing the window</value>
@@ -1596,9 +1590,6 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if
<data name="TbEchConfigList" xml:space="preserve">
<value>EchConfigList</value>
</data>
<data name="TbEchForceQuery" xml:space="preserve">
<value>EchForceQuery</value>
</data>
<data name="TbFullCertTips" xml:space="preserve">
<value>Full certificate (chain), PEM format</value>
</data>
@@ -1707,4 +1698,25 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if
<data name="TbLegacyProtect" xml:space="preserve">
<value>Legacy TUN Protect</value>
</data>
</root>
<data name="TbCamouflageDomain" xml:space="preserve">
<value>Camouflage domain</value>
</data>
<data name="TbHost" xml:space="preserve">
<value>Host</value>
</data>
<data name="TransportExtra" xml:space="preserve">
<value>XHTTP Extra</value>
</data>
<data name="TbAllowInsecureCertFetch" xml:space="preserve">
<value>Allow insecure cert fetch (self-signed)</value>
</data>
<data name="TbAllowInsecureCertFetchTips" xml:space="preserve">
<value>Only for fetching self-signed certificates. This may expose you to MITM risks.</value>
</data>
<data name="menuUdpTestServer" xml:space="preserve">
<value>Test Configurations UDP Delay</value>
</data>
<data name="TbSettingsUdpTestUrl" xml:space="preserve">
<value>UDP Test Url</value>
</data>
</root>
+47 -29
View File
@@ -343,7 +343,7 @@
<value>*QUIC-ключ / KCP-seed</value>
</data>
<data name="TransportPathTip4" xml:space="preserve">
<value>Имя сервиса *gRPC</value>
<value>Имя сервиса gRPC</value>
</data>
<data name="TransportRequestHostTip1" xml:space="preserve">
<value>*http-хосты, разделённые запятыми (,)</value>
@@ -357,17 +357,17 @@
<data name="TransportRequestHostTip4" xml:space="preserve">
<value>Безопасность *QUIC</value>
</data>
<data name="TransportHeaderTypeTip1" xml:space="preserve">
<value>Тип *TCP-камуфляжа</value>
<data name="TransportHeaderType1" xml:space="preserve">
<value>Тип raw-камуфляжа</value>
</data>
<data name="TransportHeaderTypeTip2" xml:space="preserve">
<value>Тип *KCP-камуфляжа</value>
<data name="TransportHeaderType2" xml:space="preserve">
<value>Тип KCP-камуфляжа</value>
</data>
<data name="TransportHeaderTypeTip3" xml:space="preserve">
<value>Тип *QUIC-камуфляжа</value>
<data name="TransportHeaderType3" xml:space="preserve">
<value>Тип QUIC-камуфляжа</value>
</data>
<data name="TransportHeaderTypeTip4" xml:space="preserve">
<value>Режим *gRPC</value>
<data name="TransportHeaderType4" xml:space="preserve">
<value>Режим gRPC</value>
</data>
<data name="LvTLS" xml:space="preserve">
<value>TLS</value>
@@ -606,9 +606,6 @@
<data name="TbRemarks" xml:space="preserve">
<value>Псевдоним (remarks)</value>
</data>
<data name="TbRequestHost" xml:space="preserve">
<value>Камуфляжный домен (host)</value>
</data>
<data name="TbSecurity" xml:space="preserve">
<value>Метод шифрования (security)</value>
</data>
@@ -619,7 +616,7 @@
<value>TLS</value>
</data>
<data name="TipNetwork" xml:space="preserve">
<value>*По умолчанию TCP</value>
<value>*По-умолчанию raw</value>
</data>
<data name="TbCoreType" xml:space="preserve">
<value>Ядро</value>
@@ -676,7 +673,7 @@
<value>Ядро: базовые настройки</value>
</data>
<data name="TbCustomDnsRay" xml:space="preserve">
<value>Пользовательский DNS для V2ray</value>
<value>Пользовательский DNS для v2ray</value>
</data>
<data name="TbSettingsCoreKcp" xml:space="preserve">
<value>Ядро: настройки KCP</value>
@@ -723,9 +720,6 @@
<data name="TbSettingsPass" xml:space="preserve">
<value>Пароль авторизации</value>
</data>
<data name="TbSettingsRemoteDNS" xml:space="preserve">
<value>Пользовательский DNS (если несколько, то делите запятыми (,))</value>
</data>
<data name="TbSettingsSetUWP" xml:space="preserve">
<value>Разрешить loopback для приложений UWP (Win10)</value>
</data>
@@ -937,7 +931,7 @@
<value>User-Agent</value>
</data>
<data name="TbSettingsDefUserAgentTips" xml:space="preserve">
<value>This parameter is valid only for tcp/http, ws, gRPC and xhttp</value>
<value>Параметр действует только для raw/http, ws, gRPC и xhttp</value>
</data>
<data name="TbSettingsCurrentFontFamily" xml:space="preserve">
<value>Шрифт (требуется перезапуск)</value>
@@ -1102,7 +1096,7 @@
<value>Завершение тестирования...</value>
</data>
<data name="TransportRequestHostTip5" xml:space="preserve">
<value>* gRPC Authority (HTTP/2 псевдозаголовок :authority)</value>
<value>gRPC Authority (HTTP/2 псевдозаголовок :authority)</value>
</data>
<data name="menuAddHttpServer" xml:space="preserve">
<value>Добавить сервер [HTTP]</value>
@@ -1320,11 +1314,11 @@
<data name="TbSettingsLinuxSudoPasswordTip" xml:space="preserve">
<value>Пароль sudo будет проверен в терминале. Если из-за ошибки проверки приложение начнёт работать некорректно, перезапустите его. Пароль не сохраняется — его нужно вводить после каждого перезапуска.</value>
</data>
<data name="TransportHeaderTypeTip5" xml:space="preserve">
<value>*XHTTP-режим</value>
<data name="TransportHeaderType5" xml:space="preserve">
<value>XHTTP-режим</value>
</data>
<data name="TransportExtraTip" xml:space="preserve">
<value>Дополнительный сырой JSON для XHTTP, формат: { XHTTP Object }</value>
<value>Сырой JSON, формат: { XHTTP Object }</value>
</data>
<data name="TbSettingsHide2TrayWhenClose" xml:space="preserve">
<value>Сворачивать в трей при закрытии окна</value>
@@ -1342,7 +1336,7 @@
<value>Включить второй смешанный порт</value>
</data>
<data name="TbRoutingInboundTagTips" xml:space="preserve">
<value>socks: локальный порт, socks2: второй локальный порт, socks3: LAN порт</value>
<value>socks: локальный порт, socks2: второй локальный порт, socks3: LAN-порт</value>
</data>
<data name="TbSettingsTheme" xml:space="preserve">
<value>Тема</value>
@@ -1384,7 +1378,7 @@
<value>Mldsa65Verify</value>
</data>
<data name="menuAddAnytlsServer" xml:space="preserve">
<value>Добавить сервер [Anytls]</value>
<value>Добавить сервер [AnyTLS]</value>
</data>
<data name="TbRemoteDNS" xml:space="preserve">
<value>Удалённый DNS</value>
@@ -1587,9 +1581,6 @@
<data name="TbEchConfigList" xml:space="preserve">
<value>EchConfigList</value>
</data>
<data name="TbEchForceQuery" xml:space="preserve">
<value>EchForceQuery</value>
</data>
<data name="TbFullCertTips" xml:space="preserve">
<value>Полный сертификат (цепочка) в формате PEM</value>
</data>
@@ -1699,6 +1690,33 @@
<value>Устаревшая защита TUN (Legacy Protect)</value>
</data>
<data name="TbSettingsSendThroughTip" xml:space="preserve">
<value>For multi-interface environments, enter the local machine's IPv4 address</value>
<value>Для среды с несколькими сетевыми интерфейсами укажите IPv4-адрес локального компьютера</value>
</data>
</root>
<data name="TbCamouflageDomain" xml:space="preserve">
<value>Камуфляжный домен</value>
</data>
<data name="TbHost" xml:space="preserve">
<value>Хост</value>
</data>
<data name="TransportExtra" xml:space="preserve">
<value>Дополнительные параметры XHTTP (Extra)</value>
</data>
<data name="TbAllowInsecureCertFetch" xml:space="preserve">
<value>Разрешить небезопасную загрузку сертификата (самоподписанного)</value>
</data>
<data name="TbAllowInsecureCertFetchTips" xml:space="preserve">
<value>Только для загрузки самоподписанных сертификатов. Это может подвергнуть вас риску атаки «человек посередине» (MITM).</value>
</data>
<data name="menuUdpTestServer" xml:space="preserve">
<value>Тест UDP-задержки конфигураций</value>
</data>
<data name="TbSettingsUdpTestUrl" xml:space="preserve">
<value>URL для UDP-теста</value>
</data>
<data name="FillCorrectSendThroughIPv4" xml:space="preserve">
<value>Укажите корректный IPv4-адрес для SendThrough.</value>
</data>
<data name="TbSettingsSendThrough" xml:space="preserve">
<value>Локальный исходящий адрес (SendThrough)</value>
</data>
</root>
+39 -27
View File
@@ -121,7 +121,7 @@
<value>导出分享链接至剪贴板成功</value>
</data>
<data name="CheckServerSettings" xml:space="preserve">
<value>请先检查设置</value>
<value>配置项无效,请检查或重新选择</value>
</data>
<data name="ConfigurationFormatIncorrect" xml:space="preserve">
<value>配置格式不正确</value>
@@ -343,7 +343,7 @@
<value>*QUIC 加密密钥</value>
</data>
<data name="TransportPathTip4" xml:space="preserve">
<value>*grpc serviceName</value>
<value>gRPC serviceName</value>
</data>
<data name="TransportRequestHostTip1" xml:space="preserve">
<value>*http host 中间逗号 (,) 分隔</value>
@@ -357,17 +357,17 @@
<data name="TransportRequestHostTip4" xml:space="preserve">
<value>*QUIC 加密方式</value>
</data>
<data name="TransportHeaderTypeTip1" xml:space="preserve">
<value>*tcp 伪装类型</value>
<data name="TransportHeaderType1" xml:space="preserve">
<value>raw 伪装类型</value>
</data>
<data name="TransportHeaderTypeTip2" xml:space="preserve">
<value>*kcp 伪装类型</value>
<data name="TransportHeaderType2" xml:space="preserve">
<value>kcp 伪装类型</value>
</data>
<data name="TransportHeaderTypeTip3" xml:space="preserve">
<value>*QUIC 伪装类型</value>
<data name="TransportHeaderType3" xml:space="preserve">
<value>QUIC 伪装类型</value>
</data>
<data name="TransportHeaderTypeTip4" xml:space="preserve">
<value>*grpc 模式</value>
<data name="TransportHeaderType4" xml:space="preserve">
<value>gRPC 模式</value>
</data>
<data name="LvTLS" xml:space="preserve">
<value>TLS</value>
@@ -606,9 +606,6 @@
<data name="TbRemarks" xml:space="preserve">
<value>别名 (remarks)</value>
</data>
<data name="TbRequestHost" xml:space="preserve">
<value>伪装域名 (host)</value>
</data>
<data name="TbSecurity" xml:space="preserve">
<value>加密方式 (security)</value>
</data>
@@ -619,7 +616,7 @@
<value>传输层安全 (TLS)</value>
</data>
<data name="TipNetwork" xml:space="preserve">
<value>*默认 tcp,选错会无法连接</value>
<value>*默认 raw,选错会无法连接</value>
</data>
<data name="TbCoreType" xml:space="preserve">
<value>Core 类型</value>
@@ -723,9 +720,6 @@
<data name="TbSettingsPass" xml:space="preserve">
<value>认证密码</value>
</data>
<data name="TbSettingsRemoteDNS" xml:space="preserve">
<value>自定义 DNS (可多个,用逗号 (,) 分隔)</value>
</data>
<data name="TbSettingsSetUWP" xml:space="preserve">
<value>解除 Win10 UWP 应用回环代理限制</value>
</data>
@@ -865,7 +859,7 @@
<value>规则详细说明文档</value>
</data>
<data name="TbDnsObjectDoc" xml:space="preserve">
<value>支持填写 DnsObjectJSON 格式,点击查看文档</value>
<value>填写 DnsObjectJSON 格式,点击查看文档</value>
</data>
<data name="SubUrlTips" xml:space="preserve">
<value>普通分组此处请留空</value>
@@ -937,7 +931,7 @@
<value>用户代理 (User-Agent)</value>
</data>
<data name="TbSettingsDefUserAgentTips" xml:space="preserve">
<value>仅对 tcp/http、ws、gRPC、xhttp 生效</value>
<value>仅对 raw/http、ws、gRPC、xhttp 生效</value>
</data>
<data name="TbSettingsCurrentFontFamily" xml:space="preserve">
<value>当前字体 (需重启)</value>
@@ -1099,7 +1093,7 @@
<value>测试终止中...</value>
</data>
<data name="TransportRequestHostTip5" xml:space="preserve">
<value>*grpc Authority</value>
<value>gRPC Authority</value>
</data>
<data name="menuAddHttpServer" xml:space="preserve">
<value>添加 [HTTP]</value>
@@ -1326,11 +1320,11 @@
<data name="FillCorrectSendThroughIPv4" xml:space="preserve">
<value>请填写正确的 SendThrough IPv4 地址。</value>
</data>
<data name="TransportHeaderTypeTip5" xml:space="preserve">
<value>*XHTTP 模式</value>
<data name="TransportHeaderType5" xml:space="preserve">
<value>XHTTP 模式</value>
</data>
<data name="TransportExtraTip" xml:space="preserve">
<value>XHTTP Extra 原始 JSON,格式: { XHTTPObject }</value>
<value>原始 JSON,格式: { XHTTPObject }</value>
</data>
<data name="TbSettingsHide2TrayWhenClose" xml:space="preserve">
<value>关闭窗口时隐藏至托盘</value>
@@ -1593,9 +1587,6 @@
<data name="TbEchConfigList" xml:space="preserve">
<value>EchConfigList</value>
</data>
<data name="TbEchForceQuery" xml:space="preserve">
<value>EchForceQuery</value>
</data>
<data name="TbFullCertTips" xml:space="preserve">
<value>完整证书(链),PEM 格式</value>
</data>
@@ -1704,4 +1695,25 @@
<data name="TbLegacyProtect" xml:space="preserve">
<value>旧版 TUN 保护</value>
</data>
</root>
<data name="TbCamouflageDomain" xml:space="preserve">
<value>伪装域名</value>
</data>
<data name="TbHost" xml:space="preserve">
<value>Host</value>
</data>
<data name="TransportExtra" xml:space="preserve">
<value>XHTTP Extra</value>
</data>
<data name="TbAllowInsecureCertFetch" xml:space="preserve">
<value>允许不安全获取证书(自签名)</value>
</data>
<data name="TbAllowInsecureCertFetchTips" xml:space="preserve">
<value>仅用于抓取自签证书,存在中间人风险。</value>
</data>
<data name="menuUdpTestServer" xml:space="preserve">
<value>测试 UDP 延迟 (多选)</value>
</data>
<data name="TbSettingsUdpTestUrl" xml:space="preserve">
<value>UDP 测试地址</value>
</data>
</root>
+38 -26
View File
@@ -121,7 +121,7 @@
<value>匯出分享連結至剪貼簿成功</value>
</data>
<data name="CheckServerSettings" xml:space="preserve">
<value>請先檢查設定</value>
<value>配置項目無效,請檢查或重新選擇</value>
</data>
<data name="ConfigurationFormatIncorrect" xml:space="preserve">
<value>設定格式不正確</value>
@@ -343,7 +343,7 @@
<value>*QUIC 加密金鑰</value>
</data>
<data name="TransportPathTip4" xml:space="preserve">
<value>*grpc serviceName</value>
<value>gRPC serviceName</value>
</data>
<data name="TransportRequestHostTip1" xml:space="preserve">
<value>*http host 中間逗號 (,) 分隔</value>
@@ -357,17 +357,17 @@
<data name="TransportRequestHostTip4" xml:space="preserve">
<value>*QUIC 加密方式</value>
</data>
<data name="TransportHeaderTypeTip1" xml:space="preserve">
<value>*TCP 偽裝類型</value>
<data name="TransportHeaderType1" xml:space="preserve">
<value>raw 偽裝類型</value>
</data>
<data name="TransportHeaderTypeTip2" xml:space="preserve">
<value>*KCP 偽裝類型</value>
<data name="TransportHeaderType2" xml:space="preserve">
<value>KCP 偽裝類型</value>
</data>
<data name="TransportHeaderTypeTip3" xml:space="preserve">
<value>*QUIC 偽裝類型</value>
<data name="TransportHeaderType3" xml:space="preserve">
<value>QUIC 偽裝類型</value>
</data>
<data name="TransportHeaderTypeTip4" xml:space="preserve">
<value>*GRPC 模式</value>
<data name="TransportHeaderType4" xml:space="preserve">
<value>gRPC 模式</value>
</data>
<data name="LvTLS" xml:space="preserve">
<value>TLS</value>
@@ -606,9 +606,6 @@
<data name="TbRemarks" xml:space="preserve">
<value>別名 (remarks)</value>
</data>
<data name="TbRequestHost" xml:space="preserve">
<value>偽裝域名 (host)</value>
</data>
<data name="TbSecurity" xml:space="preserve">
<value>加密方式 (security)</value>
</data>
@@ -619,7 +616,7 @@
<value>傳輸層安全性 (TLS)</value>
</data>
<data name="TipNetwork" xml:space="preserve">
<value>*預設 TCP,選錯會無法連線</value>
<value>*預設 raw,選錯會無法連線</value>
</data>
<data name="TbCoreType" xml:space="preserve">
<value>Core 類型</value>
@@ -723,9 +720,6 @@
<data name="TbSettingsPass" xml:space="preserve">
<value>認證密碼</value>
</data>
<data name="TbSettingsRemoteDNS" xml:space="preserve">
<value>自訂 DNS (可多個,用逗號 (,) 分隔)</value>
</data>
<data name="TbSettingsSetUWP" xml:space="preserve">
<value>解除 Win10 UWP 應用回環代理限制</value>
</data>
@@ -865,7 +859,7 @@
<value>規則詳細說明檔案</value>
</data>
<data name="TbDnsObjectDoc" xml:space="preserve">
<value>支援填寫 DnsObjectJSON 格式,點擊查看說明</value>
<value>填寫 DnsObjectJSON 格式,點擊查看說明</value>
</data>
<data name="SubUrlTips" xml:space="preserve">
<value>普通分組此處請留空</value>
@@ -937,7 +931,7 @@
<value>使用者代理 (User-Agent)</value>
</data>
<data name="TbSettingsDefUserAgentTips" xml:space="preserve">
<value>僅對 TCP/HTTP、WS、gRPC、XHTTP 生效</value>
<value>僅對 raw/HTTP、WS、gRPC、XHTTP 生效</value>
</data>
<data name="TbSettingsCurrentFontFamily" xml:space="preserve">
<value>目前字型 (需重啟)</value>
@@ -1099,7 +1093,7 @@
<value>測試終止中...</value>
</data>
<data name="TransportRequestHostTip5" xml:space="preserve">
<value>*grpc Authority</value>
<value>gRPC Authority</value>
</data>
<data name="menuAddHttpServer" xml:space="preserve">
<value>新增 [HTTP] 節點</value>
@@ -1317,11 +1311,11 @@
<data name="TbSettingsLinuxSudoPasswordTip" xml:space="preserve">
<value>密碼將調用命令行校驗,如果因為校驗錯誤導致無法正常運行時,請重啟本應用。密碼不會存儲,每次重啟後都需要再次輸入。</value>
</data>
<data name="TransportHeaderTypeTip5" xml:space="preserve">
<value>*xhttp 模式</value>
<data name="TransportHeaderType5" xml:space="preserve">
<value>xhttp 模式</value>
</data>
<data name="TransportExtraTip" xml:space="preserve">
<value>XHTTP Extra 原始 JSON,格式: { XHTTPObject }</value>
<value>原始 JSON,格式: { XHTTPObject }</value>
</data>
<data name="TbSettingsHide2TrayWhenClose" xml:space="preserve">
<value>關閉視窗時隱藏至托盤</value>
@@ -1584,9 +1578,6 @@
<data name="TbEchConfigList" xml:space="preserve">
<value>EchConfigList</value>
</data>
<data name="TbEchForceQuery" xml:space="preserve">
<value>EchForceQuery</value>
</data>
<data name="TbFullCertTips" xml:space="preserve">
<value>完整憑證(鏈),PEM 格式</value>
</data>
@@ -1698,4 +1689,25 @@
<data name="TbSettingsSendThroughTip" xml:space="preserve">
<value>For multi-interface environments, enter the local machine's IPv4 address</value>
</data>
<data name="TbCamouflageDomain" xml:space="preserve">
<value>偽裝域名</value>
</data>
<data name="TbHost" xml:space="preserve">
<value>Host</value>
</data>
<data name="TransportExtra" xml:space="preserve">
<value>XHTTP Extra</value>
</data>
<data name="TbAllowInsecureCertFetch" xml:space="preserve">
<value>允許不安全獲取證書(自簽名)</value>
</data>
<data name="TbAllowInsecureCertFetchTips" xml:space="preserve">
<value>僅用於抓取自簽證書,存在中間人風險。</value>
</data>
<data name="menuUdpTestServer" xml:space="preserve">
<value>Test Configurations UDP Delay</value>
</data>
<data name="TbSettingsUdpTestUrl" xml:space="preserve">
<value>UDP Test Url</value>
</data>
</root>
+24
View File
@@ -0,0 +1,24 @@
{
"tag": "tun",
"protocol": "tun",
"settings": {
"name": "xray_tun",
"MTU": 9000,
"gateway": [
"172.18.0.1/30",
"fdfe:dcba:9876::1/126"
],
"autoSystemRoutingTable": [
"0.0.0.0/0",
"::/0"
],
"autoOutboundsInterface": "auto"
},
"sniffing": {
"enabled": true,
"destOverride": [
"http",
"tls"
]
}
}
+14
View File
@@ -0,0 +1,14 @@
[
{
"network": "udp",
"port": "135,137-139,5353",
"outboundTag": "block"
},
{
"ip": [
"224.0.0.0/3",
"ff00::/8"
],
"outboundTag": "block"
}
]
+6
View File
@@ -38,6 +38,8 @@
<EmbeddedResource Include="Sample\SampleHttpResponse" />
<EmbeddedResource Include="Sample\SampleInbound" />
<EmbeddedResource Include="Sample\SampleOutbound" />
<EmbeddedResource Include="Sample\SampleTunInbound" />
<EmbeddedResource Include="Sample\SampleTunRules" />
<EmbeddedResource Include="Sample\SingboxSampleClientConfig" />
<EmbeddedResource Include="Sample\SingboxSampleOutbound" />
<EmbeddedResource Include="Sample\tun_singbox_dns" />
@@ -82,4 +84,8 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ServiceLib.UdpTest\ServiceLib.UdpTest.csproj" />
</ItemGroup>
</Project>
@@ -63,59 +63,6 @@ public partial class CoreConfigSingboxService(CoreConfigContext context)
ret.Success = true;
ret.Data = ApplyFullConfigTemplate();
if (!context.AppConfig.TunModeItem.EnableLegacyProtect
&& context.TunProtectSocksPort is > 0 and <= 65535)
{
// Replace relay proxy outbound, avoid mux or other feature cause issue, and add a socks inbound for tun protect
var relayProxyIndex = _coreConfig.outbounds.FindIndex(o => o.tag == Global.ProxyTag);
_coreConfig.outbounds[relayProxyIndex] = new Outbound4Sbox()
{
type = Global.ProtocolTypes[EConfigType.SOCKS],
tag = Global.ProxyTag,
server = Global.Loopback,
server_port = context.ProxyRelaySocksPort,
};
var ssInbound = new
{
type = "socks",
tag = "tun-protect-socks",
listen = Global.Loopback,
listen_port = context.TunProtectSocksPort,
};
var directRule = new Rule4Sbox()
{
inbound = new List<string> { ssInbound.tag },
outbound = Global.DirectTag,
};
var singboxConfigNode = JsonUtils.ParseJson(ret.Data.ToString())!.AsObject();
var inboundsNode = singboxConfigNode["inbounds"]!.AsArray();
inboundsNode.Add(JsonUtils.SerializeToNode(ssInbound, new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
}));
var routeNode = singboxConfigNode["route"]?.AsObject();
var rulesNode = routeNode?["rules"]?.AsArray();
var protectRuleNode = JsonUtils.SerializeToNode(directRule,
new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull });
if (rulesNode != null)
{
rulesNode.Insert(0, protectRuleNode);
}
else
{
var newRulesNode = new JsonArray() { protectRuleNode };
if (routeNode is null)
{
var newRouteNode = new JsonObject() { ["rules"] = newRulesNode };
singboxConfigNode["route"] = newRouteNode;
}
else
{
routeNode["rules"] = newRulesNode;
}
}
ret.Data = JsonUtils.Serialize(singboxConfigNode);
}
return ret;
}
catch (Exception ex)
@@ -429,15 +429,7 @@ public partial class CoreConfigSingboxService
return;
}
_coreConfig.dns = dns4Sbox;
if (dns4Sbox.servers?.Count > 0 &&
dns4Sbox.servers.First().address.IsNullOrEmpty())
{
GenDnsProtectCustom();
}
else
{
GenDnsProtectCustomLegacy();
}
GenDnsProtectCustom();
}
catch (Exception ex)
{
@@ -479,23 +471,6 @@ public partial class CoreConfigSingboxService
_coreConfig.dns = dns4Sbox;
}
private void GenDnsProtectCustomLegacy()
{
GenDnsProtectCustom();
_coreConfig.dns?.servers?.RemoveAll(s => s.tag == Global.SingboxLocalDNSTag);
var dnsItem = context.RawDnsItem;
var localDnsServer = new Server4Sbox()
{
address = string.IsNullOrEmpty(dnsItem?.DomainDNSAddress)
? Global.DomainPureIPDNSAddress.FirstOrDefault()
: dnsItem?.DomainDNSAddress,
tag = Global.SingboxLocalDNSTag,
detour = Global.DirectTag,
};
_coreConfig.dns?.servers?.Add(localDnsServer);
}
private Rule4Sbox? BuildProtectDomainRule()
{
if (context.ProtectDomainList.Count == 0)
@@ -84,6 +84,8 @@ public partial class CoreConfigSingboxService
try
{
var protocolExtra = _node.GetProtocolExtra();
var transportExtra = _node.GetTransportExtra();
var network = _node.GetNetwork();
outbound.server = _node.Address;
outbound.server_port = _node.Port;
outbound.type = Global.ProtocolTypes[_node.ConfigType];
@@ -114,27 +116,23 @@ public partial class CoreConfigSingboxService
outbound.password = _node.Password;
outbound.udp_over_tcp = protocolExtra.Uot == true ? true : null;
if (_node.Network == nameof(ETransport.tcp) && _node.HeaderType == Global.TcpHeaderHttp)
if (network == nameof(ETransport.raw) && transportExtra.RawHeaderType == Global.RawHeaderHttp)
{
outbound.plugin = "obfs-local";
outbound.plugin_opts = $"obfs=http;obfs-host={_node.RequestHost};";
outbound.plugin_opts = $"obfs=http;obfs-host={transportExtra.Host};";
}
else
{
var pluginArgs = string.Empty;
if (_node.Network == nameof(ETransport.ws))
if (network == nameof(ETransport.ws))
{
pluginArgs += "mode=websocket;";
pluginArgs += $"host={_node.RequestHost};";
pluginArgs += $"host={transportExtra.Host};";
// https://github.com/shadowsocks/v2ray-plugin/blob/e9af1cdd2549d528deb20a4ab8d61c5fbe51f306/args.go#L172
// Equal signs and commas [and backslashes] must be escaped with a backslash.
var path = _node.Path.Replace("\\", "\\\\").Replace("=", "\\=").Replace(",", "\\,");
var path = (transportExtra.Path ?? string.Empty).Replace("\\", "\\\\").Replace("=", "\\=").Replace(",", "\\,");
pluginArgs += $"path={path};";
}
else if (_node.Network == nameof(ETransport.quic))
{
pluginArgs += "mode=quic;";
}
if (_node.StreamSecurity == Global.StreamSecurity)
{
pluginArgs += "tls;";
@@ -381,9 +379,18 @@ public partial class CoreConfigSingboxService
{
serverName = _node.Sni;
}
else if (_node.RequestHost.IsNotEmpty())
else
{
serverName = Utils.String2List(_node.RequestHost)?.First();
var host = _node.GetNetwork() switch
{
nameof(ETransport.raw) => _node.GetTransportExtra().Host,
nameof(ETransport.ws) => _node.GetTransportExtra().Host,
nameof(ETransport.httpupgrade) => _node.GetTransportExtra().Host,
nameof(ETransport.xhttp) => _node.GetTransportExtra().Host,
nameof(ETransport.grpc) => _node.GetTransportExtra().GrpcAuthority,
_ => null,
};
serverName = Utils.String2List(host)?.First();
}
var tls = new Tls4Sbox()
{
@@ -438,23 +445,20 @@ public partial class CoreConfigSingboxService
try
{
var transport = new Transport4Sbox();
var transportExtra = _node.GetTransportExtra();
var useragent = _config.CoreBasicItem.DefUserAgent ?? string.Empty;
var useragentValue = Global.TcpHttpUserAgentTexts.GetValueOrDefault(useragent, useragent);
var useragentValue = Global.RawHttpUserAgentTexts.GetValueOrDefault(useragent, useragent);
switch (_node.GetNetwork())
{
case nameof(ETransport.h2):
transport.type = nameof(ETransport.http);
transport.host = _node.RequestHost.IsNullOrEmpty() ? null : Utils.String2List(_node.RequestHost);
transport.path = _node.Path.NullIfEmpty();
break;
case nameof(ETransport.tcp): //http
if (_node.HeaderType == Global.TcpHeaderHttp)
case nameof(ETransport.raw): //http
if (transportExtra.RawHeaderType == Global.RawHeaderHttp)
{
transport.type = nameof(ETransport.http);
transport.host = _node.RequestHost.IsNullOrEmpty() ? null : Utils.String2List(_node.RequestHost);
transport.path = _node.Path.NullIfEmpty();
transport.host = transportExtra.Host.IsNullOrEmpty()
? null
: Utils.String2List(transportExtra.Host);
transport.path = transportExtra.Path.NullIfEmpty();
if (!useragentValue.IsNullOrEmpty())
{
transport.headers ??= new();
@@ -465,7 +469,7 @@ public partial class CoreConfigSingboxService
case nameof(ETransport.ws):
transport.type = nameof(ETransport.ws);
var wsPath = _node.Path;
var wsPath = transportExtra.Path;
// Parse eh and ed parameters from path using regex
if (!wsPath.IsNullOrEmpty())
@@ -494,11 +498,11 @@ public partial class CoreConfigSingboxService
}
transport.path = wsPath.NullIfEmpty();
if (_node.RequestHost.IsNotEmpty())
if (transportExtra.Host.IsNotEmpty())
{
transport.headers = new()
{
Host = _node.RequestHost
Host = transportExtra.Host
};
}
if (!useragentValue.IsNullOrEmpty())
@@ -510,8 +514,8 @@ public partial class CoreConfigSingboxService
case nameof(ETransport.httpupgrade):
transport.type = nameof(ETransport.httpupgrade);
transport.path = _node.Path.NullIfEmpty();
transport.host = _node.RequestHost.NullIfEmpty();
transport.path = transportExtra.Path.NullIfEmpty();
transport.host = transportExtra.Host.NullIfEmpty();
if (!useragentValue.IsNullOrEmpty())
{
transport.headers ??= new();
@@ -520,13 +524,9 @@ public partial class CoreConfigSingboxService
break;
case nameof(ETransport.quic):
transport.type = nameof(ETransport.quic);
break;
case nameof(ETransport.grpc):
transport.type = nameof(ETransport.grpc);
transport.service_name = _node.Path;
transport.service_name = transportExtra.GrpcServiceName;
transport.idle_timeout = _config.GrpcItem.IdleTimeout?.ToString("##s");
transport.ping_timeout = _config.GrpcItem.HealthCheckTimeout?.ToString("##s");
transport.permit_without_stream = _config.GrpcItem.PermitWithoutStream;
@@ -24,7 +24,7 @@ public partial class CoreConfigSingboxService
strategy = directDnsStrategy
};
if (_config.TunModeItem.EnableTun)
if (context.IsTunEnabled)
{
_coreConfig.route.auto_detect_interface = true;
@@ -15,13 +15,6 @@ public partial class CoreConfigV2rayService(CoreConfigContext context)
var ret = new RetResult();
try
{
if (!context.AppConfig.TunModeItem.EnableLegacyProtect
&& context.IsTunEnabled
&& context.TunProtectSocksPort is > 0 and <= 65535
&& context.ProxyRelaySocksPort is > 0 and <= 65535)
{
return GenerateClientProxyRelayConfig();
}
if (_node == null
|| !_node.IsValid())
{
@@ -62,6 +55,11 @@ public partial class CoreConfigV2rayService(CoreConfigContext context)
GenDns();
GenStatistic();
if (_config.CoreBasicItem.EnableFragment)
{
ApplyOutboundFragment();
}
ApplyOutboundSendThrough();
var finalRule = BuildFinalRule();
@@ -163,6 +161,11 @@ public partial class CoreConfigV2rayService(CoreConfigContext context)
listen = Global.Loopback,
port = port,
protocol = EInboundProtocol.mixed.ToString(),
settings = new Inboundsettings4Ray()
{
udp = true,
auth = "noauth"
},
};
inbound.tag = inbound.protocol + inbound.port.ToString();
_coreConfig.inbounds.Add(inbound);
@@ -196,6 +199,10 @@ public partial class CoreConfigV2rayService(CoreConfigContext context)
_coreConfig.routing.rules.Add(rule);
}
if (_config.CoreBasicItem.EnableFragment)
{
ApplyOutboundFragment();
}
ApplyOutboundSendThrough();
//ret.Msg =string.Format(ResUI.SuccessfulConfiguration"), node.getSummary());
ret.Success = true;
@@ -254,9 +261,19 @@ public partial class CoreConfigV2rayService(CoreConfigContext context)
listen = Global.Loopback,
port = port,
protocol = EInboundProtocol.mixed.ToString(),
settings = new Inboundsettings4Ray()
{
udp = true,
auth = "noauth"
},
});
_coreConfig.routing.rules.Add(BuildFinalRule());
if (_config.CoreBasicItem.EnableFragment)
{
ApplyOutboundFragment();
}
ApplyOutboundSendThrough();
ret.Msg = string.Format(ResUI.SuccessfulConfiguration, "");
@@ -272,139 +289,5 @@ public partial class CoreConfigV2rayService(CoreConfigContext context)
}
}
public RetResult GenerateClientProxyRelayConfig()
{
var ret = new RetResult();
try
{
if (_node == null
|| !_node.IsValid())
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
}
if (_node.GetNetwork() is nameof(ETransport.quic))
{
ret.Msg = ResUI.Incorrectconfiguration + $" - {_node.GetNetwork()}";
return ret;
}
var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
if (result.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
return ret;
}
_coreConfig = JsonUtils.Deserialize<V2rayConfig>(result);
if (_coreConfig == null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
}
GenLog();
_coreConfig.outbounds.Clear();
GenOutbounds();
GenStatistic();
var protectNode = new ProfileItem()
{
CoreType = ECoreType.Xray,
ConfigType = EConfigType.SOCKS,
Address = Global.Loopback,
Port = context.TunProtectSocksPort,
};
protectNode.SetProtocolExtra(protectNode.GetProtocolExtra() with
{
SsMethod = Global.None,
});
const string protectTag = "tun-protect-socks";
foreach (var outbound in _coreConfig.outbounds
.Where(o => o.streamSettings?.sockopt?.dialerProxy?.IsNullOrEmpty() ?? true))
{
outbound.streamSettings ??= new();
outbound.streamSettings.sockopt ??= new();
outbound.streamSettings.sockopt.dialerProxy = protectTag;
}
// ech protected
foreach (var outbound in _coreConfig.outbounds
.Where(outbound => outbound.streamSettings?.tlsSettings?.echConfigList?.IsNullOrEmpty() == false))
{
outbound.streamSettings!.tlsSettings!.echSockopt ??= new();
outbound.streamSettings.tlsSettings.echSockopt.dialerProxy = protectTag;
}
// xhttp download protected
foreach (var outbound in _coreConfig.outbounds
.Where(o => o.streamSettings?.xhttpSettings?.extra is not null))
{
var xhttpExtra = JsonUtils.ParseJson(JsonUtils.Serialize(outbound.streamSettings.xhttpSettings!.extra));
if (xhttpExtra is not JsonObject xhttpExtraObject
|| xhttpExtraObject["downloadSettings"] is not JsonObject downloadSettings)
{
continue;
}
// dialerProxy
var sockopt = downloadSettings["sockopt"] as JsonObject ?? new JsonObject();
sockopt["dialerProxy"] = protectTag;
downloadSettings["sockopt"] = sockopt;
// ech protected
if (downloadSettings["tlsSettings"] is JsonObject tlsSettings
&& tlsSettings["echConfigList"] is not null)
{
tlsSettings["echSockopt"] = new JsonObject
{
["dialerProxy"] = protectTag
};
}
outbound.streamSettings.xhttpSettings.extra = xhttpExtraObject;
}
_coreConfig.outbounds.Add(new CoreConfigV2rayService(context with
{
Node = protectNode,
}).BuildProxyOutbound(protectTag));
_coreConfig.routing.rules ??= [];
var hasBalancer = _coreConfig.routing.balancers is { Count: > 0 };
_coreConfig.routing.rules.Add(new()
{
inboundTag = ["proxy-relay-socks"],
outboundTag = hasBalancer ? null : Global.ProxyTag,
balancerTag = hasBalancer ? Global.ProxyTag + Global.BalancerTagSuffix : null,
type = "field"
});
//_coreConfig.inbounds.Clear();
ApplyOutboundSendThrough();
var configNode = JsonUtils.ParseJson(JsonUtils.Serialize(_coreConfig))!;
configNode["inbounds"]!.AsArray().Add(new
{
listen = Global.Loopback,
port = context.ProxyRelaySocksPort,
protocol = "socks",
settings = new
{
auth = "noauth",
udp = true,
},
tag = "proxy-relay-socks",
});
ret.Msg = string.Format(ResUI.SuccessfulConfiguration, "");
ret.Success = true;
ret.Data = JsonUtils.Serialize(configNode);
return ret;
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
}
}
#endregion public gen function
}
@@ -5,12 +5,18 @@ public partial class CoreConfigV2rayService
private string ApplyFullConfigTemplate()
{
var fullConfigTemplate = context.FullConfigTemplate;
if (fullConfigTemplate == null || !fullConfigTemplate.Enabled || fullConfigTemplate.Config.IsNullOrEmpty())
if (fullConfigTemplate is not { Enabled: true })
{
return JsonUtils.Serialize(_coreConfig);
}
var fullConfigTemplateNode = JsonNode.Parse(fullConfigTemplate.Config);
var fullConfigTemplateItem = context.IsTunEnabled ? fullConfigTemplate.TunConfig : fullConfigTemplate.Config;
if (fullConfigTemplateItem.IsNullOrEmpty())
{
return JsonUtils.Serialize(_coreConfig);
}
var fullConfigTemplateNode = JsonNode.Parse(fullConfigTemplateItem);
if (fullConfigTemplateNode == null)
{
return JsonUtils.Serialize(_coreConfig);
@@ -370,11 +370,11 @@ public partial class CoreConfigV2rayService
try
{
var item = context.RawDnsItem;
var normalDNS = item?.NormalDNS;
var customDNS = context.IsTunEnabled ? item?.TunDNS : item?.NormalDNS;
var domainStrategy4Freedom = item?.DomainStrategy4Freedom;
if (normalDNS.IsNullOrEmpty())
if (customDNS.IsNullOrEmpty())
{
normalDNS = EmbedUtils.GetEmbedText(Global.DNSV2rayNormalFileName);
customDNS = EmbedUtils.GetEmbedText(Global.DNSV2rayNormalFileName);
}
//Outbound Freedom domainStrategy
@@ -389,11 +389,11 @@ public partial class CoreConfigV2rayService
}
}
var obj = JsonUtils.ParseJson(normalDNS);
var obj = JsonUtils.ParseJson(customDNS);
if (obj is null)
{
List<string> servers = [];
var arrDNS = normalDNS.Split(',');
var arrDNS = customDNS.Split(',');
foreach (var str in arrDNS)
{
servers.Add(str);
@@ -7,36 +7,61 @@ public partial class CoreConfigV2rayService
try
{
var listen = "0.0.0.0";
var listenPort = AppManager.Instance.GetLocalPort(EInboundProtocol.socks);
_coreConfig.inbounds = [];
var inbound = BuildInbound(_config.Inbound.First(), EInboundProtocol.socks, true);
_coreConfig.inbounds.Add(inbound);
if (_config.Inbound.First().SecondLocalPortEnabled)
if (!context.IsTunEnabled
|| (context.IsTunEnabled && _node.Address != Global.Loopback && _node.Port != listenPort))
{
var inbound2 = BuildInbound(_config.Inbound.First(), EInboundProtocol.socks2, true);
_coreConfig.inbounds.Add(inbound2);
}
_coreConfig.inbounds.Add(inbound);
if (_config.Inbound.First().AllowLANConn)
{
if (_config.Inbound.First().NewPort4LAN)
if (_config.Inbound.First().SecondLocalPortEnabled)
{
var inbound3 = BuildInbound(_config.Inbound.First(), EInboundProtocol.socks3, true);
inbound3.listen = listen;
_coreConfig.inbounds.Add(inbound3);
var inbound2 = BuildInbound(_config.Inbound.First(), EInboundProtocol.socks2, true);
_coreConfig.inbounds.Add(inbound2);
}
//auth
if (_config.Inbound.First().User.IsNotEmpty() && _config.Inbound.First().Pass.IsNotEmpty())
if (_config.Inbound.First().AllowLANConn)
{
if (_config.Inbound.First().NewPort4LAN)
{
inbound3.settings.auth = "password";
inbound3.settings.accounts = new List<AccountsItem4Ray> { new() { user = _config.Inbound.First().User, pass = _config.Inbound.First().Pass } };
var inbound3 = BuildInbound(_config.Inbound.First(), EInboundProtocol.socks3, true);
inbound3.listen = listen;
_coreConfig.inbounds.Add(inbound3);
//auth
if (_config.Inbound.First().User.IsNotEmpty() && _config.Inbound.First().Pass.IsNotEmpty())
{
inbound3.settings.auth = "password";
inbound3.settings.accounts = new List<AccountsItem4Ray>
{
new() { user = _config.Inbound.First().User, pass = _config.Inbound.First().Pass }
};
}
}
else
{
inbound.listen = listen;
}
}
else
}
if (context.IsTunEnabled)
{
if (_config.TunModeItem.Mtu <= 0)
{
inbound.listen = listen;
_config.TunModeItem.Mtu = Global.TunMtus.First();
}
var tunInbound = JsonUtils.Deserialize<Inbounds4Ray>(EmbedUtils.GetEmbedText(Global.V2raySampleTunInbound)) ?? new Inbounds4Ray { };
tunInbound.settings.name = Utils.IsMacOS() ? $"utun{new Random().Next(99)}" : "xray_tun";
tunInbound.settings.MTU = _config.TunModeItem.Mtu;
if (_config.TunModeItem.EnableIPv6Address == false)
{
tunInbound.settings.gateway = ["172.18.0.1/30"];
}
tunInbound.sniffing = inbound.sniffing;
_coreConfig.inbounds.Add(tunInbound);
}
}
catch (Exception ex)
@@ -12,6 +12,10 @@ public partial class CoreConfigV2rayService
GenObservatory(multipleLoad);
GenBalancer(multipleLoad);
}
if (context.IsTunEnabled)
{
_coreConfig.outbounds.Add(BuildDnsOutbound());
}
}
private List<Outbounds4Ray> BuildAllProxyOutbounds(string baseTagName = Global.ProxyTag)
@@ -25,35 +29,6 @@ public partial class CoreConfigV2rayService
{
proxyOutboundList.Add(BuildProxyOutbound(baseTagName));
}
if (_config.CoreBasicItem.EnableFragment)
{
var fragmentOutbound = new Outbounds4Ray
{
protocol = "freedom",
tag = $"frag-{baseTagName}",
settings = new()
{
fragment = new()
{
packets = _config.Fragment4RayItem?.Packets,
length = _config.Fragment4RayItem?.Length,
interval = _config.Fragment4RayItem?.Interval
}
}
};
var actOutboundWithTlsList =
proxyOutboundList.Where(n => n.streamSettings?.security.IsNullOrEmpty() == false
&& (n.streamSettings?.sockopt?.dialerProxy?.IsNullOrEmpty() ?? true)).ToList();
if (actOutboundWithTlsList.Count > 0)
{
proxyOutboundList.Add(fragmentOutbound);
}
foreach (var outbound in actOutboundWithTlsList)
{
FillDialerProxy(outbound, fragmentOutbound.tag);
}
}
return proxyOutboundList;
}
@@ -349,8 +324,51 @@ public partial class CoreConfigV2rayService
network = "hysteria";
}
streamSettings.network = network;
var host = _node.RequestHost.TrimEx();
var path = _node.Path.TrimEx();
var transport = _node.GetTransportExtra();
var host = string.Empty;
var path = string.Empty;
var kcpSeed = string.Empty;
var kcpMtu = 0;
var headerType = string.Empty;
var xhttpExtra = string.Empty;
switch (network)
{
case nameof(ETransport.raw):
host = transport.Host?.TrimEx() ?? string.Empty;
path = transport.Path?.TrimEx() ?? string.Empty;
headerType = transport.RawHeaderType?.TrimEx() ?? string.Empty;
break;
case nameof(ETransport.kcp):
kcpSeed = transport.KcpSeed?.TrimEx() ?? string.Empty;
headerType = transport.KcpHeaderType?.TrimEx() ?? string.Empty;
kcpMtu = transport.KcpMtu > 0 ? transport.KcpMtu!.Value : _config.KcpItem.Mtu;
break;
case nameof(ETransport.ws):
host = transport.Host?.TrimEx() ?? string.Empty;
path = transport.Path?.TrimEx() ?? string.Empty;
break;
case nameof(ETransport.httpupgrade):
host = transport.Host?.TrimEx() ?? string.Empty;
path = transport.Path?.TrimEx() ?? string.Empty;
break;
case nameof(ETransport.xhttp):
host = transport.Host?.TrimEx() ?? string.Empty;
path = transport.Path?.TrimEx() ?? string.Empty;
headerType = transport.XhttpMode?.TrimEx() ?? string.Empty;
xhttpExtra = transport.XhttpExtra?.TrimEx() ?? string.Empty;
break;
case nameof(ETransport.grpc):
host = transport.GrpcAuthority?.TrimEx() ?? string.Empty;
path = transport.GrpcServiceName?.TrimEx() ?? string.Empty;
headerType = transport.GrpcMode?.TrimEx() ?? string.Empty;
break;
}
var sni = _node.Sni.TrimEx();
var useragent = _config.CoreBasicItem.DefUserAgent ?? string.Empty;
@@ -365,7 +383,6 @@ public partial class CoreConfigV2rayService
alpn = _node.GetAlpn(),
fingerprint = _node.Fingerprint.IsNullOrEmpty() ? _config.CoreBasicItem.DefFingerprint : _node.Fingerprint,
echConfigList = _node.EchConfigList.NullIfEmpty(),
echForceQuery = _node.EchForceQuery.NullIfEmpty()
};
if (sni.IsNotEmpty())
{
@@ -375,6 +392,11 @@ public partial class CoreConfigV2rayService
{
tlsSettings.serverName = Utils.String2List(host)?.First();
}
if (!tlsSettings.echConfigList.IsNullOrEmpty())
{
// For legacy xray compatibility, remove this in the future
tlsSettings.echForceQuery = "full";
}
var certs = CertPemManager.ParsePemChain(_node.Cert);
if (certs.Count > 0)
{
@@ -425,30 +447,29 @@ public partial class CoreConfigV2rayService
case nameof(ETransport.kcp):
KcpSettings4Ray kcpSettings = new()
{
mtu = _config.KcpItem.Mtu,
mtu = kcpMtu,
tti = _config.KcpItem.Tti
};
kcpSettings.uplinkCapacity = _config.KcpItem.UplinkCapacity;
kcpSettings.downlinkCapacity = _config.KcpItem.DownlinkCapacity;
kcpSettings.congestion = _config.KcpItem.Congestion;
kcpSettings.readBufferSize = _config.KcpItem.ReadBufferSize;
kcpSettings.writeBufferSize = _config.KcpItem.WriteBufferSize;
kcpSettings.cwndMultiplier = _config.KcpItem.CwndMultiplier;
kcpSettings.maxSendingWindow = _config.KcpItem.MaxSendingWindow;
var kcpFinalmask = new Finalmask4Ray();
if (Global.KcpHeaderMaskMap.TryGetValue(_node.HeaderType, out var header))
if (Global.KcpHeaderMaskMap.TryGetValue(headerType, out var header))
{
kcpFinalmask.udp =
[
new Mask4Ray
{
type = header,
settings = _node.HeaderType == "dns" && !host.IsNullOrEmpty() ? new MaskSettings4Ray { domain = host } : null
settings = null
}
];
}
kcpFinalmask.udp ??= [];
if (path.IsNullOrEmpty())
if (kcpSeed.IsNullOrEmpty())
{
kcpFinalmask.udp.Add(new Mask4Ray
{
@@ -460,7 +481,7 @@ public partial class CoreConfigV2rayService
kcpFinalmask.udp.Add(new Mask4Ray
{
type = "mkcp-aes128gcm",
settings = new MaskSettings4Ray { password = path }
settings = new MaskSettings4Ray { password = kcpSeed }
});
}
streamSettings.kcpSettings = kcpSettings;
@@ -518,63 +539,26 @@ public partial class CoreConfigV2rayService
{
xhttpSettings.host = host;
}
if (_node.HeaderType.IsNotEmpty() && Global.XhttpMode.Contains(_node.HeaderType))
if (headerType.IsNotEmpty() && Global.XhttpMode.Contains(headerType))
{
xhttpSettings.mode = _node.HeaderType;
xhttpSettings.mode = headerType;
}
if (_node.Extra.IsNotEmpty())
if (xhttpExtra.IsNotEmpty())
{
xhttpSettings.extra = JsonUtils.ParseJson(_node.Extra);
xhttpSettings.extra = JsonUtils.ParseJson(xhttpExtra);
}
streamSettings.xhttpSettings = xhttpSettings;
FillOutboundMux(outbound);
break;
//h2
case nameof(ETransport.h2):
HttpSettings4Ray httpSettings = new();
if (host.IsNotEmpty())
{
httpSettings.host = Utils.String2List(host);
}
httpSettings.path = path;
streamSettings.httpSettings = httpSettings;
break;
//quic
case nameof(ETransport.quic):
QuicSettings4Ray quicsettings = new()
{
security = host,
key = path,
header = new Header4Ray
{
type = _node.HeaderType
}
};
streamSettings.quicSettings = quicsettings;
if (_node.StreamSecurity == Global.StreamSecurity)
{
if (sni.IsNotEmpty())
{
streamSettings.tlsSettings.serverName = sni;
}
else
{
streamSettings.tlsSettings.serverName = _node.Address;
}
}
break;
case nameof(ETransport.grpc):
GrpcSettings4Ray grpcSettings = new()
{
authority = host.NullIfEmpty(),
serviceName = path,
multiMode = _node.HeaderType == Global.GrpcMultiMode,
multiMode = headerType == Global.GrpcMultiMode,
idle_timeout = _config.GrpcItem.IdleTimeout,
health_check_timeout = _config.GrpcItem.HealthCheckTimeout,
permit_without_stream = _config.GrpcItem.PermitWithoutStream,
@@ -641,20 +625,20 @@ public partial class CoreConfigV2rayService
break;
default:
//tcp
if (_node.HeaderType == Global.TcpHeaderHttp)
// raw
if (headerType == Global.RawHeaderHttp)
{
TcpSettings4Ray tcpSettings = new()
RawSettings4Ray rawSettings = new()
{
header = new Header4Ray
{
type = _node.HeaderType
type = headerType
}
};
//request Host
var request = EmbedUtils.GetEmbedText(Global.V2raySampleHttpRequestFileName);
var useragentValue = Global.TcpHttpUserAgentTexts.GetValueOrDefault(useragent, useragent);
var useragentValue = Global.RawHttpUserAgentTexts.GetValueOrDefault(useragent, useragent);
var arrHost = host.Split(',');
var host2 = string.Join(",".AppendQuotes(), arrHost);
request = request.Replace("$requestHost$", $"{host2.AppendQuotes()}");
@@ -667,9 +651,9 @@ public partial class CoreConfigV2rayService
pathHttp = string.Join(",".AppendQuotes(), arrPath);
}
request = request.Replace("$requestPath$", $"{pathHttp.AppendQuotes()}");
tcpSettings.header.request = JsonUtils.Deserialize<object>(request);
rawSettings.header.request = JsonUtils.Deserialize<object>(request);
streamSettings.tcpSettings = tcpSettings;
streamSettings.rawSettings = rawSettings;
}
break;
}
@@ -825,4 +809,74 @@ public partial class CoreConfigV2rayService
}
}
}
private static Outbounds4Ray BuildDnsOutbound()
{
var outbound = new Outbounds4Ray { tag = Global.DnsOutboundTag, protocol = "dns", };
return outbound;
}
private void ApplyOutboundFragment()
{
var actOutboundWithTlsList =
_coreConfig.outbounds.Where(n => n.streamSettings?.security.IsNullOrEmpty() == false
&& (n.streamSettings?.sockopt?.dialerProxy?.IsNullOrEmpty() ?? true))
.ToList();
var configPackets = _config.Fragment4RayItem?.Packets ?? "tlshello";
var configLength = _config.Fragment4RayItem?.Length ?? "50-100";
var configDelay = _config.Fragment4RayItem?.Interval ?? "10-20";
var fragmentMask = new Mask4Ray
{
type = "fragment",
settings = new MaskSettings4Ray
{
packets = configPackets,
length = configLength,
delay = configDelay,
}
};
var noiseMask = new Mask4Ray
{
type = "noise",
settings = new MaskSettings4Ray
{
length = "10-20",
delay = "10-16",
}
};
foreach (var outbound in actOutboundWithTlsList)
{
//var packets = configPackets;
//if (outbound.streamSettings.security == Global.StreamSecurityReality
// && packets == "tlshello")
//{
// packets = "1-3";
//}
//else if (outbound.streamSettings.security == Global.StreamSecurity
// && packets != "tlshello")
//{
// packets = "tlshello";
//}
var finalMaskJsonObj = JsonUtils.ParseJson(JsonUtils.Serialize(outbound.streamSettings?.finalmask)) as JsonObject ?? new JsonObject();
// tcp fragment
var tcpFinalmaskList = finalMaskJsonObj["tcp"] as JsonArray ?? [];
if (tcpFinalmaskList.Count == 0)
{
tcpFinalmaskList.Add(JsonUtils.SerializeToNode(fragmentMask));
finalMaskJsonObj["tcp"] = tcpFinalmaskList;
}
// udp noise
var udpFinalmaskList = finalMaskJsonObj["udp"] as JsonArray ?? [];
if (udpFinalmaskList.Count == 0)
{
udpFinalmaskList.Add(JsonUtils.SerializeToNode(noiseMask));
finalMaskJsonObj["udp"] = udpFinalmaskList;
}
// write back
outbound.streamSettings.finalmask = finalMaskJsonObj;
}
}
}
@@ -6,6 +6,31 @@ public partial class CoreConfigV2rayService
{
try
{
if (context.IsTunEnabled)
{
var tunRules = JsonUtils.Deserialize<List<RulesItem4Ray>>(EmbedUtils.GetEmbedText(Global.V2raySampleTunRules));
if (tunRules != null)
{
_coreConfig.routing.rules.AddRange(tunRules);
}
var (lstDnsExe, lstDirectExe) = BuildRoutingDirectExe();
_coreConfig.routing.rules.Add(new()
{
port = "53",
process = lstDnsExe,
outboundTag = Global.DnsOutboundTag,
});
_coreConfig.routing.rules.Add(new()
{
process = lstDirectExe,
outboundTag = Global.DirectTag,
});
_coreConfig.routing.rules.Add(new()
{
port = "53",
outboundTag = Global.DnsOutboundTag,
});
}
if (_coreConfig.routing?.rules != null)
{
_coreConfig.routing.domainStrategy = _config.RoutingBasicItem.DomainStrategy;
@@ -205,4 +230,37 @@ public partial class CoreConfigV2rayService
}
return finalRule;
}
private static (List<string> lstDnsExe, List<string> lstDirectExe) BuildRoutingDirectExe()
{
var dnsExeSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var directExeSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var coreInfoResult = CoreInfoManager.Instance.GetCoreInfo();
foreach (var coreConfig in coreInfoResult)
{
if (coreConfig.CoreType == ECoreType.v2rayN)
{
continue;
}
foreach (var baseExeName in coreConfig.CoreExes)
{
if (coreConfig.CoreType != ECoreType.Xray)
{
dnsExeSet.Add(Utils.GetExeName(baseExeName));
}
directExeSet.Add(Utils.GetExeName(baseExeName));
}
}
directExeSet.Add("xray/");
directExeSet.Add("self/");
var lstDnsExe = new List<string>(dnsExeSet);
var lstDirectExe = new List<string>(directExeSet);
return (lstDnsExe, lstDirectExe);
}
}
@@ -1,3 +1,5 @@
using ServiceLib.UdpTest;
namespace ServiceLib.Services;
public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateFunc)
@@ -49,6 +51,10 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
await RunRealPingBatchAsync(lstSelected, exitLoopKey);
break;
case ESpeedActionType.UdpTest:
await RunUdpTestBatchAsync(lstSelected, exitLoopKey);
break;
case ESpeedActionType.Speedtest:
await RunMixedTestAsync(lstSelected, 1, true, exitLoopKey);
break;
@@ -101,6 +107,7 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
{
case ESpeedActionType.Tcping:
case ESpeedActionType.Realping:
case ESpeedActionType.UdpTest:
await UpdateFunc(it.IndexId, ResUI.Speedtesting, "");
ProfileExManager.Instance.SetTestDelay(it.IndexId, 0);
break;
@@ -238,6 +245,86 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
return true;
}
private async Task RunUdpTestBatchAsync(List<ServerTestItem> lstSelected, string exitLoopKey, int pageSize = 0)
{
if (pageSize <= 0)
{
pageSize = lstSelected.Count < Global.SpeedTestPageSize ? lstSelected.Count : Global.SpeedTestPageSize;
}
var lstTest = GetTestBatchItem(lstSelected, pageSize);
List<ServerTestItem> lstFailed = new();
foreach (var lst in lstTest)
{
var ret = await RunUdpTestAsync(lst, exitLoopKey);
if (ret == false)
{
lstFailed.AddRange(lst);
}
await Task.Delay(100);
}
//Retest the failed part
if (lstFailed.Count > 0)
{
if (ShouldStopTest(exitLoopKey))
{
await UpdateFunc("", ResUI.SpeedtestingSkip);
return;
}
await UpdateFunc("", string.Format(ResUI.SpeedtestingTestFailedPart, lstFailed.Count));
await RunUdpTestAsync(lstFailed, exitLoopKey);
}
}
private async Task<bool> RunUdpTestAsync(List<ServerTestItem> selecteds, string exitLoopKey)
{
ProcessService processService = null;
try
{
processService = await CoreManager.Instance.LoadCoreConfigSpeedtest(selecteds);
if (processService is null)
{
return false;
}
await Task.Delay(1000);
List<Task> tasks = new();
foreach (var it in selecteds)
{
if (!it.AllowTest)
{
continue;
}
if (ShouldStopTest(exitLoopKey))
{
return false;
}
tasks.Add(Task.Run(async () =>
{
await DoUdpTest(it);
}));
}
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
}
finally
{
if (processService != null)
{
await processService?.StopAsync();
}
}
return true;
}
private async Task RunMixedTestAsync(List<ServerTestItem> selecteds, int concurrencyCount, bool blSpeedTest, string exitLoopKey)
{
using var concurrencySemaphore = new SemaphoreSlim(concurrencyCount);
@@ -330,6 +417,24 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
});
}
private async Task<int> DoUdpTest(ServerTestItem it)
{
var udpService = UdpTestService.CreateFromTarget(_config?.SpeedTestItem.UdpTestTarget, out var udpTestUrl);
var responseTime = -1;
try
{
responseTime = (int)(await udpService.SendUdpRequestAsync(udpTestUrl, it.Port, TimeSpan.FromSeconds(5))).TotalMilliseconds;
}
catch
{
// ignored
}
ProfileExManager.Instance.SetTestDelay(it.IndexId, responseTime);
await UpdateFunc(it.IndexId, responseTime.ToString());
return responseTime;
}
private async Task<int> GetTcpingTime(string url, int port)
{
var responseTime = -1;
@@ -299,7 +299,6 @@ public class UpdateService(Config config, Func<bool, string, Task> updateFunc)
return url;
}
else if (Utils.IsLinux())
{
var arch = RuntimeInformation.ProcessArchitecture;
@@ -314,7 +313,6 @@ public class UpdateService(Config config, Func<bool, string, Task> updateFunc)
_ => null,
};
}
else if (Utils.IsMacOS())
{
return RuntimeInformation.ProcessArchitecture switch
@@ -17,6 +17,9 @@ public class AddServerViewModel : MyReactiveObject
[Reactive]
public string CertSha { get; set; }
[Reactive]
public bool AllowInsecureCertFetch { get; set; }
[Reactive]
public string SalamanderPass { get; set; }
@@ -73,6 +76,166 @@ public class AddServerViewModel : MyReactiveObject
[Reactive]
public bool NaiveQuic { get; set; }
[Reactive]
public string RawHeaderType { get; set; }
[Reactive]
public string Host { get; set; }
[Reactive]
public string Path { get; set; }
[Reactive]
public string XhttpMode { get; set; }
[Reactive]
public string XhttpExtra { get; set; }
[Reactive]
public string GrpcAuthority { get; set; }
[Reactive]
public string GrpcServiceName { get; set; }
[Reactive]
public string GrpcMode { get; set; }
[Reactive]
public string KcpHeaderType { get; set; }
[Reactive]
public string KcpSeed { get; set; }
[Reactive]
public int? KcpMtu { get; set; }
public string TransportHeaderType
{
get => SelectedSource.GetNetwork() switch
{
nameof(ETransport.raw) => RawHeaderType,
nameof(ETransport.kcp) => KcpHeaderType,
nameof(ETransport.xhttp) => XhttpMode,
nameof(ETransport.grpc) => GrpcMode,
_ => string.Empty,
};
set
{
switch (SelectedSource.GetNetwork())
{
case nameof(ETransport.raw):
RawHeaderType = value;
break;
case nameof(ETransport.kcp):
KcpHeaderType = value;
break;
case nameof(ETransport.xhttp):
XhttpMode = value;
break;
case nameof(ETransport.grpc):
GrpcMode = value;
break;
}
this.RaisePropertyChanged();
}
}
public string TransportHost
{
get => SelectedSource.GetNetwork() switch
{
nameof(ETransport.raw) => Host,
nameof(ETransport.ws) => Host,
nameof(ETransport.httpupgrade) => Host,
nameof(ETransport.xhttp) => Host,
nameof(ETransport.grpc) => GrpcAuthority,
_ => string.Empty,
};
set
{
switch (SelectedSource.GetNetwork())
{
case nameof(ETransport.raw):
Host = value;
break;
case nameof(ETransport.ws):
Host = value;
break;
case nameof(ETransport.httpupgrade):
Host = value;
break;
case nameof(ETransport.xhttp):
Host = value;
break;
case nameof(ETransport.grpc):
GrpcAuthority = value;
break;
}
this.RaisePropertyChanged();
}
}
public string TransportPath
{
get => SelectedSource.GetNetwork() switch
{
nameof(ETransport.kcp) => KcpSeed,
nameof(ETransport.ws) => Path,
nameof(ETransport.httpupgrade) => Path,
nameof(ETransport.xhttp) => Path,
nameof(ETransport.grpc) => GrpcServiceName,
_ => string.Empty,
};
set
{
switch (SelectedSource.GetNetwork())
{
case nameof(ETransport.kcp):
KcpSeed = value;
break;
case nameof(ETransport.ws):
Path = value;
break;
case nameof(ETransport.httpupgrade):
Path = value;
break;
case nameof(ETransport.xhttp):
Path = value;
break;
case nameof(ETransport.grpc):
GrpcServiceName = value;
break;
}
this.RaisePropertyChanged();
}
}
public string TransportExtraText
{
get => SelectedSource.GetNetwork() == nameof(ETransport.xhttp)
? XhttpExtra
: string.Empty;
set
{
if (SelectedSource.GetNetwork() == nameof(ETransport.xhttp))
{
XhttpExtra = value;
}
this.RaisePropertyChanged();
}
}
public ReactiveCommand<Unit, Unit> FetchCertCmd { get; }
public ReactiveCommand<Unit, Unit> FetchCertChainCmd { get; }
public ReactiveCommand<Unit, Unit> SaveCmd { get; }
@@ -101,14 +264,21 @@ public class AddServerViewModel : MyReactiveObject
this.WhenAnyValue(x => x.CertSha)
.Subscribe(_ => UpdateCertTip());
this.WhenAnyValue(x => x.SelectedSource.Network)
.Subscribe(_ =>
{
this.RaisePropertyChanged(nameof(TransportHeaderType));
this.RaisePropertyChanged(nameof(TransportHost));
this.RaisePropertyChanged(nameof(TransportPath));
this.RaisePropertyChanged(nameof(TransportExtraText));
});
this.WhenAnyValue(x => x.Cert)
.Subscribe(_ => UpdateCertSha());
if (profileItem.IndexId.IsNullOrEmpty())
{
profileItem.Network = Global.DefaultNetwork;
profileItem.HeaderType = Global.None;
profileItem.RequestHost = "";
profileItem.StreamSecurity = "";
SelectedSource = profileItem;
}
@@ -120,25 +290,38 @@ public class AddServerViewModel : MyReactiveObject
Cert = SelectedSource?.Cert?.ToString() ?? string.Empty;
CertSha = SelectedSource?.CertSha?.ToString() ?? string.Empty;
var protocolExtra = SelectedSource?.GetProtocolExtra();
Ports = protocolExtra?.Ports ?? string.Empty;
AlterId = int.TryParse(protocolExtra?.AlterId, out var result) ? result : 0;
Flow = protocolExtra?.Flow ?? string.Empty;
SalamanderPass = protocolExtra?.SalamanderPass ?? string.Empty;
UpMbps = protocolExtra?.UpMbps;
DownMbps = protocolExtra?.DownMbps;
HopInterval = protocolExtra?.HopInterval.IsNullOrEmpty() ?? true ? Global.Hysteria2DefaultHopInt.ToString() : protocolExtra.HopInterval;
VmessSecurity = protocolExtra?.VmessSecurity?.IsNullOrEmpty() == false ? protocolExtra.VmessSecurity : Global.DefaultSecurity;
VlessEncryption = protocolExtra?.VlessEncryption.IsNullOrEmpty() == false ? protocolExtra.VlessEncryption : Global.None;
SsMethod = protocolExtra?.SsMethod ?? string.Empty;
WgPublicKey = protocolExtra?.WgPublicKey ?? string.Empty;
WgInterfaceAddress = protocolExtra?.WgInterfaceAddress ?? string.Empty;
WgReserved = protocolExtra?.WgReserved ?? string.Empty;
WgMtu = protocolExtra?.WgMtu ?? 1280;
Uot = protocolExtra?.Uot ?? false;
CongestionControl = protocolExtra?.CongestionControl ?? string.Empty;
InsecureConcurrency = protocolExtra?.InsecureConcurrency > 0 ? protocolExtra.InsecureConcurrency : null;
NaiveQuic = protocolExtra?.NaiveQuic ?? false;
var protocolExtra = SelectedSource?.GetProtocolExtra() ?? new();
var transport = SelectedSource?.GetTransportExtra() ?? new();
Ports = protocolExtra.Ports ?? string.Empty;
AlterId = int.TryParse(protocolExtra.AlterId, out var result) ? result : 0;
Flow = protocolExtra.Flow ?? string.Empty;
SalamanderPass = protocolExtra.SalamanderPass ?? string.Empty;
UpMbps = protocolExtra.UpMbps;
DownMbps = protocolExtra.DownMbps;
HopInterval = protocolExtra.HopInterval ?? string.Empty;
VmessSecurity = protocolExtra.VmessSecurity?.IsNullOrEmpty() == false ? protocolExtra.VmessSecurity : Global.DefaultSecurity;
VlessEncryption = protocolExtra.VlessEncryption?.IsNullOrEmpty() == false ? protocolExtra.VlessEncryption : Global.None;
SsMethod = protocolExtra.SsMethod ?? string.Empty;
WgPublicKey = protocolExtra.WgPublicKey ?? string.Empty;
WgInterfaceAddress = protocolExtra.WgInterfaceAddress ?? string.Empty;
WgReserved = protocolExtra.WgReserved ?? string.Empty;
WgMtu = protocolExtra.WgMtu ?? 1280;
Uot = protocolExtra.Uot ?? false;
CongestionControl = protocolExtra.CongestionControl ?? string.Empty;
InsecureConcurrency = protocolExtra.InsecureConcurrency > 0 ? protocolExtra.InsecureConcurrency : null;
NaiveQuic = protocolExtra.NaiveQuic ?? false;
RawHeaderType = transport.RawHeaderType ?? Global.None;
Host = transport.Host ?? string.Empty;
Path = transport.Path ?? string.Empty;
XhttpMode = transport.XhttpMode ?? Global.DefaultXhttpMode;
XhttpExtra = transport.XhttpExtra ?? string.Empty;
GrpcAuthority = transport.GrpcAuthority ?? string.Empty;
GrpcServiceName = transport.GrpcServiceName ?? string.Empty;
GrpcMode = transport.GrpcMode.IsNullOrEmpty() ? Global.GrpcGunMode : transport.GrpcMode;
KcpHeaderType = transport.KcpHeaderType.IsNullOrEmpty() ? Global.None : transport.KcpHeaderType;
KcpSeed = transport.KcpSeed ?? string.Empty;
KcpMtu = transport.KcpMtu;
}
private async Task SaveServerAsync()
@@ -185,6 +368,26 @@ public class AddServerViewModel : MyReactiveObject
SelectedSource.CoreType = CoreType.IsNullOrEmpty() ? null : (ECoreType)Enum.Parse(typeof(ECoreType), CoreType);
SelectedSource.Cert = Cert.IsNullOrEmpty() ? string.Empty : Cert;
SelectedSource.CertSha = CertSha.IsNullOrEmpty() ? string.Empty : CertSha;
if (!Global.Networks.Contains(SelectedSource.Network))
{
SelectedSource.Network = Global.DefaultNetwork;
}
var transport = new TransportExtraItem
{
RawHeaderType = RawHeaderType.NullIfEmpty(),
Host = Host.NullIfEmpty(),
Path = Path.NullIfEmpty(),
XhttpMode = XhttpMode.NullIfEmpty(),
XhttpExtra = XhttpExtra.NullIfEmpty(),
GrpcAuthority = GrpcAuthority.NullIfEmpty(),
GrpcServiceName = GrpcServiceName.NullIfEmpty(),
GrpcMode = GrpcMode.NullIfEmpty(),
KcpHeaderType = KcpHeaderType.NullIfEmpty(),
KcpSeed = KcpSeed.NullIfEmpty(),
KcpMtu = KcpMtu > 0 ? KcpMtu : null,
};
SelectedSource.SetProtocolExtra(SelectedSource.GetProtocolExtra() with
{
Ports = Ports.NullIfEmpty(),
@@ -206,6 +409,7 @@ public class AddServerViewModel : MyReactiveObject
InsecureConcurrency = InsecureConcurrency > 0 ? InsecureConcurrency : null,
NaiveQuic = NaiveQuic ? true : null,
});
SelectedSource.SetTransportExtra(transport);
if (await ConfigHandler.AddServer(_config, SelectedSource) == 0)
{
@@ -261,7 +465,7 @@ public class AddServerViewModel : MyReactiveObject
var serverName = SelectedSource.Sni;
if (serverName.IsNullOrEmpty())
{
serverName = SelectedSource.RequestHost;
serverName = GetCurrentTransportHost();
}
if (serverName.IsNullOrEmpty())
{
@@ -272,7 +476,7 @@ public class AddServerViewModel : MyReactiveObject
domain += $":{SelectedSource.Port}";
}
(Cert, var certError) = await CertPemManager.Instance.GetCertPemAsync(domain, serverName);
(Cert, var certError) = await CertPemManager.Instance.GetCertPemAsync(domain, serverName, allowInsecure: AllowInsecureCertFetch);
UpdateCertTip(certError);
}
@@ -286,7 +490,7 @@ public class AddServerViewModel : MyReactiveObject
var serverName = SelectedSource.Sni;
if (serverName.IsNullOrEmpty())
{
serverName = SelectedSource.RequestHost;
serverName = GetCurrentTransportHost();
}
if (serverName.IsNullOrEmpty())
{
@@ -297,8 +501,21 @@ public class AddServerViewModel : MyReactiveObject
domain += $":{SelectedSource.Port}";
}
var (certs, certError) = await CertPemManager.Instance.GetCertChainPemAsync(domain, serverName);
var (certs, certError) = await CertPemManager.Instance.GetCertChainPemAsync(domain, serverName, allowInsecure: AllowInsecureCertFetch);
Cert = CertPemManager.ConcatenatePemChain(certs);
UpdateCertTip(certError);
}
private string GetCurrentTransportHost()
{
return SelectedSource.GetNetwork() switch
{
nameof(ETransport.raw) => Host,
nameof(ETransport.ws) => Host,
nameof(ETransport.httpupgrade) => Host,
nameof(ETransport.xhttp) => Host,
nameof(ETransport.grpc) => GrpcAuthority,
_ => string.Empty,
};
}
}
@@ -20,6 +20,7 @@ public class DNSSettingViewModel : MyReactiveObject
[Reactive] public string DomainStrategy4FreedomCompatible { get; set; }
[Reactive] public string DomainDNSAddressCompatible { get; set; }
[Reactive] public string NormalDNSCompatible { get; set; }
[Reactive] public string TunDNSCompatible { get; set; }
[Reactive] public string DomainStrategy4Freedom2Compatible { get; set; }
[Reactive] public string DomainDNSAddress2Compatible { get; set; }
@@ -43,6 +44,7 @@ public class DNSSettingViewModel : MyReactiveObject
ImportDefConfig4V2rayCompatibleCmd = ReactiveCommand.CreateFromTask(async () =>
{
NormalDNSCompatible = EmbedUtils.GetEmbedText(Global.DNSV2rayNormalFileName);
TunDNSCompatible = EmbedUtils.GetEmbedText(Global.DNSV2rayNormalFileName);
await Task.CompletedTask;
});
@@ -84,6 +86,7 @@ public class DNSSettingViewModel : MyReactiveObject
DomainStrategy4FreedomCompatible = item1?.DomainStrategy4Freedom ?? string.Empty;
DomainDNSAddressCompatible = item1?.DomainDNSAddress ?? string.Empty;
NormalDNSCompatible = item1?.NormalDNS ?? string.Empty;
TunDNSCompatible = item1?.TunDNS ?? string.Empty;
var item2 = await AppManager.Instance.GetDNSItem(ECoreType.sing_box);
SBCustomDNSEnableCompatible = item2.Enabled;
@@ -124,10 +127,27 @@ public class DNSSettingViewModel : MyReactiveObject
}
}
}
if (TunDNSCompatible.IsNotEmpty())
{
var obj = JsonUtils.ParseJson(TunDNSCompatible);
if (obj != null && obj["servers"] != null)
{
}
else
{
if (TunDNSCompatible.Contains('{') || TunDNSCompatible.Contains('}'))
{
NoticeManager.Instance.Enqueue(ResUI.FillCorrectDNSText);
return;
}
}
}
if (NormalDNS2Compatible.IsNotEmpty())
{
var obj2 = JsonUtils.Deserialize<Dns4Sbox>(NormalDNS2Compatible);
if (obj2 == null)
if (obj2 == null
|| obj2.servers.Count == 0
|| obj2.servers.Any(s => s.type.IsNullOrEmpty()))
{
NoticeManager.Instance.Enqueue(ResUI.FillCorrectDNSText);
return;
@@ -136,7 +156,9 @@ public class DNSSettingViewModel : MyReactiveObject
if (TunDNS2Compatible.IsNotEmpty())
{
var obj2 = JsonUtils.Deserialize<Dns4Sbox>(TunDNS2Compatible);
if (obj2 == null)
if (obj2 == null
|| obj2.servers.Count == 0
|| obj2.servers.Any(s => s.type.IsNullOrEmpty()))
{
NoticeManager.Instance.Enqueue(ResUI.FillCorrectDNSText);
return;
@@ -149,14 +171,15 @@ public class DNSSettingViewModel : MyReactiveObject
item1.DomainDNSAddress = DomainDNSAddressCompatible;
item1.UseSystemHosts = UseSystemHostsCompatible;
item1.NormalDNS = NormalDNSCompatible;
item1.TunDNS = TunDNSCompatible;
await ConfigHandler.SaveDNSItems(_config, item1);
var item2 = await AppManager.Instance.GetDNSItem(ECoreType.sing_box);
item2.Enabled = SBCustomDNSEnableCompatible;
item2.DomainStrategy4Freedom = DomainStrategy4Freedom2Compatible;
item2.DomainDNSAddress = DomainDNSAddress2Compatible;
item2.NormalDNS = JsonUtils.Serialize(JsonUtils.ParseJson(NormalDNS2Compatible));
item2.TunDNS = JsonUtils.Serialize(JsonUtils.ParseJson(TunDNS2Compatible));
item2.NormalDNS = JsonUtils.Serialize(JsonUtils.Deserialize<Dns4Sbox>(NormalDNS2Compatible));
item2.TunDNS = JsonUtils.Serialize(JsonUtils.Deserialize<Dns4Sbox>(TunDNS2Compatible));
await ConfigHandler.SaveDNSItems(_config, item2);
await ConfigHandler.SaveConfig(_config);
@@ -13,6 +13,9 @@ public class FullConfigTemplateViewModel : MyReactiveObject
[Reactive]
public string FullConfigTemplate4Ray { get; set; }
[Reactive]
public string FullTunConfigTemplate4Ray { get; set; }
[Reactive]
public string FullConfigTemplate4Singbox { get; set; }
@@ -50,10 +53,15 @@ public class FullConfigTemplateViewModel : MyReactiveObject
private async Task Init()
{
var item = await AppManager.Instance.GetFullConfigTemplateItem(ECoreType.Xray);
EnableFullConfigTemplate4Ray = item?.Enabled ?? false;
FullConfigTemplate4Ray = item?.Config ?? string.Empty;
AddProxyOnly4Ray = item?.AddProxyOnly ?? false;
ProxyDetour4Ray = item?.ProxyDetour ?? string.Empty;
if (item == null)
{
return;
}
EnableFullConfigTemplate4Ray = item.Enabled;
FullConfigTemplate4Ray = item.Config ?? string.Empty;
FullTunConfigTemplate4Ray = item.TunConfig ?? string.Empty;
AddProxyOnly4Ray = item.AddProxyOnly ?? false;
ProxyDetour4Ray = item.ProxyDetour ?? string.Empty;
var item2 = await AppManager.Instance.GetFullConfigTemplateItem(ECoreType.sing_box);
EnableFullConfigTemplate4Singbox = item2?.Enabled ?? false;
@@ -82,10 +90,13 @@ public class FullConfigTemplateViewModel : MyReactiveObject
private async Task<bool> SaveXrayConfigAsync()
{
var item = await AppManager.Instance.GetFullConfigTemplateItem(ECoreType.Xray);
if (item == null)
{
return false;
}
item.Enabled = EnableFullConfigTemplate4Ray;
item.Config = null;
item.Config = FullConfigTemplate4Ray;
item.TunConfig = FullTunConfigTemplate4Ray;
item.AddProxyOnly = AddProxyOnly4Ray;
item.ProxyDetour = ProxyDetour4Ray;
@@ -97,10 +108,11 @@ public class FullConfigTemplateViewModel : MyReactiveObject
private async Task<bool> SaveSingboxConfigAsync()
{
var item = await AppManager.Instance.GetFullConfigTemplateItem(ECoreType.sing_box);
if (item == null)
{
return false;
}
item.Enabled = EnableFullConfigTemplate4Singbox;
item.Config = null;
item.TunConfig = null;
item.Config = FullConfigTemplate4Singbox;
item.TunConfig = FullTunConfigTemplate4Singbox;
@@ -559,7 +559,7 @@ public class MainWindowViewModel : MyReactiveObject
await Task.Run(async () =>
{
await LoadCore(allResult.ResolvedMainContext, allResult.PreSocksResult?.Context);
await LoadCore(allResult.MainResult.Context, allResult.PreSocksResult?.Context);
await SysProxyHandler.UpdateSysProxy(_config, false);
await Task.Delay(1000);
});
@@ -59,6 +59,7 @@ public class OptionSettingViewModel : MyReactiveObject
[Reactive] public int SpeedTestTimeout { get; set; }
[Reactive] public string SpeedTestUrl { get; set; }
[Reactive] public string SpeedPingTestUrl { get; set; }
[Reactive] public string UdpTestTarget { get; set; }
[Reactive] public int MixedConcurrencyCount { get; set; }
[Reactive] public bool EnableHWA { get; set; }
[Reactive] public string SubConvertUrl { get; set; }
@@ -195,6 +196,7 @@ public class OptionSettingViewModel : MyReactiveObject
SpeedTestUrl = _config.SpeedTestItem.SpeedTestUrl;
MixedConcurrencyCount = _config.SpeedTestItem.MixedConcurrencyCount;
SpeedPingTestUrl = _config.SpeedTestItem.SpeedPingTestUrl;
UdpTestTarget = _config.SpeedTestItem.UdpTestTarget;
EnableHWA = _config.GuiItem.EnableHWA;
SubConvertUrl = _config.ConstItem.SubConvertUrl;
MainGirdOrientation = (int)_config.UiItem.MainGirdOrientation;
@@ -368,6 +370,7 @@ public class OptionSettingViewModel : MyReactiveObject
_config.SpeedTestItem.MixedConcurrencyCount = MixedConcurrencyCount;
_config.SpeedTestItem.SpeedTestUrl = SpeedTestUrl;
_config.SpeedTestItem.SpeedPingTestUrl = SpeedPingTestUrl;
_config.SpeedTestItem.UdpTestTarget = UdpTestTarget;
_config.GuiItem.EnableHWA = EnableHWA;
_config.ConstItem.SubConvertUrl = SubConvertUrl;
_config.UiItem.MainGirdOrientation = (EGirdOrientation)MainGirdOrientation;
@@ -190,7 +190,7 @@ public class ProfilesSelectViewModel : MyReactiveObject
}
SelectedSub = (_config.SubIndexId.IsNotEmpty()
? SubItems.FirstOrDefault(t => t.Id == _config.SubIndexId)
: null) ?? SubItems.LastOrDefault();
: null) ?? SubItems.FirstOrDefault();
}
private async Task<List<ProfileItemModel>?> GetProfileItemsEx(string subid, string filter)
@@ -60,6 +60,7 @@ public class ProfilesViewModel : MyReactiveObject
public ReactiveCommand<Unit, Unit> TcpingServerCmd { get; }
public ReactiveCommand<Unit, Unit> RealPingServerCmd { get; }
public ReactiveCommand<Unit, Unit> UdpTestServerCmd { get; }
public ReactiveCommand<Unit, Unit> SpeedServerCmd { get; }
public ReactiveCommand<Unit, Unit> SortServerResultCmd { get; }
public ReactiveCommand<Unit, Unit> RemoveInvalidServerResultCmd { get; }
@@ -178,6 +179,10 @@ public class ProfilesViewModel : MyReactiveObject
{
await ServerSpeedtest(ESpeedActionType.Realping);
}, canEditRemove);
UdpTestServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await ServerSpeedtest(ESpeedActionType.UdpTest);
}, canEditRemove);
SpeedServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await ServerSpeedtest(ESpeedActionType.Speedtest);
@@ -393,7 +398,7 @@ public class ProfilesViewModel : MyReactiveObject
}
SelectedSub = (_config.SubIndexId.IsNotEmpty()
? SubItems.FirstOrDefault(t => t.Id == _config.SubIndexId)
: null) ?? SubItems.LastOrDefault();
: null) ?? SubItems.FirstOrDefault();
}
private async Task<List<ProfileItemModel>?> GetProfileItemsEx(string subid, string filter)
@@ -22,7 +22,6 @@ public class RoutingSettingViewModel : MyReactiveObject
public ReactiveCommand<Unit, Unit> RoutingAdvancedSetDefaultCmd { get; }
public ReactiveCommand<Unit, Unit> RoutingAdvancedImportRulesCmd { get; }
public ReactiveCommand<Unit, Unit> SaveCmd { get; }
public bool IsModified { get; set; }
#endregion Reactive
@@ -53,12 +52,19 @@ public class RoutingSettingViewModel : MyReactiveObject
await RoutingAdvancedImportRules();
});
SaveCmd = ReactiveCommand.CreateFromTask(async () =>
{
await SaveRoutingAsync();
});
_ = Init();
// Auto-save DomainStrategy when changed
this.WhenAnyValue(
x => x.DomainStrategy,
x => x.DomainStrategy4Singbox)
.Skip(1)
.DistinctUntilChanged()
.Subscribe(x =>
{
IsModified = true;
_ = SaveSettingsAsync();
});
}
private async Task Init()
@@ -96,20 +102,14 @@ public class RoutingSettingViewModel : MyReactiveObject
}
}
private async Task SaveRoutingAsync()
/// <summary>
/// Save DomainStrategy settings
/// </summary>
public async Task SaveSettingsAsync()
{
_config.RoutingBasicItem.DomainStrategy = DomainStrategy;
_config.RoutingBasicItem.DomainStrategy4Singbox = DomainStrategy4Singbox;
if (await ConfigHandler.SaveConfig(_config) == 0)
{
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null);
}
else
{
NoticeManager.Instance.Enqueue(ResUI.OperationFailed);
}
await ConfigHandler.SaveConfig(_config);
}
#endregion Refresh Save
@@ -0,0 +1,8 @@
namespace v2rayN.Desktop.Common;
public enum ButtonResult
{
None = 0,
Yes = 1,
No = 2
}
+4 -3
View File
@@ -1,5 +1,5 @@
using Avalonia.Platform.Storage;
using MsBox.Avalonia;
using v2rayN.Desktop.Views;
namespace v2rayN.Desktop.Common;
@@ -9,8 +9,9 @@ internal class UI
public static async Task<ButtonResult> ShowYesNo(Window owner, string msg)
{
var box = MessageBoxManager.GetMessageBoxStandard(caption, msg, ButtonEnum.YesNo);
return await box.ShowWindowDialogAsync(owner);
var box = new MessageBoxDialog(caption, msg);
var result = await box.ShowDialog<ButtonResult>(owner);
return result == ButtonResult.Yes ? ButtonResult.Yes : ButtonResult.No;
}
public static async Task<string?> OpenFileDialog(Window owner, FilePickerFileType? filter)
-1
View File
@@ -20,7 +20,6 @@ global using Avalonia.Platform;
global using Avalonia.Styling;
global using Avalonia.Threading;
global using DynamicData;
global using MsBox.Avalonia.Enums;
global using ReactiveUI;
global using ReactiveUI.Avalonia;
global using ReactiveUI.Fody.Helpers;
+296 -124
View File
@@ -306,7 +306,7 @@
x:Name="txtSecurity5"
Grid.Row="3"
Grid.Column="1"
Width="200"
Width="400"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left" />
@@ -690,128 +690,294 @@
<Grid
x:Name="gridTransport"
Grid.Row="4"
ColumnDefinitions="300,Auto,Auto"
RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto">
RowDefinitions="Auto,Auto,Auto">
<TextBlock
Grid.Row="0"
Grid.ColumnSpan="2"
Margin="{StaticResource Margin4}"
Text="{x:Static resx:ResUI.GbTransport}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbNetwork}" />
<ComboBox
x:Name="cmbNetwork"
Grid.Row="1"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="1"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TipNetwork}" />
<TextBlock
x:Name="labHeaderType"
Grid.Row="2"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbHeaderType}" />
<StackPanel
Grid.Row="2"
Grid.Column="1"
VerticalAlignment="Center"
Orientation="Horizontal">
<Grid Grid.Row="1" ColumnDefinitions="300,Auto,Auto">
<TextBlock
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbNetwork}" />
<ComboBox
x:Name="cmbHeaderType"
x:Name="cmbNetwork"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TipNetwork}" />
</Grid>
<Button
x:Name="btnExtra"
Margin="{StaticResource MarginLr8}"
Classes="IconButton">
<Button.Content>
<PathIcon Data="{StaticResource SemiIconMore}">
<PathIcon.RenderTransform>
<RotateTransform Angle="90" />
</PathIcon.RenderTransform>
</PathIcon>
</Button.Content>
<Button.Flyout>
<Flyout>
<StackPanel>
<TextBlock
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TransportExtraTip}" />
<views:JsonEditor
x:Name="txtExtra"
Width="400"
MinHeight="100"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Stretch"
VerticalAlignment="Center" />
</StackPanel>
</Flyout>
</Button.Flyout>
</Button>
</StackPanel>
<TextBlock
x:Name="tipHeaderType"
Grid.Row="2"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbHeaderType}" />
<Grid Grid.Row="2">
<Grid
x:Name="gridTransportRaw"
IsVisible="False"
RowDefinitions="Auto,Auto">
<Grid Grid.Row="0" ColumnDefinitions="300,Auto">
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TransportHeaderType1}" />
<ComboBox
x:Name="cmbHeaderTypeRaw"
Grid.Row="0"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}" />
</Grid>
<TextBlock
Grid.Row="3"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbRequestHost}" />
<TextBox
x:Name="txtRequestHost"
Grid.Row="3"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
<TextBlock
x:Name="tipRequestHost"
Grid.Row="3"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbRequestHost}" />
<Grid
x:Name="gridTransportRawHttp"
Grid.Row="1"
ColumnDefinitions="300,Auto"
IsVisible="False"
RowDefinitions="Auto,Auto">
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbCamouflageDomain}" />
<TextBox
x:Name="txtRequestHostRaw"
Grid.Row="0"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbPath}" />
<TextBox
x:Name="txtPathRaw"
Grid.Row="1"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
</Grid>
</Grid>
<TextBlock
Grid.Row="4"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbPath}" />
<TextBox
x:Name="txtPath"
Grid.Row="4"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
<TextBlock
x:Name="tipPath"
Grid.Row="4"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbPath}" />
<Grid
x:Name="gridTransportXhttp"
ColumnDefinitions="300,Auto"
IsVisible="False"
RowDefinitions="Auto,Auto,Auto,Auto">
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TransportHeaderType5}" />
<ComboBox
x:Name="cmbHeaderTypeXhttp"
Grid.Row="0"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbHost}" />
<TextBox
x:Name="txtRequestHostXhttp"
Grid.Row="1"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="2"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbPath}" />
<TextBox
x:Name="txtPathXhttp"
Grid.Row="2"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="3"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Top"
Text="{x:Static resx:ResUI.TransportExtra}"
TextWrapping="Wrap" />
<Expander
Grid.Row="3"
Grid.Column="1"
IsExpanded="True">
<Expander.Header>
<TextBlock FontWeight="Normal" Text="{x:Static resx:ResUI.TransportExtraTip}" />
</Expander.Header>
<views:JsonEditor x:Name="txtExtraXhttp" HorizontalAlignment="Stretch" />
</Expander>
</Grid>
<Grid
x:Name="gridTransportKcp"
ColumnDefinitions="300,Auto"
IsVisible="False"
RowDefinitions="Auto,Auto,Auto">
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TransportHeaderType2}" />
<ComboBox
x:Name="cmbHeaderTypeKcp"
Grid.Row="0"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="MTU" />
<TextBox
x:Name="txtKcpMtu"
Grid.Row="1"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left" />
<TextBlock
Grid.Row="2"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="Seed" />
<TextBox
x:Name="txtKcpSeed"
Grid.Row="2"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left" />
</Grid>
<Grid
x:Name="gridTransportGrpc"
ColumnDefinitions="300,Auto"
IsVisible="False"
RowDefinitions="Auto,Auto,Auto">
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TransportHeaderType4}" />
<ComboBox
x:Name="cmbHeaderTypeGrpc"
Grid.Row="0"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TransportRequestHostTip5}" />
<TextBox
x:Name="txtRequestHostGrpc"
Grid.Row="1"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="2"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TransportPathTip4}" />
<TextBox
x:Name="txtPathGrpc"
Grid.Row="2"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
</Grid>
<Grid
x:Name="gridTransportWs"
ColumnDefinitions="300,Auto"
IsVisible="False"
RowDefinitions="Auto,Auto">
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbHost}" />
<TextBox
x:Name="txtRequestHostWs"
Grid.Row="0"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbPath}" />
<TextBox
x:Name="txtPathWs"
Grid.Row="1"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
</Grid>
<Grid
x:Name="gridTransportHttpupgrade"
ColumnDefinitions="300,Auto"
IsVisible="False"
RowDefinitions="Auto,Auto">
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbHost}" />
<TextBox
x:Name="txtRequestHostHttpupgrade"
Grid.Row="0"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbPath}" />
<TextBox
x:Name="txtPathHttpupgrade"
Grid.Row="1"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}" />
</Grid>
</Grid>
</Grid>
<Grid
@@ -949,19 +1115,6 @@
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left" />
<TextBlock
Grid.Row="6"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbEchForceQuery}" />
<ComboBox
x:Name="cmbEchForceQuery"
Grid.Row="6"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="7"
Grid.Column="0"
@@ -1008,6 +1161,25 @@
Margin="{StaticResource Margin4}"
Content="{x:Static resx:ResUI.TbFetchCertChain}" />
</StackPanel>
<StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
<TextBlock
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbAllowInsecureCertFetch}" />
<ToggleSwitch
x:Name="togAllowInsecureCertFetch"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left" />
</StackPanel>
<TextBlock
x:Name="txtAllowInsecureCertFetchTips"
Width="400"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Foreground="#FFD32F2F"
IsVisible="False"
Text="{x:Static resx:ResUI.TbAllowInsecureCertFetchTips}"
TextWrapping="Wrap" />
<TextBlock
Width="400"
Margin="{StaticResource Margin4}"
@@ -16,6 +16,7 @@ public partial class AddServerWindow : WindowBase<AddServerViewModel>
Loaded += Window_Loaded;
btnCancel.Click += (s, e) => Close();
cmbNetwork.SelectionChanged += CmbNetwork_SelectionChanged;
cmbHeaderTypeRaw.SelectionChanged += CmbHeaderTypeRaw_SelectionChanged;
cmbStreamSecurity.SelectionChanged += CmbStreamSecurity_SelectionChanged;
btnGUID.Click += btnGUID_Click;
btnGUID5.Click += btnGUID_Click;
@@ -24,15 +25,22 @@ public partial class AddServerWindow : WindowBase<AddServerViewModel>
cmbCoreType.ItemsSource = Global.CoreTypes.AppendEmpty();
cmbNetwork.ItemsSource = Global.Networks;
cmbHeaderTypeRaw.ItemsSource = new List<string> { Global.None, Global.RawHeaderHttp };
var kcpHeaderTypes = new List<string> { Global.None };
kcpHeaderTypes.AddRange(Global.KcpHeaderTypes);
cmbHeaderTypeKcp.ItemsSource = kcpHeaderTypes;
cmbHeaderTypeXhttp.ItemsSource = Global.XhttpMode;
cmbHeaderTypeGrpc.ItemsSource = new List<string> { Global.GrpcGunMode, Global.GrpcMultiMode };
cmbFingerprint.ItemsSource = Global.Fingerprints;
cmbFingerprint2.ItemsSource = Global.Fingerprints;
cmbAllowInsecure.ItemsSource = Global.AllowInsecure;
cmbAlpn.ItemsSource = Global.Alpns;
cmbEchForceQuery.ItemsSource = Global.EchForceQuerys;
var lstStreamSecurity = new List<string>();
lstStreamSecurity.Add(string.Empty);
lstStreamSecurity.Add(Global.StreamSecurity);
var lstStreamSecurity = new List<string> { string.Empty, Global.StreamSecurity };
switch (profileItem.ConfigType)
{
@@ -201,10 +209,28 @@ public partial class AddServerWindow : WindowBase<AddServerViewModel>
break;
}
this.Bind(ViewModel, vm => vm.SelectedSource.Network, v => v.cmbNetwork.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.HeaderType, v => v.cmbHeaderType.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.RequestHost, v => v.txtRequestHost.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.Path, v => v.txtPath.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.Extra, v => v.txtExtra.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.RawHeaderType, v => v.cmbHeaderTypeRaw.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostRaw.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Path, v => v.txtPathRaw.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.KcpHeaderType, v => v.cmbHeaderTypeKcp.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.KcpSeed, v => v.txtKcpSeed.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.KcpMtu, v => v.txtKcpMtu.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostWs.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Path, v => v.txtPathWs.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostHttpupgrade.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Path, v => v.txtPathHttpupgrade.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.XhttpMode, v => v.cmbHeaderTypeXhttp.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostXhttp.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Path, v => v.txtPathXhttp.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.XhttpExtra, v => v.txtExtraXhttp.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.GrpcMode, v => v.cmbHeaderTypeGrpc.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.GrpcAuthority, v => v.txtRequestHostGrpc.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.GrpcServiceName, v => v.txtPathGrpc.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.StreamSecurity, v => v.cmbStreamSecurity.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.Sni, v => v.txtSNI.Text).DisposeWith(disposables);
@@ -214,8 +240,9 @@ public partial class AddServerWindow : WindowBase<AddServerViewModel>
this.Bind(ViewModel, vm => vm.CertSha, v => v.txtCertSha256Pinning.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.CertTip, v => v.labCertPinning.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Cert, v => v.txtCert.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.AllowInsecureCertFetch, v => v.togAllowInsecureCertFetch.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.AllowInsecureCertFetch, v => v.txtAllowInsecureCertFetchTips.IsVisible).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.EchConfigList, v => v.txtEchConfigList.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.EchForceQuery, v => v.cmbEchForceQuery.SelectedValue).DisposeWith(disposables);
//reality
this.Bind(ViewModel, vm => vm.SelectedSource.Sni, v => v.txtSNI2.Text).DisposeWith(disposables);
@@ -253,8 +280,12 @@ public partial class AddServerWindow : WindowBase<AddServerViewModel>
private void CmbNetwork_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
SetHeaderType();
SetTips();
SetTransportGridVisibility();
}
private void CmbHeaderTypeRaw_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
SetRawHttpFieldsVisibility();
}
private void CmbStreamSecurity_SelectionChanged(object? sender, SelectionChangedEventArgs e)
@@ -283,102 +314,66 @@ public partial class AddServerWindow : WindowBase<AddServerViewModel>
txtId5.Text = Utils.GetGuid();
}
private void SetHeaderType()
private void SetTransportGridVisibility()
{
var lstHeaderType = new List<string>();
var network = cmbNetwork.SelectedItem.ToString();
if (network.IsNullOrEmpty())
{
lstHeaderType.Add(Global.None);
cmbHeaderType.ItemsSource = lstHeaderType;
cmbHeaderType.SelectedIndex = 0;
return;
}
if (network == nameof(ETransport.tcp))
{
lstHeaderType.Add(Global.None);
lstHeaderType.Add(Global.TcpHeaderHttp);
}
else if (network is nameof(ETransport.kcp) or nameof(ETransport.quic))
{
lstHeaderType.Add(Global.None);
lstHeaderType.AddRange(Global.KcpHeaderTypes);
}
else if (network is nameof(ETransport.xhttp))
{
lstHeaderType.AddRange(Global.XhttpMode);
}
else if (network == nameof(ETransport.grpc))
{
lstHeaderType.Add(Global.GrpcGunMode);
lstHeaderType.Add(Global.GrpcMultiMode);
}
else
{
lstHeaderType.Add(Global.None);
}
cmbHeaderType.ItemsSource = lstHeaderType;
cmbHeaderType.SelectedIndex = 0;
}
private void SetTips()
{
var network = cmbNetwork.SelectedItem.ToString();
var network = cmbNetwork.SelectedItem?.ToString();
if (network.IsNullOrEmpty())
{
network = Global.DefaultNetwork;
}
labHeaderType.IsVisible = true;
btnExtra.IsVisible = false;
tipRequestHost.Text =
tipPath.Text =
tipHeaderType.Text = string.Empty;
gridTransportRaw.IsVisible = false;
gridTransportKcp.IsVisible = false;
gridTransportWs.IsVisible = false;
gridTransportHttpupgrade.IsVisible = false;
gridTransportXhttp.IsVisible = false;
gridTransportGrpc.IsVisible = false;
switch (network)
{
case nameof(ETransport.tcp):
tipRequestHost.Text = ResUI.TransportRequestHostTip1;
tipHeaderType.Text = ResUI.TransportHeaderTypeTip1;
case nameof(ETransport.raw):
gridTransportRaw.IsVisible = true;
break;
case nameof(ETransport.kcp):
tipHeaderType.Text = ResUI.TransportHeaderTypeTip2;
tipPath.Text = ResUI.TransportPathTip5;
gridTransportKcp.IsVisible = true;
break;
case nameof(ETransport.ws):
gridTransportWs.IsVisible = true;
break;
case nameof(ETransport.httpupgrade):
tipRequestHost.Text = ResUI.TransportRequestHostTip2;
tipPath.Text = ResUI.TransportPathTip1;
gridTransportHttpupgrade.IsVisible = true;
break;
case nameof(ETransport.xhttp):
tipRequestHost.Text = ResUI.TransportRequestHostTip2;
tipPath.Text = ResUI.TransportPathTip1;
tipHeaderType.Text = ResUI.TransportHeaderTypeTip5;
labHeaderType.IsVisible = false;
btnExtra.IsVisible = true;
break;
case nameof(ETransport.h2):
tipRequestHost.Text = ResUI.TransportRequestHostTip3;
tipPath.Text = ResUI.TransportPathTip2;
break;
case nameof(ETransport.quic):
tipRequestHost.Text = ResUI.TransportRequestHostTip4;
tipPath.Text = ResUI.TransportPathTip3;
tipHeaderType.Text = ResUI.TransportHeaderTypeTip3;
gridTransportXhttp.IsVisible = true;
break;
case nameof(ETransport.grpc):
tipRequestHost.Text = ResUI.TransportRequestHostTip5;
tipPath.Text = ResUI.TransportPathTip4;
tipHeaderType.Text = ResUI.TransportHeaderTypeTip4;
labHeaderType.IsVisible = false;
gridTransportGrpc.IsVisible = true;
break;
default:
gridTransportRaw.IsVisible = true;
break;
}
SetRawHttpFieldsVisibility();
}
private void SetRawHttpFieldsVisibility()
{
var network = cmbNetwork.SelectedItem?.ToString();
if (network.IsNullOrEmpty())
{
network = Global.DefaultNetwork;
}
var rawHeaderType = cmbHeaderTypeRaw.SelectedItem?.ToString();
var showRawHttpFields = network == nameof(ETransport.raw)
&& rawHeaderType == Global.RawHeaderHttp;
gridTransportRawHttp.IsVisible = showRawHttpFields;
}
}
@@ -342,11 +342,6 @@
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<TextBlock
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbSettingsRemoteDNS}" />
<TextBlock Margin="{StaticResource Margin4}" VerticalAlignment="Center">
<HyperlinkButton Classes="WithIcon" Click="linkDnsObjectDoc_Click">
<TextBlock Text="{x:Static resx:ResUI.TbDnsObjectDoc}" />
@@ -395,13 +390,26 @@
</StackPanel>
</WrapPanel>
<HeaderedContentControl
Margin="{StaticResource Margin4}"
BorderBrush="Gray"
BorderThickness="1"
Header="HTTP/SOCKS">
<local:JsonEditor Name="txtnormalDNSCompatible" VerticalAlignment="Stretch" />
</HeaderedContentControl>
<Grid Margin="{StaticResource Margin4}" ColumnDefinitions="*,10,*">
<HeaderedContentControl
Grid.Column="0"
BorderBrush="Gray"
BorderThickness="1"
Header="HTTP/SOCKS">
<local:JsonEditor Name="txtnormalDNSCompatible" VerticalAlignment="Stretch" />
</HeaderedContentControl>
<GridSplitter Grid.Column="1" HorizontalAlignment="Stretch" />
<HeaderedContentControl
Grid.Column="2"
BorderBrush="Gray"
BorderThickness="1"
Header="{x:Static resx:ResUI.TbSettingsTunMode}">
<local:JsonEditor Name="txttunDNSCompatible" VerticalAlignment="Stretch" />
</HeaderedContentControl>
</Grid>
</DockPanel>
</TabItem>
@@ -481,7 +489,6 @@
Header="{x:Static resx:ResUI.TbSettingsTunMode}">
<local:JsonEditor Name="txttunDNS2Compatible" VerticalAlignment="Stretch" />
</HeaderedContentControl>
</Grid>
</DockPanel>
</TabItem>
@@ -52,6 +52,7 @@ public partial class DNSSettingWindow : WindowBase<DNSSettingViewModel>
this.Bind(ViewModel, vm => vm.DomainStrategy4FreedomCompatible, v => v.cmbdomainStrategy4FreedomCompatible.SelectedItem).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DomainDNSAddressCompatible, v => v.cmbdomainDNSAddressCompatible.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.NormalDNSCompatible, v => v.txtnormalDNSCompatible.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.TunDNSCompatible, v => v.txttunDNSCompatible.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DomainStrategy4Freedom2Compatible, v => v.cmbdomainStrategy4OutCompatible.SelectedItem).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DomainDNSAddress2Compatible, v => v.cmbdomainDNSAddress2Compatible.Text).DisposeWith(disposables);
@@ -90,13 +90,26 @@
</StackPanel>
</WrapPanel>
<HeaderedContentControl
Margin="{StaticResource Margin4}"
BorderBrush="Gray"
BorderThickness="1"
Header="xray config template json">
<views:JsonEditor x:Name="rayFullConfigTemplate" VerticalAlignment="Stretch" />
</HeaderedContentControl>
<Grid Margin="{StaticResource Margin4}" ColumnDefinitions="*,10,*">
<HeaderedContentControl
Grid.Column="0"
BorderBrush="Gray"
BorderThickness="1"
Header="xray config template json">
<views:JsonEditor x:Name="rayFullConfigTemplate" VerticalAlignment="Stretch" />
</HeaderedContentControl>
<GridSplitter Grid.Column="1" HorizontalAlignment="Stretch" />
<HeaderedContentControl
Grid.Column="2"
BorderBrush="Gray"
BorderThickness="1"
Header="xray tun config template json">
<views:JsonEditor x:Name="rayFullTunConfigTemplate" VerticalAlignment="Stretch" />
</HeaderedContentControl>
</Grid>
</DockPanel>
</TabItem>
<TabItem HorizontalAlignment="Left" Header="{x:Static resx:ResUI.TbSBFullConfigTemplate}">
@@ -12,13 +12,14 @@ public partial class FullConfigTemplateWindow : WindowBase<FullConfigTemplateVie
_config = AppManager.Instance.Config;
Loaded += Window_Loaded;
btnCancel.Click += (s, e) => Close();
btnCancel.Click += (_, _) => Close();
ViewModel = new FullConfigTemplateViewModel(UpdateViewHandler);
this.WhenActivated(disposables =>
{
this.Bind(ViewModel, vm => vm.EnableFullConfigTemplate4Ray, v => v.rayFullConfigTemplateEnable.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.FullConfigTemplate4Ray, v => v.rayFullConfigTemplate.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.FullTunConfigTemplate4Ray, v => v.rayFullTunConfigTemplate.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.AddProxyOnly4Ray, v => v.togAddProxyProtocolOutboundOnly4Ray.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.ProxyDetour4Ray, v => v.txtProxyDetour4Ray.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.EnableFullConfigTemplate4Singbox, v => v.sbFullConfigTemplateEnable.IsChecked).DisposeWith(disposables);
@@ -0,0 +1,53 @@
<Window
x:Class="v2rayN.Desktop.Views.MessageBoxDialog"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:resx="clr-namespace:ServiceLib.Resx;assembly=ServiceLib"
Width="420"
MinWidth="350"
MaxWidth="600"
CanResize="False"
ShowInTaskbar="False"
SizeToContent="Height"
SystemDecorations="Full"
WindowStartupLocation="CenterOwner"
mc:Ignorable="d">
<Grid Margin="24" RowDefinitions="*,Auto">
<ScrollViewer
Grid.Row="0"
MinHeight="60"
MaxHeight="300"
Margin="0,0,0,24"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto">
<TextBlock
x:Name="txtMessage"
VerticalAlignment="Center"
FontSize="14"
LineHeight="22"
TextWrapping="Wrap" />
</ScrollViewer>
<StackPanel
Grid.Row="1"
HorizontalAlignment="Right"
Orientation="Horizontal"
Spacing="12">
<Button
x:Name="btnYes"
MinWidth="90"
HorizontalContentAlignment="Center"
Content="{x:Static resx:ResUI.TbConfirm}"
IsDefault="True" />
<Button
x:Name="btnNo"
MinWidth="90"
HorizontalContentAlignment="Center"
Content="{x:Static resx:ResUI.TbCancel}"
IsCancel="True" />
</StackPanel>
</Grid>
</Window>
@@ -0,0 +1,27 @@
using v2rayN.Desktop.Common;
namespace v2rayN.Desktop.Views;
public partial class MessageBoxDialog : Window
{
public MessageBoxDialog(string caption, string message)
{
InitializeComponent();
Title = caption;
txtMessage.Text = message;
btnYes.Click += BtnYes_Click;
btnNo.Click += BtnNo_Click;
}
private void BtnYes_Click(object? sender, RoutedEventArgs e)
{
Close(ButtonResult.Yes);
}
private void BtnNo_Click(object? sender, RoutedEventArgs e)
{
Close(ButtonResult.No);
}
}
@@ -355,7 +355,7 @@
<Grid
Margin="{StaticResource Margin4}"
ColumnDefinitions="Auto,Auto,*"
RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto">
RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto">
<TextBlock
x:Name="tbAutoRun"
@@ -418,7 +418,7 @@
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left" />
<TextBlock
<!--<TextBlock
Grid.Row="5"
Grid.Column="0"
Margin="{StaticResource Margin4}"
@@ -429,7 +429,7 @@
Grid.Row="5"
Grid.Column="1"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left" />
HorizontalAlignment="Left" />-->
<TextBlock
Grid.Row="8"
@@ -588,57 +588,71 @@
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbSettingsUdpTestUrl}" />
<ComboBox
x:Name="cmbUdpTestTarget"
Grid.Row="20"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
IsEditable="True" />
<TextBlock
Grid.Row="22"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbSettingsIPAPIUrl}" />
<ComboBox
x:Name="cmbIPAPIUrl"
Grid.Row="20"
Grid.Row="22"
Grid.Column="1"
Width="300"
Margin="{StaticResource Margin4}"
IsEditable="True" />
<TextBlock
Grid.Row="21"
Grid.Row="23"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbSettingsSubConvert}" />
<ComboBox
x:Name="cmbSubConvertUrl"
Grid.Row="21"
Grid.Row="23"
Grid.Column="1"
Width="300"
Margin="{StaticResource Margin4}"
IsEditable="True" />
<TextBlock
Grid.Row="22"
Grid.Row="24"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbSettingsMainGirdOrientation}" />
<ComboBox
x:Name="cmbMainGirdOrientation"
Grid.Row="22"
Grid.Row="24"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}" />
<TextBlock
Grid.Row="23"
Grid.Row="25"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbSettingsGeoFilesSource}" />
<ComboBox
x:Name="cmbGetFilesSourceUrl"
Grid.Row="23"
Grid.Row="25"
Grid.Column="1"
Width="300"
Margin="{StaticResource Margin4}"
IsEditable="True" />
<TextBlock
Grid.Row="23"
Grid.Row="25"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
@@ -646,20 +660,20 @@
TextWrapping="Wrap" />
<TextBlock
Grid.Row="24"
Grid.Row="26"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbSettingsSrsFilesSource}" />
<ComboBox
x:Name="cmbSrsFilesSourceUrl"
Grid.Row="24"
Grid.Row="26"
Grid.Column="1"
Width="300"
Margin="{StaticResource Margin4}"
IsEditable="True" />
<TextBlock
Grid.Row="24"
Grid.Row="26"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
@@ -667,26 +681,25 @@
TextWrapping="Wrap" />
<TextBlock
Grid.Row="25"
Grid.Row="27"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbSettingsRoutingRulesSource}" />
<ComboBox
x:Name="cmbRoutingRulesSourceUrl"
Grid.Row="25"
Grid.Row="27"
Grid.Column="1"
Width="300"
Margin="{StaticResource Margin4}"
IsEditable="True" />
<TextBlock
Grid.Row="25"
Grid.Row="27"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbSettingsChinaUserTip}"
TextWrapping="Wrap" />
</Grid>
</ScrollViewer>
</TabItem>
@@ -49,6 +49,7 @@ public partial class OptionSettingWindow : WindowBase<OptionSettingViewModel>
cmbSpeedTestTimeout.ItemsSource = Enumerable.Range(2, 5).Select(i => i * 5).ToList();
cmbSpeedTestUrl.ItemsSource = Global.SpeedTestUrls;
cmbSpeedPingTestUrl.ItemsSource = Global.SpeedPingTestUrls;
cmbUdpTestTarget.ItemsSource = Global.UdpTestTargets;
cmbSubConvertUrl.ItemsSource = Global.SubConvertUrls;
cmbGetFilesSourceUrl.ItemsSource = Global.GeoFilesSources;
cmbSrsFilesSourceUrl.ItemsSource = Global.SingboxRulesetSources;
@@ -87,7 +88,7 @@ public partial class OptionSettingWindow : WindowBase<OptionSettingViewModel>
this.Bind(ViewModel, vm => vm.EnableStatistics, v => v.togEnableStatistics.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DisplayRealTimeSpeed, v => v.togDisplayRealTimeSpeed.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.KeepOlderDedupl, v => v.togKeepOlderDedupl.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.EnableAutoAdjustMainLvColWidth, v => v.togEnableAutoAdjustMainLvColWidth.IsChecked).DisposeWith(disposables);
//this.Bind(ViewModel, vm => vm.EnableAutoAdjustMainLvColWidth, v => v.togEnableAutoAdjustMainLvColWidth.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.AutoHideStartup, v => v.togAutoHideStartup.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Hide2TrayWhenClose, v => v.togHide2TrayWhenClose.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.MacOSShowInDock, v => v.togMacOSShowInDock.IsChecked).DisposeWith(disposables);
@@ -97,9 +98,11 @@ public partial class OptionSettingWindow : WindowBase<OptionSettingViewModel>
this.Bind(ViewModel, vm => vm.SpeedTestTimeout, v => v.cmbSpeedTestTimeout.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SpeedTestUrl, v => v.cmbSpeedTestUrl.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SpeedPingTestUrl, v => v.cmbSpeedPingTestUrl.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.UdpTestTarget, v => v.cmbUdpTestTarget.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.MixedConcurrencyCount, v => v.cmbMixedConcurrencyCount.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SubConvertUrl, v => v.cmbSubConvertUrl.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.MainGirdOrientation, v => v.cmbMainGirdOrientation.SelectedIndex).DisposeWith(disposables);
this.Bind<OptionSettingViewModel, OptionSettingWindow, int, int>(ViewModel,
vm => vm.MainGirdOrientation, view => view.cmbMainGirdOrientation.SelectedIndex).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.GeoFileSourceUrl, v => v.cmbGetFilesSourceUrl.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SrsFileSourceUrl, v => v.cmbSrsFilesSourceUrl.SelectedValue).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.RoutingRulesSourceUrl, v => v.cmbRoutingRulesSourceUrl.SelectedValue).DisposeWith(disposables);
@@ -140,6 +140,7 @@
x:Name="menuSpeedServer"
Header="{x:Static resx:ResUI.menuSpeedServer}"
InputGesture="Ctrl+T" />
<MenuItem x:Name="menuUdpTestServer" Header="{x:Static resx:ResUI.menuUdpTestServer}" />
<MenuItem x:Name="menuSortServerResult" Header="{x:Static resx:ResUI.menuSortServerResult}" />
<Separator />
<MenuItem
@@ -77,6 +77,7 @@ public partial class ProfilesView : ReactiveUserControl<ProfilesViewModel>
this.BindCommand(ViewModel, vm => vm.MixedTestServerCmd, v => v.menuMixedTestServer).DisposeWith(disposables);
this.BindCommand(ViewModel, vm => vm.TcpingServerCmd, v => v.menuTcpingServer).DisposeWith(disposables);
this.BindCommand(ViewModel, vm => vm.RealPingServerCmd, v => v.menuRealPingServer).DisposeWith(disposables);
this.BindCommand(ViewModel, vm => vm.UdpTestServerCmd, v => v.menuUdpTestServer).DisposeWith(disposables);
this.BindCommand(ViewModel, vm => vm.SpeedServerCmd, v => v.menuSpeedServer).DisposeWith(disposables);
this.BindCommand(ViewModel, vm => vm.SortServerResultCmd, v => v.menuSortServerResult).DisposeWith(disposables);
this.BindCommand(ViewModel, vm => vm.RemoveInvalidServerResultCmd, v => v.menuRemoveInvalidServerResult).DisposeWith(disposables);
@@ -94,11 +95,11 @@ public partial class ProfilesView : ReactiveUserControl<ProfilesViewModel>
.Subscribe(_ => StorageUI())
.DisposeWith(disposables);
AppEvents.AdjustMainLvColWidthRequested
.AsObservable()
.ObserveOn(RxSchedulers.MainThreadScheduler)
.Subscribe(_ => AutofitColumnWidth())
.DisposeWith(disposables);
//AppEvents.AdjustMainLvColWidthRequested
// .AsObservable()
// .ObserveOn(RxSchedulers.MainThreadScheduler)
// .Subscribe(_ => AutofitColumnWidth())
// .DisposeWith(disposables);
});
RestoreUI();
@@ -20,24 +20,6 @@
<MenuItem x:Name="menuRoutingAdvancedImportRules2" Header="{x:Static resx:ResUI.menuRoutingAdvancedImportRules}" />
</Menu>
<StackPanel
Margin="{StaticResource Margin4}"
HorizontalAlignment="Right"
DockPanel.Dock="Bottom"
Orientation="Horizontal">
<Button
x:Name="btnSave"
Width="100"
Content="{x:Static resx:ResUI.TbConfirm}"
IsDefault="True" />
<Button
x:Name="btnCancel"
Width="100"
Margin="{StaticResource MarginLr8}"
Content="{x:Static resx:ResUI.TbCancel}"
IsCancel="True" />
</StackPanel>
<Grid
Margin="{StaticResource Margin4}"
ColumnDefinitions="Auto,Auto"
@@ -5,15 +5,12 @@ namespace v2rayN.Desktop.Views;
public partial class RoutingSettingWindow : WindowBase<RoutingSettingViewModel>
{
private bool _manualClose = false;
public RoutingSettingWindow()
{
InitializeComponent();
Loaded += Window_Loaded;
Closing += RoutingSettingWindow_Closing;
btnCancel.Click += (s, e) => Close();
KeyDown += RoutingSettingWindow_KeyDown;
lstRoutings.SelectionChanged += lstRoutings_SelectionChanged;
lstRoutings.DoubleTapped += LstRoutings_DoubleTapped;
@@ -38,8 +35,6 @@ public partial class RoutingSettingWindow : WindowBase<RoutingSettingViewModel>
this.BindCommand(ViewModel, vm => vm.RoutingAdvancedSetDefaultCmd, v => v.menuRoutingAdvancedSetDefault).DisposeWith(disposables);
this.BindCommand(ViewModel, vm => vm.RoutingAdvancedImportRulesCmd, v => v.menuRoutingAdvancedImportRules).DisposeWith(disposables);
this.BindCommand(ViewModel, vm => vm.RoutingAdvancedImportRulesCmd, v => v.menuRoutingAdvancedImportRules2).DisposeWith(disposables);
this.BindCommand(ViewModel, vm => vm.SaveCmd, v => v.btnSave).DisposeWith(disposables);
});
}
@@ -47,10 +42,6 @@ public partial class RoutingSettingWindow : WindowBase<RoutingSettingViewModel>
{
switch (action)
{
case EViewAction.CloseWindow:
Close(true);
break;
case EViewAction.ShowYesNo:
if (await UI.ShowYesNo(this, ResUI.RemoveRules) != ButtonResult.Yes)
{
@@ -69,6 +60,24 @@ public partial class RoutingSettingWindow : WindowBase<RoutingSettingViewModel>
return await Task.FromResult(true);
}
private bool _closed = false;
private void RoutingSettingWindow_Closing(object? sender, WindowClosingEventArgs e)
{
if (_closed)
{
return;
}
// DomainStrategy is auto-saved reactively; just ensure the caller knows changes were made
if (ViewModel?.IsModified == true)
{
e.Cancel = true;
_closed = true;
Close(true);
}
}
private void RoutingSettingWindow_KeyDown(object? sender, KeyEventArgs e)
{
if (e.KeyModifiers is KeyModifiers.Control or KeyModifiers.Meta)
@@ -125,25 +134,7 @@ public partial class RoutingSettingWindow : WindowBase<RoutingSettingViewModel>
ProcUtils.ProcessStart("https://sing-box.sagernet.org/zh/configuration/route/rule_action/#strategy");
}
private void btnCancel_Click(object? sender, RoutedEventArgs e)
{
_manualClose = true;
Close(ViewModel?.IsModified);
}
private void RoutingSettingWindow_Closing(object? sender, WindowClosingEventArgs e)
{
if (ViewModel?.IsModified == true)
{
if (!_manualClose)
{
btnCancel_Click(null, null);
}
}
}
private void Window_Loaded(object? sender, RoutedEventArgs e)
{
btnCancel.Focus();
}
}
+1 -1
View File
@@ -16,8 +16,8 @@
</PackageReference>
<PackageReference Include="Avalonia.Desktop" />
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" />
<PackageReference Include="DialogHost.Avalonia" />
<PackageReference Include="ReactiveUI.Avalonia" />
<PackageReference Include="MessageBox.Avalonia" />
<PackageReference Include="Semi.Avalonia" />
<PackageReference Include="Semi.Avalonia.AvaloniaEdit" />
<PackageReference Include="Semi.Avalonia.DataGrid">
+9 -3
View File
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32811.315
# Visual Studio Version 18
VisualStudioVersion = 18.5.11709.299 stable
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "v2rayN", "v2rayN\v2rayN.csproj", "{6DE127CA-1763-4236-B297-D2EF9CB2EC9B}"
EndProject
@@ -34,6 +34,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GitHub Action", "GitHub Act
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServiceLib.Tests", "ServiceLib.Tests\ServiceLib.Tests.csproj", "{E0B6C5C7-ED48-42EB-947A-877779E9F555}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServiceLib.UdpTest", "ServiceLib.UdpTest\ServiceLib.UdpTest.csproj", "{CE9D9298-0289-4718-2522-B236489F2912}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -64,6 +66,10 @@ Global
{E0B6C5C7-ED48-42EB-947A-877779E9F555}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E0B6C5C7-ED48-42EB-947A-877779E9F555}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E0B6C5C7-ED48-42EB-947A-877779E9F555}.Release|Any CPU.Build.0 = Release|Any CPU
{CE9D9298-0289-4718-2522-B236489F2912}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CE9D9298-0289-4718-2522-B236489F2912}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CE9D9298-0289-4718-2522-B236489F2912}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CE9D9298-0289-4718-2522-B236489F2912}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+1
View File
@@ -17,6 +17,7 @@
<Project Path="AmazTool/AmazTool.csproj" />
<Project Path="GlobalHotKeys/src/GlobalHotKeys/GlobalHotKeys.csproj" />
<Project Path="ServiceLib.Tests/ServiceLib.Tests.csproj" />
<Project Path="ServiceLib.UdpTest/ServiceLib.UdpTest.csproj" Id="77930428-4dc4-4130-9031-6b9e714f5d20" />
<Project Path="ServiceLib/ServiceLib.csproj" />
<Project Path="v2rayN.Desktop/v2rayN.Desktop.csproj" />
<Project Path="v2rayN/v2rayN.csproj" />
@@ -137,7 +137,7 @@ public class ThemeSettingViewModel : MyReactiveObject
private void ModifyFontSize()
{
double size = (long)CurrentFontSize;
double size = CurrentFontSize;
if (size < Global.MinFontSize)
{
return;
+383 -144
View File
@@ -150,7 +150,7 @@
<Grid
x:Name="gridVMess"
Grid.Row="2"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -234,7 +234,7 @@
<Grid
x:Name="gridSs"
Grid.Row="2"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -308,7 +308,7 @@
<Grid
x:Name="gridSocks"
Grid.Row="2"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -353,7 +353,7 @@
<Grid
x:Name="gridVLESS"
Grid.Row="2"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -415,7 +415,7 @@
x:Name="txtSecurity5"
Grid.Row="3"
Grid.Column="1"
Width="200"
Width="400"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left"
Style="{StaticResource DefTextBox}" />
@@ -437,7 +437,7 @@
<Grid
x:Name="gridTrojan"
Grid.Row="2"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -497,7 +497,7 @@
<Grid
x:Name="gridHysteria2"
Grid.Row="2"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -610,7 +610,7 @@
<Grid
x:Name="gridTuic"
Grid.Row="2"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -670,7 +670,7 @@
<Grid
x:Name="gridWireguard"
Grid.Row="2"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -767,7 +767,7 @@
<Grid
x:Name="gridAnytls"
Grid.Row="2"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -796,7 +796,7 @@
<Grid
x:Name="gridNaive"
Grid.Row="2"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -907,143 +907,376 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Row="0"
Grid.ColumnSpan="2"
Margin="{StaticResource Margin4}"
Style="{StaticResource ModuleTitle}"
Text="{x:Static resx:ResUI.GbTransport}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbNetwork}" />
<ComboBox
x:Name="cmbNetwork"
Grid.Row="1"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefComboBox}" />
<TextBlock
Grid.Row="1"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TipNetwork}" />
<TextBlock
x:Name="labHeaderType"
Grid.Row="2"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbHeaderType}" />
<StackPanel
Grid.Row="2"
Grid.Column="1"
VerticalAlignment="Center"
Orientation="Horizontal">
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbNetwork}" />
<ComboBox
x:Name="cmbHeaderType"
x:Name="cmbNetwork"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefComboBox}" />
<TextBlock
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TipNetwork}" />
</Grid>
<materialDesign:PopupBox
x:Name="popExtra"
HorizontalAlignment="Right"
StaysOpen="True"
Style="{StaticResource MaterialDesignToolForegroundPopupBox}">
<StackPanel>
<Grid Grid.Row="2">
<Grid x:Name="gridTransportRaw" Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TransportExtraTip}" />
<TextBox
x:Name="txtExtra"
Width="400"
Text="{x:Static resx:ResUI.TransportHeaderType1}" />
<ComboBox
x:Name="cmbHeaderTypeRaw"
Grid.Row="0"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefComboBox}" />
</Grid>
<Grid
x:Name="gridTransportRawHttp"
Grid.Row="1"
Visibility="Collapsed">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
AcceptsReturn="True"
MinLines="6"
Style="{StaticResource MyOutlinedTextBox}"
TextWrapping="Wrap" />
</StackPanel>
</materialDesign:PopupBox>
</StackPanel>
<TextBlock
x:Name="tipHeaderType"
Grid.Row="2"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbHeaderType}" />
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbCamouflageDomain}" />
<TextBox
x:Name="txtRequestHostRaw"
Grid.Row="0"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbPath}" />
<TextBox
x:Name="txtPathRaw"
Grid.Row="1"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
</Grid>
</Grid>
<TextBlock
Grid.Row="3"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbRequestHost}" />
<TextBox
x:Name="txtRequestHost"
Grid.Row="3"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
<TextBlock
x:Name="tipRequestHost"
Grid.Row="3"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbRequestHost}" />
<Grid x:Name="gridTransportXhttp" Visibility="Collapsed">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TransportHeaderType5}" />
<ComboBox
x:Name="cmbHeaderTypeXhttp"
Grid.Row="0"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefComboBox}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbHost}" />
<TextBox
x:Name="txtRequestHostXhttp"
Grid.Row="1"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
<TextBlock
Grid.Row="2"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbPath}" />
<TextBox
x:Name="txtPathXhttp"
Grid.Row="2"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
<TextBlock
Grid.Row="3"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Top"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TransportExtra}"
TextWrapping="Wrap" />
<TextBox
x:Name="txtExtraXhttp"
Grid.Row="3"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
materialDesign:HintAssist.Hint="{x:Static resx:ResUI.TransportExtraTip}"
AcceptsReturn="True"
MaxLines="12"
MinLines="3"
Style="{StaticResource MyOutlinedTextBox}"
TextWrapping="Wrap" />
</Grid>
<TextBlock
Grid.Row="4"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbPath}" />
<TextBox
x:Name="txtPath"
Grid.Row="4"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
<TextBlock
x:Name="tipPath"
Grid.Row="4"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbPath}" />
<Grid x:Name="gridTransportKcp" Visibility="Collapsed">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TransportHeaderType2}" />
<ComboBox
x:Name="cmbHeaderTypeKcp"
Grid.Row="0"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left"
Style="{StaticResource DefComboBox}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="MTU" />
<TextBox
x:Name="txtKcpMtu"
Grid.Row="1"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left"
Style="{StaticResource DefTextBox}" />
<TextBlock
Grid.Row="2"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="Seed" />
<TextBox
x:Name="txtKcpSeed"
Grid.Row="2"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left"
Style="{StaticResource DefTextBox}" />
</Grid>
<Grid x:Name="gridTransportGrpc" Visibility="Collapsed">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TransportHeaderType4}" />
<ComboBox
x:Name="cmbHeaderTypeGrpc"
Grid.Row="0"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefComboBox}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TransportRequestHostTip5}" />
<TextBox
x:Name="txtRequestHostGrpc"
Grid.Row="1"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
<TextBlock
Grid.Row="2"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TransportPathTip4}" />
<TextBox
x:Name="txtPathGrpc"
Grid.Row="2"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
</Grid>
<Grid x:Name="gridTransportWs" Visibility="Collapsed">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbHost}" />
<TextBox
x:Name="txtRequestHostWs"
Grid.Row="0"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbPath}" />
<TextBox
x:Name="txtPathWs"
Grid.Row="1"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
</Grid>
<Grid x:Name="gridTransportHttpupgrade" Visibility="Collapsed">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbHost}" />
<TextBox
x:Name="txtRequestHostHttpupgrade"
Grid.Row="0"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
<TextBlock
Grid.Row="1"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbPath}" />
<TextBox
x:Name="txtPathHttpupgrade"
Grid.Row="1"
Grid.Column="1"
Width="400"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefTextBox}" />
</Grid>
</Grid>
</Grid>
<Grid x:Name="gridFinalmask" Grid.Row="5">
@@ -1117,7 +1350,7 @@
<Grid
x:Name="gridTlsMore"
Grid.Row="8"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -1211,21 +1444,6 @@
HorizontalAlignment="Left"
Style="{StaticResource DefTextBox}" />
<TextBlock
Grid.Row="6"
Grid.Column="0"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbEchForceQuery}" />
<ComboBox
x:Name="cmbEchForceQuery"
Grid.Row="6"
Grid.Column="1"
Width="200"
Margin="{StaticResource Margin4}"
Style="{StaticResource DefComboBox}" />
<TextBlock
Grid.Row="7"
Grid.Column="0"
@@ -1268,6 +1486,27 @@
Content="{x:Static resx:ResUI.TbFetchCertChain}"
Style="{StaticResource DefButton}" />
</StackPanel>
<StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
<TextBlock
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbAllowInsecureCertFetch}" />
<ToggleButton
x:Name="togAllowInsecureCertFetch"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left" />
</StackPanel>
<TextBlock
x:Name="txtAllowInsecureCertFetchTips"
Width="400"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Foreground="#FFD32F2F"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbAllowInsecureCertFetchTips}"
TextWrapping="Wrap"
Visibility="Collapsed" />
<TextBlock
Width="400"
Margin="{StaticResource Margin4}"
@@ -1306,7 +1545,7 @@
<Grid
x:Name="gridRealityMore"
Grid.Row="8"
Visibility="Hidden">
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
+93 -90
View File
@@ -11,6 +11,7 @@ public partial class AddServerWindow
Owner = Application.Current.MainWindow;
Loaded += Window_Loaded;
cmbNetwork.SelectionChanged += CmbNetwork_SelectionChanged;
cmbHeaderTypeRaw.SelectionChanged += CmbHeaderTypeRaw_SelectionChanged;
cmbStreamSecurity.SelectionChanged += CmbStreamSecurity_SelectionChanged;
btnGUID.Click += btnGUID_Click;
btnGUID5.Click += btnGUID_Click;
@@ -19,15 +20,26 @@ public partial class AddServerWindow
cmbCoreType.ItemsSource = Global.CoreTypes.AppendEmpty();
cmbNetwork.ItemsSource = Global.Networks;
if (ViewModel.SelectedSource.Network.IsNullOrEmpty() || !Global.Networks.Contains(ViewModel.SelectedSource.Network))
{
ViewModel.SelectedSource.Network = Global.DefaultNetwork;
}
cmbHeaderTypeRaw.ItemsSource = new List<string> { Global.None, Global.RawHeaderHttp };
var kcpHeaderTypes = new List<string> { Global.None };
kcpHeaderTypes.AddRange(Global.KcpHeaderTypes);
cmbHeaderTypeKcp.ItemsSource = kcpHeaderTypes;
cmbHeaderTypeXhttp.ItemsSource = Global.XhttpMode;
cmbHeaderTypeGrpc.ItemsSource = new List<string> { Global.GrpcGunMode, Global.GrpcMultiMode };
cmbFingerprint.ItemsSource = Global.Fingerprints;
cmbFingerprint2.ItemsSource = Global.Fingerprints;
cmbAllowInsecure.ItemsSource = Global.AllowInsecure;
cmbAlpn.ItemsSource = Global.Alpns;
cmbEchForceQuery.ItemsSource = Global.EchForceQuerys;
var lstStreamSecurity = new List<string>();
lstStreamSecurity.Add(string.Empty);
lstStreamSecurity.Add(Global.StreamSecurity);
var lstStreamSecurity = new List<string> { string.Empty, Global.StreamSecurity };
switch (profileItem.ConfigType)
{
@@ -114,7 +126,7 @@ public partial class AddServerWindow
}
cmbStreamSecurity.ItemsSource = lstStreamSecurity;
gridTlsMore.Visibility = Visibility.Hidden;
gridTlsMore.Visibility = Visibility.Collapsed;
this.WhenActivated(disposables =>
{
@@ -195,10 +207,28 @@ public partial class AddServerWindow
break;
}
this.Bind(ViewModel, vm => vm.SelectedSource.Network, v => v.cmbNetwork.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.HeaderType, v => v.cmbHeaderType.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.RequestHost, v => v.txtRequestHost.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.Path, v => v.txtPath.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.Extra, v => v.txtExtra.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.RawHeaderType, v => v.cmbHeaderTypeRaw.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostRaw.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Path, v => v.txtPathRaw.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.KcpHeaderType, v => v.cmbHeaderTypeKcp.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.KcpSeed, v => v.txtKcpSeed.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.KcpMtu, v => v.txtKcpMtu.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostWs.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Path, v => v.txtPathWs.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostHttpupgrade.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Path, v => v.txtPathHttpupgrade.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.XhttpMode, v => v.cmbHeaderTypeXhttp.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostXhttp.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Path, v => v.txtPathXhttp.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.XhttpExtra, v => v.txtExtraXhttp.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.GrpcMode, v => v.cmbHeaderTypeGrpc.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.GrpcAuthority, v => v.txtRequestHostGrpc.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.GrpcServiceName, v => v.txtPathGrpc.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.StreamSecurity, v => v.cmbStreamSecurity.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.Sni, v => v.txtSNI.Text).DisposeWith(disposables);
@@ -208,9 +238,12 @@ public partial class AddServerWindow
this.Bind(ViewModel, vm => vm.CertSha, v => v.txtCertSha256Pinning.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.CertTip, v => v.labCertPinning.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Cert, v => v.txtCert.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.AllowInsecureCertFetch, v => v.togAllowInsecureCertFetch.IsChecked).DisposeWith(disposables);
this.WhenAnyValue(x => x.ViewModel.AllowInsecureCertFetch)
.Select(b => b ? Visibility.Visible : Visibility.Collapsed)
.BindTo(this, v => v.txtAllowInsecureCertFetchTips.Visibility);
this.Bind(ViewModel, vm => vm.Cert, v => v.txtCert.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.EchConfigList, v => v.txtEchConfigList.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.SelectedSource.EchForceQuery, v => v.cmbEchForceQuery.Text).DisposeWith(disposables);
//reality
this.Bind(ViewModel, vm => vm.SelectedSource.Sni, v => v.txtSNI2.Text).DisposeWith(disposables);
@@ -249,8 +282,12 @@ public partial class AddServerWindow
private void CmbNetwork_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SetHeaderType();
SetTips();
SetTransportGridVisibility();
}
private void CmbHeaderTypeRaw_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SetRawHttpFieldsVisibility();
}
private void CmbStreamSecurity_SelectionChanged(object sender, SelectionChangedEventArgs e)
@@ -259,17 +296,17 @@ public partial class AddServerWindow
if (security == Global.StreamSecurityReality)
{
gridRealityMore.Visibility = Visibility.Visible;
gridTlsMore.Visibility = Visibility.Hidden;
gridTlsMore.Visibility = Visibility.Collapsed;
}
else if (security == Global.StreamSecurity)
{
gridRealityMore.Visibility = Visibility.Hidden;
gridRealityMore.Visibility = Visibility.Collapsed;
gridTlsMore.Visibility = Visibility.Visible;
}
else
{
gridRealityMore.Visibility = Visibility.Hidden;
gridTlsMore.Visibility = Visibility.Hidden;
gridRealityMore.Visibility = Visibility.Collapsed;
gridTlsMore.Visibility = Visibility.Collapsed;
}
}
@@ -279,102 +316,68 @@ public partial class AddServerWindow
txtId5.Text = Utils.GetGuid();
}
private void SetHeaderType()
private void SetTransportGridVisibility()
{
var lstHeaderType = new List<string>();
var network = cmbNetwork.SelectedItem.ToString();
if (network.IsNullOrEmpty())
{
lstHeaderType.Add(Global.None);
cmbHeaderType.ItemsSource = lstHeaderType;
cmbHeaderType.SelectedIndex = 0;
return;
}
if (network == nameof(ETransport.tcp))
{
lstHeaderType.Add(Global.None);
lstHeaderType.Add(Global.TcpHeaderHttp);
}
else if (network is nameof(ETransport.kcp) or nameof(ETransport.quic))
{
lstHeaderType.Add(Global.None);
lstHeaderType.AddRange(Global.KcpHeaderTypes);
}
else if (network is nameof(ETransport.xhttp))
{
lstHeaderType.AddRange(Global.XhttpMode);
}
else if (network == nameof(ETransport.grpc))
{
lstHeaderType.Add(Global.GrpcGunMode);
lstHeaderType.Add(Global.GrpcMultiMode);
}
else
{
lstHeaderType.Add(Global.None);
}
cmbHeaderType.ItemsSource = lstHeaderType;
cmbHeaderType.SelectedIndex = 0;
}
private void SetTips()
{
var network = cmbNetwork.SelectedItem.ToString();
var network = cmbNetwork.SelectedItem?.ToString();
if (network.IsNullOrEmpty())
{
network = Global.DefaultNetwork;
}
labHeaderType.Visibility = Visibility.Visible;
popExtra.Visibility = Visibility.Hidden;
tipRequestHost.Text =
tipPath.Text =
tipHeaderType.Text = string.Empty;
gridTransportRaw.Visibility = Visibility.Collapsed;
gridTransportKcp.Visibility = Visibility.Collapsed;
gridTransportWs.Visibility = Visibility.Collapsed;
gridTransportHttpupgrade.Visibility = Visibility.Collapsed;
gridTransportXhttp.Visibility = Visibility.Collapsed;
gridTransportGrpc.Visibility = Visibility.Collapsed;
switch (network)
{
case nameof(ETransport.tcp):
tipRequestHost.Text = ResUI.TransportRequestHostTip1;
tipHeaderType.Text = ResUI.TransportHeaderTypeTip1;
case nameof(ETransport.raw):
gridTransportRaw.Visibility = Visibility.Visible;
break;
case nameof(ETransport.kcp):
tipHeaderType.Text = ResUI.TransportHeaderTypeTip2;
tipPath.Text = ResUI.TransportPathTip5;
gridTransportKcp.Visibility = Visibility.Visible;
break;
case nameof(ETransport.ws):
gridTransportWs.Visibility = Visibility.Visible;
break;
case nameof(ETransport.httpupgrade):
tipRequestHost.Text = ResUI.TransportRequestHostTip2;
tipPath.Text = ResUI.TransportPathTip1;
gridTransportHttpupgrade.Visibility = Visibility.Visible;
break;
case nameof(ETransport.xhttp):
tipRequestHost.Text = ResUI.TransportRequestHostTip2;
tipPath.Text = ResUI.TransportPathTip1;
tipHeaderType.Text = ResUI.TransportHeaderTypeTip5;
labHeaderType.Visibility = Visibility.Hidden;
popExtra.Visibility = Visibility.Visible;
break;
case nameof(ETransport.h2):
tipRequestHost.Text = ResUI.TransportRequestHostTip3;
tipPath.Text = ResUI.TransportPathTip2;
break;
case nameof(ETransport.quic):
tipRequestHost.Text = ResUI.TransportRequestHostTip4;
tipPath.Text = ResUI.TransportPathTip3;
tipHeaderType.Text = ResUI.TransportHeaderTypeTip3;
gridTransportXhttp.Visibility = Visibility.Visible;
break;
case nameof(ETransport.grpc):
tipRequestHost.Text = ResUI.TransportRequestHostTip5;
tipPath.Text = ResUI.TransportPathTip4;
tipHeaderType.Text = ResUI.TransportHeaderTypeTip4;
labHeaderType.Visibility = Visibility.Hidden;
gridTransportGrpc.Visibility = Visibility.Visible;
break;
default:
gridTransportRaw.Visibility = Visibility.Visible;
break;
}
SetRawHttpFieldsVisibility();
}
private void SetRawHttpFieldsVisibility()
{
var network = cmbNetwork.SelectedItem?.ToString();
if (network.IsNullOrEmpty())
{
network = Global.DefaultNetwork;
}
var rawHeaderType = cmbHeaderTypeRaw.SelectedItem?.ToString();
var showRawHttpFields = network == nameof(ETransport.raw)
&& rawHeaderType == Global.RawHeaderHttp;
gridTransportRawHttp.Visibility = showRawHttpFields
? Visibility.Visible
: Visibility.Collapsed;
}
}
+31 -15
View File
@@ -390,11 +390,6 @@
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<TextBlock
Margin="{StaticResource Margin8}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbSettingsRemoteDNS}" />
<TextBlock
Margin="{StaticResource Margin8}"
VerticalAlignment="Center"
@@ -453,16 +448,37 @@
</StackPanel>
</WrapPanel>
<TextBox
x:Name="txtnormalDNSCompatible"
Margin="{StaticResource Margin8}"
VerticalAlignment="Stretch"
materialDesign:HintAssist.Hint="HTTP/SOCKS"
AcceptsReturn="True"
BorderThickness="1"
Style="{StaticResource MaterialDesignOutlinedTextBox}"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto" />
<Grid Margin="{StaticResource Margin8}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<TextBox
x:Name="txtnormalDNSCompatible"
Grid.Column="0"
VerticalAlignment="Stretch"
materialDesign:HintAssist.Hint="HTTP/SOCKS"
AcceptsReturn="True"
BorderThickness="1"
Style="{StaticResource MaterialDesignOutlinedTextBox}"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto" />
<GridSplitter Grid.Column="1" HorizontalAlignment="Stretch" />
<TextBox
x:Name="txttunDNSCompatible"
Grid.Column="2"
VerticalAlignment="Stretch"
materialDesign:HintAssist.Hint="{x:Static resx:ResUI.TbSettingsTunMode}"
AcceptsReturn="True"
BorderThickness="1"
Style="{StaticResource MaterialDesignOutlinedTextBox}"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto" />
</Grid>
</DockPanel>
</TabItem>
@@ -50,6 +50,7 @@ public partial class DNSSettingWindow
this.Bind(ViewModel, vm => vm.DomainStrategy4FreedomCompatible, v => v.cmbdomainStrategy4FreedomCompatible.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DomainDNSAddressCompatible, v => v.cmbdomainDNSAddressCompatible.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.NormalDNSCompatible, v => v.txtnormalDNSCompatible.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.TunDNSCompatible, v => v.txttunDNSCompatible.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DomainStrategy4Freedom2Compatible, v => v.cmbdomainStrategy4OutCompatible.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DomainDNSAddress2Compatible, v => v.cmbdomainDNSAddress2Compatible.Text).DisposeWith(disposables);
@@ -107,16 +107,37 @@
</StackPanel>
</WrapPanel>
<TextBox
x:Name="rayFullConfigTemplate"
Margin="{StaticResource Margin8}"
VerticalAlignment="Stretch"
materialDesign:HintAssist.Hint="xray config template json"
AcceptsReturn="True"
BorderThickness="1"
Style="{StaticResource MaterialDesignOutlinedTextBox}"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto" />
<Grid Margin="{StaticResource Margin8}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<TextBox
x:Name="rayFullConfigTemplate"
Grid.Column="0"
VerticalAlignment="Stretch"
materialDesign:HintAssist.Hint="xray config template json"
AcceptsReturn="True"
BorderThickness="1"
Style="{StaticResource MaterialDesignOutlinedTextBox}"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto" />
<GridSplitter Grid.Column="1" HorizontalAlignment="Stretch" />
<TextBox
x:Name="rayFullTunConfigTemplate"
Grid.Column="2"
VerticalAlignment="Stretch"
materialDesign:HintAssist.Hint="xray tun config template json"
AcceptsReturn="True"
BorderThickness="1"
Style="{StaticResource MaterialDesignOutlinedTextBox}"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto" />
</Grid>
</DockPanel>
</TabItem>
<TabItem HorizontalAlignment="Left" Header="{x:Static resx:ResUI.TbSBFullConfigTemplate}">
@@ -17,6 +17,7 @@ public partial class FullConfigTemplateWindow
{
this.Bind(ViewModel, vm => vm.EnableFullConfigTemplate4Ray, v => v.rayFullConfigTemplateEnable.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.FullConfigTemplate4Ray, v => v.rayFullConfigTemplate.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.FullTunConfigTemplate4Ray, v => v.rayFullTunConfigTemplate.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.AddProxyOnly4Ray, v => v.togAddProxyProtocolOutboundOnly4Ray.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.ProxyDetour4Ray, v => v.txtProxyDetour4Ray.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.EnableFullConfigTemplate4Singbox, v => v.sbFullConfigTemplateEnable.IsChecked).DisposeWith(disposables);
+2 -2
View File
@@ -170,10 +170,10 @@ public partial class MainWindow
private void OnProgramStarted(object state, bool timeout)
{
Application.Current?.Dispatcher.Invoke((Action)(() =>
Application.Current?.Dispatcher.Invoke(() =>
{
ShowHideWindow(true);
}));
});
}
private async Task DelegateSnackMsg(string content)

Some files were not shown because too many files have changed in this diff Show More