diff --git a/.github/workflows/build-all.yml b/.github/workflows/build-all.yml index 09e84f1d..c7d486bf 100644 --- a/.github/workflows/build-all.yml +++ b/.github/workflows/build-all.yml @@ -7,6 +7,9 @@ on: required: false type: string +permissions: + actions: write + jobs: update: runs-on: ubuntu-latest diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index b28cd8ee..fe3af4a9 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -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 diff --git a/.github/workflows/build-osx.yml b/.github/workflows/build-osx.yml index ab5be89f..3db6f621 100644 --- a/.github/workflows/build-osx.yml +++ b/.github/workflows/build-osx.yml @@ -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 diff --git a/.github/workflows/package-zip.yml b/.github/workflows/package-zip.yml index de89a5ce..d724841a 100644 --- a/.github/workflows/package-zip.yml +++ b/.github/workflows/package-zip.yml @@ -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: diff --git a/package-rhel-riscv.sh b/package-rhel-riscv.sh index e06556e2..ef22934c 100644 --- a/package-rhel-riscv.sh +++ b/package-rhel-riscv.sh @@ -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}" diff --git a/v2rayN/Directory.Build.props b/v2rayN/Directory.Build.props index 9299ae9a..da1004ef 100644 --- a/v2rayN/Directory.Build.props +++ b/v2rayN/Directory.Build.props @@ -1,7 +1,7 @@ - 7.20.4 + 7.21.0 diff --git a/v2rayN/Directory.Packages.props b/v2rayN/Directory.Packages.props index d441b382..4cdb0ad7 100644 --- a/v2rayN/Directory.Packages.props +++ b/v2rayN/Directory.Packages.props @@ -9,13 +9,14 @@ + + - - + + - @@ -27,8 +28,8 @@ - + diff --git a/v2rayN/ServiceLib.Tests/CoreConfig/Context/CoreConfigContextBuilderTests.cs b/v2rayN/ServiceLib.Tests/CoreConfig/Context/CoreConfigContextBuilderTests.cs new file mode 100644 index 00000000..5f185a9f --- /dev/null +++ b/v2rayN/ServiceLib.Tests/CoreConfig/Context/CoreConfigContextBuilderTests.cs @@ -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(); + foreach (var profile in profiles) + { + await SQLiteHelper.Instance.ReplaceAsync(profile); + } + } +} diff --git a/v2rayN/ServiceLib.Tests/CoreConfig/CoreConfigTestFactory.cs b/v2rayN/ServiceLib.Tests/CoreConfig/CoreConfigTestFactory.cs new file mode 100644 index 00000000..c5acd854 --- /dev/null +++ b/v2rayN/ServiceLib.Tests/CoreConfig/CoreConfigTestFactory.cs @@ -0,0 +1,197 @@ +using ServiceLib.Enums; +using ServiceLib.Manager; +using ServiceLib.Models; +using System.Reflection; + +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 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 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 { [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; + } +} diff --git a/v2rayN/ServiceLib.Tests/CoreConfig/Singbox/CoreConfigSingboxServiceTests.cs b/v2rayN/ServiceLib.Tests/CoreConfig/Singbox/CoreConfigSingboxServiceTests.cs new file mode 100644 index 00000000..91f2884b --- /dev/null +++ b/v2rayN/ServiceLib.Tests/CoreConfig/Singbox/CoreConfigSingboxServiceTests.cs @@ -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(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(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(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(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(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 + { + 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(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 + { + 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(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 + { + 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(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(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 + { + 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(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 + { + 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(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 + { + 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(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(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(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()); + } +} diff --git a/v2rayN/ServiceLib.Tests/CoreConfig/V2ray/CoreConfigV2rayServiceTests.cs b/v2rayN/ServiceLib.Tests/CoreConfig/V2ray/CoreConfigV2rayServiceTests.cs new file mode 100644 index 00000000..29b26648 --- /dev/null +++ b/v2rayN/ServiceLib.Tests/CoreConfig/V2ray/CoreConfigV2rayServiceTests.cs @@ -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(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(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(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(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(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 + { + 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(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 + { + 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(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 + { + 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(result.Data!.ToString())!; + var dns = JsonUtils.Deserialize(JsonUtils.Serialize(cfg.dns))!; + + var dnsServers = dns.servers + .Select(s => JsonUtils.Deserialize(JsonUtils.Serialize(s))) + .Where(s => s is not null) + .Cast() + .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(result.Data!.ToString())!; + var dns = JsonUtils.Deserialize(JsonUtils.Serialize(cfg.dns))!; + + var dnsServers = dns.servers + .Select(s => JsonUtils.Deserialize(JsonUtils.Serialize(s))) + .Where(s => s is not null) + .Cast() + .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 + { + 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(result.Data!.ToString())!; + var dns = JsonUtils.Deserialize(JsonUtils.Serialize(cfg.dns))!; + var dnsServers = dns.servers + .Select(s => JsonUtils.Deserialize(JsonUtils.Serialize(s))) + .Where(s => s is not null) + .Cast() + .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 + { + 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(result.Data!.ToString())!; + var dns = JsonUtils.Deserialize(JsonUtils.Serialize(cfg.dns))!; + var dnsServers = dns.servers + .Select(s => JsonUtils.Deserialize(JsonUtils.Serialize(s))) + .Where(s => s is not null) + .Cast() + .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 + { + 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(result.Data!.ToString())!; + var dns = JsonUtils.Deserialize(JsonUtils.Serialize(cfg.dns))!; + var dnsServers = dns.servers + .Select(s => JsonUtils.Deserialize(JsonUtils.Serialize(s))) + .Where(s => s is not null) + .Cast() + .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(result.Data!.ToString())!; + var dns = JsonUtils.Deserialize(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(result.Data!.ToString())!; + var dns = JsonUtils.Deserialize(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"); + } +} diff --git a/v2rayN/ServiceLib.Tests/CoreConfigV2rayServiceTests.cs b/v2rayN/ServiceLib.Tests/CoreConfigV2rayServiceTests.cs deleted file mode 100644 index 52f5d58a..00000000 --- a/v2rayN/ServiceLib.Tests/CoreConfigV2rayServiceTests.cs +++ /dev/null @@ -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() == Global.ProxyTag); - var directOutbound = outbounds.Single(outbound => outbound["tag"]!.GetValue() == Global.DirectTag); - var blockOutbound = outbounds.Single(outbound => outbound["tag"]!.GetValue() == Global.BlockTag); - - Assert.Equal(SendThrough, proxyOutbound["sendThrough"]?.GetValue()); - 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 - { - [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() is not ("freedom" or "blackhole" or "dns")) - .ToList(); - - var sendThroughOutbounds = outbounds - .Where(outbound => outbound["sendThrough"]?.GetValue() == 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() == SendThrough); - } - - private static CoreConfigContext CreateContext( - ProfileItem node, - Config? config = null, - Dictionary? 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 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"); - } -} diff --git a/v2rayN/ServiceLib.Tests/Fmt/FmtHandlerTests.cs b/v2rayN/ServiceLib.Tests/Fmt/FmtHandlerTests.cs new file mode 100644 index 00000000..56fb0f97 --- /dev/null +++ b/v2rayN/ServiceLib.Tests/Fmt/FmtHandlerTests.cs @@ -0,0 +1,173 @@ +using AwesomeAssertions; +using ServiceLib.Handler.Fmt; +using ServiceLib.Models; +using ServiceLib.Enums; +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", + }; + } +} diff --git a/v2rayN/ServiceLib.Tests/ServiceLib.Tests.csproj b/v2rayN/ServiceLib.Tests/ServiceLib.Tests.csproj index 4e1ed1a7..f86ca573 100644 --- a/v2rayN/ServiceLib.Tests/ServiceLib.Tests.csproj +++ b/v2rayN/ServiceLib.Tests/ServiceLib.Tests.csproj @@ -1,17 +1,19 @@ + Exe false true + - all runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/v2rayN/ServiceLib/Common/WindowsUtils.cs b/v2rayN/ServiceLib/Common/WindowsUtils.cs index 2215a3e3..6cd47f0a 100644 --- a/v2rayN/ServiceLib/Common/WindowsUtils.cs +++ b/v2rayN/ServiceLib/Common/WindowsUtils.cs @@ -53,19 +53,23 @@ internal static class WindowsUtils public static async Task RemoveTunDevice() { - try + var tunNameList = new List { "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); + } } } } diff --git a/v2rayN/ServiceLib/Enums/ETransport.cs b/v2rayN/ServiceLib/Enums/ETransport.cs index b1166608..b315c5f0 100644 --- a/v2rayN/ServiceLib/Enums/ETransport.cs +++ b/v2rayN/ServiceLib/Enums/ETransport.cs @@ -2,7 +2,7 @@ namespace ServiceLib.Enums; public enum ETransport { - tcp, + raw, kcp, ws, httpupgrade, diff --git a/v2rayN/ServiceLib/Global.cs b/v2rayN/ServiceLib/Global.cs index d6792115..a20a0ba5 100644 --- a/v2rayN/ServiceLib/Global.cs +++ b/v2rayN/ServiceLib/Global.cs @@ -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 TcpHttpUserAgentTexts = new() + public static readonly Dictionary 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 Networks = [ - "tcp", - "kcp", - "ws", - "httpupgrade", + "raw", "xhttp", - "h2", - "quic", - "grpc" + "kcp", + "grpc", + "ws", + "httpupgrade" ]; public static readonly List 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 TunMtus = diff --git a/v2rayN/ServiceLib/Handler/Builder/CoreConfigContextBuilder.cs b/v2rayN/ServiceLib/Handler/Builder/CoreConfigContextBuilder.cs index 5017250e..886a1971 100644 --- a/v2rayN/ServiceLib/Handler/Builder/CoreConfigContextBuilder.cs +++ b/v2rayN/ServiceLib/Handler/Builder/CoreConfigContextBuilder.cs @@ -23,19 +23,6 @@ public record CoreConfigContextBuilderAllResult( public NodeValidatorResult CombinedValidatorResult => new( [.. MainResult.ValidatorResult.Errors, .. PreSocksResult?.ValidatorResult.Errors ?? []], [.. MainResult.ValidatorResult.Warnings, .. PreSocksResult?.ValidatorResult.Warnings ?? []]); - - /// - /// The main context with TunProtectSocksPort/ProxyRelaySocksPort and ProtectDomainList merged in - /// from the pre-socks result (if any). Pass this to the core runner. - /// - 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); } /// @@ -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; } /// @@ -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) diff --git a/v2rayN/ServiceLib/Handler/Builder/NodeValidator.cs b/v2rayN/ServiceLib/Handler/Builder/NodeValidator.cs index 85c90011..e94635b7 100644 --- a/v2rayN/ServiceLib/Handler/Builder/NodeValidator.cs +++ b/v2rayN/ServiceLib/Handler/Builder/NodeValidator.cs @@ -20,7 +20,7 @@ public class NodeValidator [EConfigType.VMess, EConfigType.VLESS, EConfigType.Trojan, EConfigType.Shadowsocks]; private static readonly HashSet 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); diff --git a/v2rayN/ServiceLib/Handler/ConfigHandler.cs b/v2rayN/ServiceLib/Handler/ConfigHandler.cs index 78229e6c..281db07d 100644 --- a/v2rayN/ServiceLib/Handler/ConfigHandler.cs +++ b/v2rayN/ServiceLib/Handler/ConfigHandler.cs @@ -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, @@ -161,7 +162,7 @@ public static class ConfigHandler config.Fragment4RayItem ??= new() { Packets = "tlshello", - Length = "100-200", + Length = "50-100", Interval = "10-20" }; config.GlobalHotkeys ??= new(); @@ -236,9 +237,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,7 +248,6 @@ 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; @@ -258,6 +255,7 @@ public static class ConfigHandler item.EchForceQuery = profileItem.EchForceQuery; item.Finalmask = profileItem.Finalmask; item.ProtoExtra = profileItem.ProtoExtra; + item.TransportExtra = profileItem.TransportExtra; } var ret = item.ConfigType switch @@ -297,9 +295,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 +746,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 +993,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(); @@ -1067,7 +1061,7 @@ public static class ConfigHandler /// 0 if successful public static async Task AddServerCommon(Config config, ProfileItem profileItem, bool toFile = true) { - profileItem.ConfigVersion = 3; + profileItem.ConfigVersion = 4; if (profileItem.StreamSecurity.IsNotEmpty()) { @@ -1135,6 +1129,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 +1141,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 +1420,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 +1936,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; } diff --git a/v2rayN/ServiceLib/Handler/Fmt/BaseFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/BaseFmt.cs index b620cfe9..3f07548f 100644 --- a/v2rayN/ServiceLib/Handler/Fmt/BaseFmt.cs +++ b/v2rayN/ServiceLib/Handler/Fmt/BaseFmt.cs @@ -5,6 +5,7 @@ namespace ServiceLib.Handler.Fmt; 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) { @@ -21,6 +22,8 @@ public class BaseFmt protected static int ToUriQuery(ProfileItem item, string? securityDef, ref Dictionary dicQuery) { + var transport = item.GetTransportExtra(); + if (item.StreamSecurity.IsNotEmpty()) { dicQuery.Add("security", item.StreamSecurity); @@ -87,54 +90,65 @@ 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)); } 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 +156,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 +211,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 +255,54 @@ 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"); + transport = transport with + { + KcpHeaderType = GetQueryValue(query, "headerType", Global.None), + KcpSeed = kcpSeed, + }; 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 +310,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; } diff --git a/v2rayN/ServiceLib/Handler/Fmt/ShadowsocksFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/ShadowsocksFmt.cs index 5b30fa46..ab805002 100644 --- a/v2rayN/ServiceLib/Handler/Fmt/ShadowsocksFmt.cs +++ b/v2rayN/ServiceLib/Handler/Fmt/ShadowsocksFmt.cs @@ -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) diff --git a/v2rayN/ServiceLib/Handler/Fmt/VmessFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/VmessFmt.cs index b8760a40..7abe08a8 100644 --- a/v2rayN/ServiceLib/Handler/Fmt/VmessFmt.cs +++ b/v2rayN/ServiceLib/Handler/Fmt/VmessFmt.cs @@ -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); diff --git a/v2rayN/ServiceLib/Manager/AppManager.cs b/v2rayN/ServiceLib/Manager/AppManager.cs index 7310bb4e..34f6b3f1 100644 --- a/v2rayN/ServiceLib/Manager/AppManager.cs +++ b/v2rayN/ServiceLib/Manager/AppManager.cs @@ -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 MigrateProfileExtraSub(List 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(sql); + if (batch is null || batch.Count == 0) + { + break; + } + + var updateProfileItems = new List(); + 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 MigrateProfileExtraV2ToV3Sub(List batch) { var updateProfileItems = new List(); @@ -434,7 +554,7 @@ public sealed class AppManager } } - private async Task MigrateProfileExtraGroup() + private async Task MigrateProfileExtraGroupV2ToV3() { var list = await SQLiteHelper.Instance.TableAsync().ToListAsync(); var groupItems = new ConcurrentDictionary(list.Where(t => !string.IsNullOrEmpty(t.IndexId)).ToDictionary(t => t.IndexId!)); diff --git a/v2rayN/ServiceLib/Manager/CertPemManager.cs b/v2rayN/ServiceLib/Manager/CertPemManager.cs index b1c8d82a..0a58e2de 100644 --- a/v2rayN/ServiceLib/Manager/CertPemManager.cs +++ b/v2rayN/ServiceLib/Manager/CertPemManager.cs @@ -203,7 +203,7 @@ public class CertPemManager /// /// Get certificate in PEM format from a server with CA pinning validation /// - 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 /// /// Get certificate chain in PEM format from a server with CA pinning validation /// - public async Task<(List, string?)> GetCertChainPemAsync(string target, string serverName, int timeout = 4) + public async Task<(List, string?)> GetCertChainPemAsync(string target, string serverName, int timeout = 4, bool allowInsecure = false) { var pemList = new List(); 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 /// 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)) { diff --git a/v2rayN/ServiceLib/Models/ConfigItems.cs b/v2rayN/ServiceLib/Models/ConfigItems.cs index 98b4bae4..784f3c43 100644 --- a/v2rayN/ServiceLib/Models/ConfigItems.cs +++ b/v2rayN/ServiceLib/Models/ConfigItems.cs @@ -52,11 +52,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] @@ -200,7 +198,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] diff --git a/v2rayN/ServiceLib/Models/CoreConfigContext.cs b/v2rayN/ServiceLib/Models/CoreConfigContext.cs index 4aa891e9..8123f19f 100644 --- a/v2rayN/ServiceLib/Models/CoreConfigContext.cs +++ b/v2rayN/ServiceLib/Models/CoreConfigContext.cs @@ -16,10 +16,5 @@ public record CoreConfigContext // TUN Compatibility public bool IsTunEnabled { get; init; } = false; - public HashSet 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 ProtectDomainList { get; init; } = []; } diff --git a/v2rayN/ServiceLib/Models/ProfileItem.cs b/v2rayN/ServiceLib/Models/ProfileItem.cs index 50ac8b90..6fe44a3b 100644 --- a/v2rayN/ServiceLib/Models/ProfileItem.cs +++ b/v2rayN/ServiceLib/Models/ProfileItem.cs @@ -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(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(TransportExtra) ?? new TransportExtraItem(); } - public ProtocolExtraItem GetProtocolExtra() + public void SetTransportExtra(TransportExtraItem transportExtra) { - return _protocolExtraCache ??= JsonUtils.Deserialize(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,7 +183,10 @@ 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; } @@ -181,6 +195,7 @@ public class ProfileItem 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; } diff --git a/v2rayN/ServiceLib/Models/SingboxConfig.cs b/v2rayN/ServiceLib/Models/SingboxConfig.cs index 000097bb..06449224 100644 --- a/v2rayN/ServiceLib/Models/SingboxConfig.cs +++ b/v2rayN/ServiceLib/Models/SingboxConfig.cs @@ -261,14 +261,6 @@ public class Server4Sbox : BaseServer4Sbox // public List? path { get; set; } // hosts public Dictionary>? 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 diff --git a/v2rayN/ServiceLib/Models/TransportExtraItem.cs b/v2rayN/ServiceLib/Models/TransportExtraItem.cs new file mode 100644 index 00000000..7ffcc9f5 --- /dev/null +++ b/v2rayN/ServiceLib/Models/TransportExtraItem.cs @@ -0,0 +1,18 @@ +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; } +} diff --git a/v2rayN/ServiceLib/Models/V2rayConfig.cs b/v2rayN/ServiceLib/Models/V2rayConfig.cs index 1bde2dc2..b6aaa2df 100644 --- a/v2rayN/ServiceLib/Models/V2rayConfig.cs +++ b/v2rayN/ServiceLib/Models/V2rayConfig.cs @@ -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? accounts { get; set; } + + public string? name { get; set; } + + public int? MTU { get; set; } + + public List? gateway { get; set; } + + public List? autoSystemRoutingTable { get; set; } + + public string? autoOutboundsInterface { get; set; } + + // public List? 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? 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,19 @@ 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? noise { get; set; } +} + +public class NoiseMask4Ray +{ + public string? rand { get; set; } + public string? delay { get; set; } } public class QuicParams4Ray @@ -511,6 +533,8 @@ public class AccountsItem4Ray public class Sockopt4Ray { public string? dialerProxy { get; set; } + [JsonPropertyName("interface")] + public string? Interface { get; set; } } public class FragmentItem4Ray diff --git a/v2rayN/ServiceLib/Resx/ResUI.Designer.cs b/v2rayN/ServiceLib/Resx/ResUI.Designer.cs index 547888f2..05851f08 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.Designer.cs +++ b/v2rayN/ServiceLib/Resx/ResUI.Designer.cs @@ -2580,6 +2580,24 @@ namespace ServiceLib.Resx { } } + /// + /// 查找类似 Allow insecure cert fetch (self-signed) 的本地化字符串。 + /// + public static string TbAllowInsecureCertFetch { + get { + return ResourceManager.GetString("TbAllowInsecureCertFetch", resourceCulture); + } + } + + /// + /// 查找类似 Only for fetching self-signed certificates. This may expose you to MITM risks. 的本地化字符串。 + /// + public static string TbAllowInsecureCertFetchTips { + get { + return ResourceManager.GetString("TbAllowInsecureCertFetchTips", resourceCulture); + } + } + /// /// 查找类似 ALPN 的本地化字符串。 /// @@ -2670,6 +2688,15 @@ namespace ServiceLib.Resx { } } + /// + /// 查找类似 Camouflage domain 的本地化字符串。 + /// + public static string TbCamouflageDomain { + get { + return ResourceManager.GetString("TbCamouflageDomain", resourceCulture); + } + } + /// /// 查找类似 Cancel 的本地化字符串。 /// @@ -3087,6 +3114,15 @@ namespace ServiceLib.Resx { } } + /// + /// 查找类似 Host 的本地化字符串。 + /// + public static string TbHost { + get { + return ResourceManager.GetString("TbHost", resourceCulture); + } + } + /// /// 查找类似 ICMP routing policy 的本地化字符串。 /// @@ -3393,15 +3429,6 @@ namespace ServiceLib.Resx { } } - /// - /// 查找类似 Camouflage domain(host) 的本地化字符串。 - /// - public static string TbRequestHost { - get { - return ResourceManager.GetString("TbRequestHost", resourceCulture); - } - } - /// /// 查找类似 Reserved (2,3,4) 的本地化字符串。 /// @@ -3772,7 +3799,7 @@ namespace ServiceLib.Resx { } /// - /// 查找类似 This parameter is valid only for tcp/http, ws, gRPC and xhttp 的本地化字符串。 + /// 查找类似 This parameter is valid only for raw/http, ws, gRPC and xhttp 的本地化字符串。 /// public static string TbSettingsDefUserAgentTips { get { @@ -4681,7 +4708,7 @@ namespace ServiceLib.Resx { } /// - /// 查找类似 *Default value tcp 的本地化字符串。 + /// 查找类似 *Default value raw 的本地化字符串。 /// public static string TipNetwork { get { @@ -4699,7 +4726,16 @@ namespace ServiceLib.Resx { } /// - /// 查找类似 XHTTP Extra raw JSON, format: { XHTTP Object } 的本地化字符串。 + /// 查找类似 XHTTP Extra 的本地化字符串。 + /// + public static string TransportExtra { + get { + return ResourceManager.GetString("TransportExtra", resourceCulture); + } + } + + /// + /// 查找类似 Raw JSON, format: { XHTTP Object } 的本地化字符串。 /// public static string TransportExtraTip { get { @@ -4708,47 +4744,47 @@ namespace ServiceLib.Resx { } /// - /// 查找类似 *tcp camouflage type 的本地化字符串。 + /// 查找类似 raw camouflage type 的本地化字符串。 /// - public static string TransportHeaderTypeTip1 { + public static string TransportHeaderType1 { get { - return ResourceManager.GetString("TransportHeaderTypeTip1", resourceCulture); + return ResourceManager.GetString("TransportHeaderType1", resourceCulture); } } /// - /// 查找类似 *kcp camouflage type 的本地化字符串。 + /// 查找类似 kcp camouflage type 的本地化字符串。 /// - public static string TransportHeaderTypeTip2 { + public static string TransportHeaderType2 { get { - return ResourceManager.GetString("TransportHeaderTypeTip2", resourceCulture); + return ResourceManager.GetString("TransportHeaderType2", resourceCulture); } } /// - /// 查找类似 *QUIC camouflage type 的本地化字符串。 + /// 查找类似 QUIC camouflage type 的本地化字符串。 /// - public static string TransportHeaderTypeTip3 { + public static string TransportHeaderType3 { get { - return ResourceManager.GetString("TransportHeaderTypeTip3", resourceCulture); + return ResourceManager.GetString("TransportHeaderType3", resourceCulture); } } /// - /// 查找类似 *grpc mode 的本地化字符串。 + /// 查找类似 gRPC mode 的本地化字符串。 /// - public static string TransportHeaderTypeTip4 { + public static string TransportHeaderType4 { get { - return ResourceManager.GetString("TransportHeaderTypeTip4", resourceCulture); + return ResourceManager.GetString("TransportHeaderType4", resourceCulture); } } /// - /// 查找类似 *xhttp mode 的本地化字符串。 + /// 查找类似 xhttp mode 的本地化字符串。 /// - public static string TransportHeaderTypeTip5 { + public static string TransportHeaderType5 { get { - return ResourceManager.GetString("TransportHeaderTypeTip5", resourceCulture); + return ResourceManager.GetString("TransportHeaderType5", resourceCulture); } } @@ -4780,7 +4816,7 @@ namespace ServiceLib.Resx { } /// - /// 查找类似 *grpc service name 的本地化字符串。 + /// 查找类似 gRPC service name 的本地化字符串。 /// public static string TransportPathTip4 { get { @@ -4834,7 +4870,7 @@ namespace ServiceLib.Resx { } /// - /// 查找类似 *grpc Authority 的本地化字符串。 + /// 查找类似 gRPC Authority 的本地化字符串。 /// public static string TransportRequestHostTip5 { get { diff --git a/v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx b/v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx index 694c5bd3..0d8f8077 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx @@ -343,7 +343,7 @@ *QUIC key/Kcp seed - *grpc serviceName + gRPC serviceName *هاست http جدا شده با کاما (،) @@ -357,17 +357,17 @@ *QUIC securty - - *tcp camouflage type + + raw camouflage type - - *kcp camouflage type + + kcp camouflage type - - *QUIC camouflage type + + QUIC camouflage type - - *حالت grpc + + حالت grpc TLS @@ -606,9 +606,6 @@ نام مستعار (ملاحظات) - - Camouflage domain(host) - روش رمزگذاری (امنیتی) @@ -619,7 +616,7 @@ TLS - *مقدار پیش فرض tcp + *مقدار پیش فرض raw نوع هسته @@ -937,7 +934,7 @@ User-Agent - This parameter is valid only for tcp/http, ws, gRPC and xhttp + This parameter is valid only for raw/http, ws, gRPC and xhttp FontFamily (نیاز به راه اندازی مجدد) @@ -1102,7 +1099,7 @@ پایان تست... - *grpc Authority + RPC Authority افزودن سرور [HTTP] @@ -1320,11 +1317,11 @@ 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. - - *حالت xhttp + + حالت xhttp - جیسون خام XHTTP Extra, فرمت: { XHTTPObject } + Raw JSON, format: { XHTTP Object } هنگام بستن پنجره در سینی پنهان شوید @@ -1710,4 +1707,19 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if For multi-interface environments, enter the local machine's IPv4 address + + Camouflage domain + + + Host + + + XHTTP Extra + + + Allow insecure cert fetch (self-signed) + + + Only for fetching self-signed certificates. This may expose you to MITM risks. + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.fr.resx b/v2rayN/ServiceLib/Resx/ResUI.fr.resx index 32eacf62..2a9af52d 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.fr.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.fr.resx @@ -343,7 +343,7 @@ *clé de chiffrement QUIC - *nom de service gRPC + nom de service gRPC *hôte http, séparés par des virgules (,) @@ -357,17 +357,17 @@ *méthode de chiffrement QUIC - - *type de camouflage tcp + + type de camouflage raw - - *type de camouflage kcp + + type de camouflage kcp - - *type de camouflage QUIC + + type de camouflage QUIC - - *mode gRPC + + mode gRPC TLS @@ -606,9 +606,6 @@ Alias (remarks) - - Domaine de camouflage (host) - Méthode de chiffrement (security) @@ -619,7 +616,7 @@ Sécurité couche transport (TLS) - *tcp par défaut ; un mauvais choix bloque la connexion + *raw par défaut ; un mauvais choix bloque la connexion Type de Core @@ -937,7 +934,7 @@ Agent utilisateur (User-Agent) - This parameter is valid only for tcp/http, ws, gRPC and xhttp + This parameter is valid only for raw/http, ws, gRPC and xhttp Police actuelle (redémarrage requis) @@ -1099,7 +1096,7 @@ Arrêt du test en cours... - *Autorité gRPC + Autorité gRPC Ajouter [HTTP] @@ -1321,16 +1318,16 @@ Adresse sortante locale (SendThrough) - Pour environnement multi-interfaces, veuillez saisir l’adresse IPv4 de la machine locale. + Pour environnements multi-interfaces, entrez l'adresse IPv4 de la machine locale. Veuillez saisir l’adresse IPv4 correcte de SendThrough. - - *Mode XHTTP + + Mode XHTTP - JSON brut XHTTP Extra, format : { XHTTPObject } + Raw JSON, format: { XHTTP Object } Masquer dans la barre d’état à la fermeture de la fenêtre @@ -1713,7 +1710,19 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if Protection TUN héritée - - Pour environnements multi-interfaces, entrez l’adresse IPv4 de la machine locale. + + Domaine de camouflage - + + Host + + + XHTTP Extra + + + Allow insecure cert fetch (self-signed) + + + Only for fetching self-signed certificates. This may expose you to MITM risks. + + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.hu.resx b/v2rayN/ServiceLib/Resx/ResUI.hu.resx index 69050aae..866a08a9 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.hu.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.hu.resx @@ -343,7 +343,7 @@ *QUIC kulcs/KCP seed - *grpc szolgáltatásnév + gRPC szolgáltatásnév *http host vesszővel elválasztva (,) @@ -357,17 +357,17 @@ *QUIC biztonság - - *tcp álcázási típus + + raw álcázási típus - - *kcp álcázási típus + + kcp álcázási típus - - *QUIC álcázási típus + + QUIC álcázási típus - - *grpc mód + + gRPC mód TLS @@ -606,9 +606,6 @@ Alias (megjegyzések) - - Álcázási tartomány(host) - Titkosítási módszer (biztonság) @@ -619,7 +616,7 @@ TLS - *Alapértelmezett érték tcp + *Alapértelmezett érték raw Core Típus @@ -937,7 +934,7 @@ User-Agent - This parameter is valid only for tcp/http, ws, gRPC and xhttp + This parameter is valid only for raw/http, ws, gRPC and xhttp Betűtípus (újraindítást igényel) @@ -1102,7 +1099,7 @@ Teszt megszakítása... - *grpc Authority + gRPC Authority HTTP konfiguráció hozzáadása @@ -1320,11 +1317,11 @@ 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. - - *xhttp mód + + xhttp mód - XHTTP Extra nyers JSON, formátum: { XHTTP Objektum } + Raw JSON, format: { XHTTP Object } Ablak bezárásakor a tálcára rejtés @@ -1710,4 +1707,19 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if For multi-interface environments, enter the local machine's IPv4 address + + Álcázási tartomány + + + Host + + + XHTTP Extra + + + Allow insecure cert fetch (self-signed) + + + Only for fetching self-signed certificates. This may expose you to MITM risks. + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.resx b/v2rayN/ServiceLib/Resx/ResUI.resx index fd0e89e1..a1c4ebb7 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.resx @@ -343,7 +343,7 @@ *QUIC key/KCP seed - *grpc service name + gRPC service name *http host separated by commas (,) @@ -357,17 +357,17 @@ *QUIC security - - *tcp camouflage type + + raw camouflage type - - *kcp camouflage type + + kcp camouflage type - - *QUIC camouflage type + + QUIC camouflage type - - *grpc mode + + gRPC mode TLS @@ -606,9 +606,6 @@ Alias (remarks) - - Camouflage domain(host) - Encryption method (security) @@ -619,7 +616,7 @@ TLS - *Default value tcp + *Default value raw Core Type @@ -937,7 +934,7 @@ User-Agent - This parameter is valid only for tcp/http, ws, gRPC and xhttp + This parameter is valid only for raw/http, ws, gRPC and xhttp Font family (requires restart) @@ -1102,7 +1099,7 @@ Test terminating... - *grpc Authority + gRPC Authority Add [HTTP] @@ -1329,11 +1326,11 @@ Please fill in the correct IPv4 address for SendThrough. - - *xhttp mode + + xhttp mode - XHTTP Extra raw JSON, format: { XHTTP Object } + Raw JSON, format: { XHTTP Object } Hide to tray when closing the window @@ -1716,4 +1713,19 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if Legacy TUN Protect + + Camouflage domain + + + Host + + + XHTTP Extra + + + Allow insecure cert fetch (self-signed) + + + Only for fetching self-signed certificates. This may expose you to MITM risks. + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.ru.resx b/v2rayN/ServiceLib/Resx/ResUI.ru.resx index a46609c1..7eb2435b 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.ru.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.ru.resx @@ -343,7 +343,7 @@ *QUIC-ключ / KCP-seed - Имя сервиса *gRPC + Имя сервиса gRPC *http-хосты, разделённые запятыми (,) @@ -357,17 +357,17 @@ Безопасность *QUIC - - Тип *TCP-камуфляжа + + Тип raw-камуфляжа - - Тип *KCP-камуфляжа + + Тип KCP-камуфляжа - - Тип *QUIC-камуфляжа + + Тип QUIC-камуфляжа - - Режим *gRPC + + Режим gRPC TLS @@ -606,9 +606,6 @@ Псевдоним (remarks) - - Камуфляжный домен (host) - Метод шифрования (security) @@ -619,7 +616,7 @@ TLS - *По умолчанию TCP + *По-умолчанию raw Ядро @@ -937,7 +934,7 @@ User-Agent - This parameter is valid only for tcp/http, ws, gRPC and xhttp + This parameter is valid only for raw/http, ws, gRPC and xhttp Шрифт (требуется перезапуск) @@ -1102,7 +1099,7 @@ Завершение тестирования... - * gRPC Authority (HTTP/2 псевдозаголовок :authority) + gRPC Authority (HTTP/2 псевдозаголовок :authority) Добавить сервер [HTTP] @@ -1320,11 +1317,11 @@ Пароль sudo будет проверен в терминале. Если из-за ошибки проверки приложение начнёт работать некорректно, перезапустите его. Пароль не сохраняется — его нужно вводить после каждого перезапуска. - - *XHTTP-режим + + XHTTP-режим - Дополнительный сырой JSON для XHTTP, формат: { XHTTP Object } + Raw JSON, format: { XHTTP Object } Сворачивать в трей при закрытии окна @@ -1710,4 +1707,19 @@ For multi-interface environments, enter the local machine's IPv4 address + + Камуфляжный домен + + + Host + + + XHTTP Extra + + + Allow insecure cert fetch (self-signed) + + + Only for fetching self-signed certificates. This may expose you to MITM risks. + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.zh-Hans.resx b/v2rayN/ServiceLib/Resx/ResUI.zh-Hans.resx index d40fccfd..e27df42c 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.zh-Hans.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.zh-Hans.resx @@ -343,7 +343,7 @@ *QUIC 加密密钥 - *grpc serviceName + gRPC serviceName *http host 中间逗号 (,) 分隔 @@ -357,17 +357,17 @@ *QUIC 加密方式 - - *tcp 伪装类型 + + raw 伪装类型 - - *kcp 伪装类型 + + kcp 伪装类型 - - *QUIC 伪装类型 + + QUIC 伪装类型 - - *grpc 模式 + + gRPC 模式 TLS @@ -606,9 +606,6 @@ 别名 (remarks) - - 伪装域名 (host) - 加密方式 (security) @@ -619,7 +616,7 @@ 传输层安全 (TLS) - *默认 tcp,选错会无法连接 + *默认 raw,选错会无法连接 Core 类型 @@ -937,7 +934,7 @@ 用户代理 (User-Agent) - 仅对 tcp/http、ws、gRPC、xhttp 生效 + 仅对 raw/http、ws、gRPC、xhttp 生效 当前字体 (需重启) @@ -1099,7 +1096,7 @@ 测试终止中... - *grpc Authority + gRPC Authority 添加 [HTTP] @@ -1326,11 +1323,11 @@ 请填写正确的 SendThrough IPv4 地址。 - - *XHTTP 模式 + + XHTTP 模式 - XHTTP Extra 原始 JSON,格式: { XHTTPObject } + 原始 JSON,格式: { XHTTPObject } 关闭窗口时隐藏至托盘 @@ -1713,4 +1710,19 @@ 旧版 TUN 保护 + + 伪装域名 + + + Host + + + XHTTP Extra + + + 允许不安全获取证书(自签名) + + + 仅用于抓取自签证书,存在中间人风险。 + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.zh-Hant.resx b/v2rayN/ServiceLib/Resx/ResUI.zh-Hant.resx index 2b9b9458..d06d28dc 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.zh-Hant.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.zh-Hant.resx @@ -343,7 +343,7 @@ *QUIC 加密金鑰 - *grpc serviceName + gRPC serviceName *http host 中間逗號 (,) 分隔 @@ -357,17 +357,17 @@ *QUIC 加密方式 - - *TCP 偽裝類型 + + raw 偽裝類型 - - *KCP 偽裝類型 + + KCP 偽裝類型 - - *QUIC 偽裝類型 + + QUIC 偽裝類型 - - *GRPC 模式 + + gRPC 模式 TLS @@ -606,9 +606,6 @@ 別名 (remarks) - - 偽裝域名 (host) - 加密方式 (security) @@ -619,7 +616,7 @@ 傳輸層安全性 (TLS) - *預設 TCP,選錯會無法連線 + *預設 raw,選錯會無法連線 Core 類型 @@ -937,7 +934,7 @@ 使用者代理 (User-Agent) - 僅對 TCP/HTTP、WS、gRPC、XHTTP 生效 + 僅對 raw/HTTP、WS、gRPC、XHTTP 生效 目前字型 (需重啟) @@ -1099,7 +1096,7 @@ 測試終止中... - *grpc Authority + gRPC Authority 新增 [HTTP] 節點 @@ -1317,11 +1314,11 @@ 密碼將調用命令行校驗,如果因為校驗錯誤導致無法正常運行時,請重啟本應用。密碼不會存儲,每次重啟後都需要再次輸入。 - - *xhttp 模式 + + xhttp 模式 - XHTTP Extra 原始 JSON,格式: { XHTTPObject } + 原始 JSON,格式: { XHTTPObject } 關閉視窗時隱藏至托盤 @@ -1707,4 +1704,19 @@ For multi-interface environments, enter the local machine's IPv4 address + + 偽裝域名 + + + Host + + + XHTTP Extra + + + 允許不安全獲取證書(自簽名) + + + 僅用於抓取自簽證書,存在中間人風險。 + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Sample/SampleTunInbound b/v2rayN/ServiceLib/Sample/SampleTunInbound new file mode 100644 index 00000000..95cefbc1 --- /dev/null +++ b/v2rayN/ServiceLib/Sample/SampleTunInbound @@ -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" + ] + } +} \ No newline at end of file diff --git a/v2rayN/ServiceLib/Sample/SampleTunRules b/v2rayN/ServiceLib/Sample/SampleTunRules new file mode 100644 index 00000000..ca6eb051 --- /dev/null +++ b/v2rayN/ServiceLib/Sample/SampleTunRules @@ -0,0 +1,14 @@ +[ + { + "network": "udp", + "port": "135,137-139,5353", + "outboundTag": "block" + }, + { + "ip": [ + "224.0.0.0/3", + "ff00::/8" + ], + "outboundTag": "block" + } +] \ No newline at end of file diff --git a/v2rayN/ServiceLib/ServiceLib.csproj b/v2rayN/ServiceLib/ServiceLib.csproj index 8cfbf8ca..169c1080 100644 --- a/v2rayN/ServiceLib/ServiceLib.csproj +++ b/v2rayN/ServiceLib/ServiceLib.csproj @@ -38,6 +38,8 @@ + + diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/CoreConfigSingboxService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/CoreConfigSingboxService.cs index f0a4f0ef..fe00861d 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/CoreConfigSingboxService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/CoreConfigSingboxService.cs @@ -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 { 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) diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxDnsService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxDnsService.cs index f09d3ee9..a0d172ba 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxDnsService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxDnsService.cs @@ -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) diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxOutboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxOutboundService.cs index 34a7f49f..5b35db01 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxOutboundService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxOutboundService.cs @@ -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; diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRoutingService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRoutingService.cs index e220aa21..92ee56a2 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRoutingService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRoutingService.cs @@ -24,7 +24,7 @@ public partial class CoreConfigSingboxService strategy = directDnsStrategy }; - if (_config.TunModeItem.EnableTun) + if (context.IsTunEnabled) { _coreConfig.route.auto_detect_interface = true; diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/CoreConfigV2rayService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/CoreConfigV2rayService.cs index fb8d92a7..6a815d62 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/CoreConfigV2rayService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/CoreConfigV2rayService.cs @@ -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(); @@ -196,6 +194,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; @@ -257,6 +259,11 @@ public partial class CoreConfigV2rayService(CoreConfigContext context) }); _coreConfig.routing.rules.Add(BuildFinalRule()); + + if (_config.CoreBasicItem.EnableFragment) + { + ApplyOutboundFragment(); + } ApplyOutboundSendThrough(); ret.Msg = string.Format(ResUI.SuccessfulConfiguration, ""); @@ -272,139 +279,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(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 } diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayConfigTemplateService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayConfigTemplateService.cs index 6e563f0f..e6bc48cb 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayConfigTemplateService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayConfigTemplateService.cs @@ -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); diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayDnsService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayDnsService.cs index 6b0d335d..7faae5b1 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayDnsService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayDnsService.cs @@ -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 servers = []; - var arrDNS = normalDNS.Split(','); + var arrDNS = customDNS.Split(','); foreach (var str in arrDNS) { servers.Add(str); diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayInboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayInboundService.cs index 8bb7d0a6..985f597f 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayInboundService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayInboundService.cs @@ -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 { 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 + { + 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(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) diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs index b04f777f..b058dfa1 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs @@ -12,6 +12,10 @@ public partial class CoreConfigV2rayService GenObservatory(multipleLoad); GenBalancer(multipleLoad); } + if (context.IsTunEnabled) + { + _coreConfig.outbounds.Add(BuildDnsOutbound()); + } } private List 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,49 @@ 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 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; + 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; @@ -432,23 +448,22 @@ public partial class CoreConfigV2rayService 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 +475,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 +533,25 @@ 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 +618,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 +644,9 @@ public partial class CoreConfigV2rayService pathHttp = string.Join(",".AppendQuotes(), arrPath); } request = request.Replace("$requestPath$", $"{pathHttp.AppendQuotes()}"); - tcpSettings.header.request = JsonUtils.Deserialize(request); + rawSettings.header.request = JsonUtils.Deserialize(request); - streamSettings.tcpSettings = tcpSettings; + streamSettings.rawSettings = rawSettings; } break; } @@ -825,4 +802,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; + } + } } diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayRoutingService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayRoutingService.cs index dd752a68..4f7431fc 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayRoutingService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayRoutingService.cs @@ -6,6 +6,31 @@ public partial class CoreConfigV2rayService { try { + if (context.IsTunEnabled) + { + var tunRules = JsonUtils.Deserialize>(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 lstDnsExe, List lstDirectExe) BuildRoutingDirectExe() + { + var dnsExeSet = new HashSet(StringComparer.OrdinalIgnoreCase); + var directExeSet = new HashSet(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(dnsExeSet); + var lstDirectExe = new List(directExeSet); + + return (lstDnsExe, lstDirectExe); + } } diff --git a/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs b/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs index e5c307c8..3dbea94c 100644 --- a/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs @@ -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,163 @@ 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; } + + 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 FetchCertCmd { get; } public ReactiveCommand FetchCertChainCmd { get; } public ReactiveCommand SaveCmd { get; } @@ -101,14 +261,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; } @@ -121,13 +288,14 @@ public class AddServerViewModel : MyReactiveObject CertSha = SelectedSource?.CertSha?.ToString() ?? string.Empty; var protocolExtra = SelectedSource?.GetProtocolExtra(); + var transport = SelectedSource?.GetTransportExtra(); 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; + 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; @@ -139,6 +307,17 @@ public class AddServerViewModel : MyReactiveObject 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; } private async Task SaveServerAsync() @@ -185,6 +364,25 @@ 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(), + }; + SelectedSource.SetProtocolExtra(SelectedSource.GetProtocolExtra() with { Ports = Ports.NullIfEmpty(), @@ -206,6 +404,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 +460,7 @@ public class AddServerViewModel : MyReactiveObject var serverName = SelectedSource.Sni; if (serverName.IsNullOrEmpty()) { - serverName = SelectedSource.RequestHost; + serverName = GetCurrentTransportHost(); } if (serverName.IsNullOrEmpty()) { @@ -272,7 +471,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 +485,7 @@ public class AddServerViewModel : MyReactiveObject var serverName = SelectedSource.Sni; if (serverName.IsNullOrEmpty()) { - serverName = SelectedSource.RequestHost; + serverName = GetCurrentTransportHost(); } if (serverName.IsNullOrEmpty()) { @@ -297,8 +496,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, + }; + } } diff --git a/v2rayN/ServiceLib/ViewModels/DNSSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/DNSSettingViewModel.cs index 00178d17..13571616 100644 --- a/v2rayN/ServiceLib/ViewModels/DNSSettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/DNSSettingViewModel.cs @@ -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(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(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(NormalDNS2Compatible)); + item2.TunDNS = JsonUtils.Serialize(JsonUtils.Deserialize(TunDNS2Compatible)); await ConfigHandler.SaveDNSItems(_config, item2); await ConfigHandler.SaveConfig(_config); diff --git a/v2rayN/ServiceLib/ViewModels/FullConfigTemplateViewModel.cs b/v2rayN/ServiceLib/ViewModels/FullConfigTemplateViewModel.cs index 3a50b52e..78cd10a2 100644 --- a/v2rayN/ServiceLib/ViewModels/FullConfigTemplateViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/FullConfigTemplateViewModel.cs @@ -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 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 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; diff --git a/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs b/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs index 36027b79..53ad06c8 100644 --- a/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs @@ -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); }); diff --git a/v2rayN/ServiceLib/ViewModels/ProfilesSelectViewModel.cs b/v2rayN/ServiceLib/ViewModels/ProfilesSelectViewModel.cs index b3810b52..a4d9b298 100644 --- a/v2rayN/ServiceLib/ViewModels/ProfilesSelectViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/ProfilesSelectViewModel.cs @@ -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?> GetProfileItemsEx(string subid, string filter) diff --git a/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs b/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs index 7a127fa7..f44f52e3 100644 --- a/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs @@ -393,7 +393,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?> GetProfileItemsEx(string subid, string filter) diff --git a/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs index 8f62f2d0..2075bb1e 100644 --- a/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs @@ -22,7 +22,6 @@ public class RoutingSettingViewModel : MyReactiveObject public ReactiveCommand RoutingAdvancedSetDefaultCmd { get; } public ReactiveCommand RoutingAdvancedImportRulesCmd { get; } - public ReactiveCommand 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() + /// + /// Save DomainStrategy settings + /// + 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 diff --git a/v2rayN/v2rayN.Desktop/Common/ButtonResult.cs b/v2rayN/v2rayN.Desktop/Common/ButtonResult.cs new file mode 100644 index 00000000..6f939d8d --- /dev/null +++ b/v2rayN/v2rayN.Desktop/Common/ButtonResult.cs @@ -0,0 +1,8 @@ +namespace v2rayN.Desktop.Common; + +public enum ButtonResult +{ + None = 0, + Yes = 1, + No = 2 +} diff --git a/v2rayN/v2rayN.Desktop/Common/UI.cs b/v2rayN/v2rayN.Desktop/Common/UI.cs index c17d8947..990e3c68 100644 --- a/v2rayN/v2rayN.Desktop/Common/UI.cs +++ b/v2rayN/v2rayN.Desktop/Common/UI.cs @@ -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 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(owner); + return result == ButtonResult.Yes ? ButtonResult.Yes : ButtonResult.No; } public static async Task OpenFileDialog(Window owner, FilePickerFileType? filter) diff --git a/v2rayN/v2rayN.Desktop/GlobalUsings.cs b/v2rayN/v2rayN.Desktop/GlobalUsings.cs index e7499b01..5b0b2158 100644 --- a/v2rayN/v2rayN.Desktop/GlobalUsings.cs +++ b/v2rayN/v2rayN.Desktop/GlobalUsings.cs @@ -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; diff --git a/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml b/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml index 4dc378b4..f29afb7f 100644 --- a/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml +++ b/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml @@ -690,128 +690,279 @@ + RowDefinitions="Auto,Auto,Auto"> - - - - - - + + + + - - - + + + + + + - - - + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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,6 +25,16 @@ public partial class AddServerWindow : WindowBase cmbCoreType.ItemsSource = Global.CoreTypes.AppendEmpty(); cmbNetwork.ItemsSource = Global.Networks; + + cmbHeaderTypeRaw.ItemsSource = new List { Global.None, Global.RawHeaderHttp }; + + var kcpHeaderTypes = new List { Global.None }; + kcpHeaderTypes.AddRange(Global.KcpHeaderTypes); + cmbHeaderTypeKcp.ItemsSource = kcpHeaderTypes; + + cmbHeaderTypeXhttp.ItemsSource = Global.XhttpMode; + cmbHeaderTypeGrpc.ItemsSource = new List { Global.GrpcGunMode, Global.GrpcMultiMode }; + cmbFingerprint.ItemsSource = Global.Fingerprints; cmbFingerprint2.ItemsSource = Global.Fingerprints; cmbAllowInsecure.ItemsSource = Global.AllowInsecure; @@ -201,10 +212,27 @@ public partial class AddServerWindow : WindowBase 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.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,6 +242,8 @@ public partial class AddServerWindow : WindowBase 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); @@ -253,8 +283,12 @@ public partial class AddServerWindow : WindowBase 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 +317,60 @@ public partial class AddServerWindow : WindowBase txtId5.Text = Utils.GetGuid(); } - private void SetHeaderType() + private void SetTransportGridVisibility() { - var lstHeaderType = new List(); - - 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; + gridTransportXhttp.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; - 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; } } diff --git a/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml b/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml index 3335785b..1b2a691c 100644 --- a/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml +++ b/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml @@ -395,13 +395,26 @@ - - - + + + + + + + + + + + + diff --git a/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml.cs index dd39e229..e2ea1201 100644 --- a/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml.cs @@ -52,6 +52,7 @@ public partial class DNSSettingWindow : WindowBase 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); diff --git a/v2rayN/v2rayN.Desktop/Views/FullConfigTemplateWindow.axaml b/v2rayN/v2rayN.Desktop/Views/FullConfigTemplateWindow.axaml index 1a2b482c..7ff49937 100644 --- a/v2rayN/v2rayN.Desktop/Views/FullConfigTemplateWindow.axaml +++ b/v2rayN/v2rayN.Desktop/Views/FullConfigTemplateWindow.axaml @@ -90,13 +90,26 @@ - - - + + + + + + + + + + + + diff --git a/v2rayN/v2rayN.Desktop/Views/FullConfigTemplateWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/FullConfigTemplateWindow.axaml.cs index bfe0c2c5..6ea6e994 100644 --- a/v2rayN/v2rayN.Desktop/Views/FullConfigTemplateWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/FullConfigTemplateWindow.axaml.cs @@ -12,13 +12,14 @@ public partial class FullConfigTemplateWindow : WindowBase 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); diff --git a/v2rayN/v2rayN.Desktop/Views/MessageBoxDialog.axaml b/v2rayN/v2rayN.Desktop/Views/MessageBoxDialog.axaml new file mode 100644 index 00000000..dae11854 --- /dev/null +++ b/v2rayN/v2rayN.Desktop/Views/MessageBoxDialog.axaml @@ -0,0 +1,53 @@ + + + + + + + + +