From 494b35c1f7016cfbf7f8116deb6175c072becdf1 Mon Sep 17 00:00:00 2001 From: DHR60 Date: Thu, 16 Apr 2026 11:17:44 +0000 Subject: [PATCH 01/21] Add xray tun support (#9063) * Add xray tun support * Revert mtu list --- .../CoreConfigV2rayServiceTests.cs | 10 +- v2rayN/ServiceLib/Common/WindowsUtils.cs | 26 ++-- v2rayN/ServiceLib/Global.cs | 3 + .../Builder/CoreConfigContextBuilder.cs | 57 ++----- v2rayN/ServiceLib/Handler/ConfigHandler.cs | 4 +- v2rayN/ServiceLib/Models/CoreConfigContext.cs | 7 +- v2rayN/ServiceLib/Models/V2rayConfig.cs | 18 ++- v2rayN/ServiceLib/Sample/SampleTunInbound | 24 +++ v2rayN/ServiceLib/Sample/SampleTunRules | 14 ++ v2rayN/ServiceLib/ServiceLib.csproj | 2 + .../Singbox/CoreConfigSingboxService.cs | 53 ------- .../Singbox/SingboxRoutingService.cs | 2 +- .../V2ray/CoreConfigV2rayService.cs | 141 ------------------ .../CoreConfig/V2ray/V2rayInboundService.cs | 61 +++++--- .../CoreConfig/V2ray/V2rayOutboundService.cs | 10 ++ .../CoreConfig/V2ray/V2rayRoutingService.cs | 58 +++++++ .../ViewModels/MainWindowViewModel.cs | 2 +- 17 files changed, 208 insertions(+), 284 deletions(-) create mode 100644 v2rayN/ServiceLib/Sample/SampleTunInbound create mode 100644 v2rayN/ServiceLib/Sample/SampleTunRules diff --git a/v2rayN/ServiceLib.Tests/CoreConfigV2rayServiceTests.cs b/v2rayN/ServiceLib.Tests/CoreConfigV2rayServiceTests.cs index 52f5d58a..7d9ecdcb 100644 --- a/v2rayN/ServiceLib.Tests/CoreConfigV2rayServiceTests.cs +++ b/v2rayN/ServiceLib.Tests/CoreConfigV2rayServiceTests.cs @@ -75,9 +75,7 @@ public class CoreConfigV2rayServiceTests var service = new CoreConfigV2rayService(CreateContext( node, config, - isTunEnabled: true, - tunProtectSsPort: 10811, - proxyRelaySsPort: 10812)); + isTunEnabled: true)); var result = service.GenerateClientConfigContent(); @@ -91,9 +89,7 @@ public class CoreConfigV2rayServiceTests ProfileItem node, Config? config = null, Dictionary? allProxiesMap = null, - bool isTunEnabled = false, - int tunProtectSsPort = 0, - int proxyRelaySsPort = 0) + bool isTunEnabled = false) { return new CoreConfigContext { @@ -103,8 +99,6 @@ public class CoreConfigV2rayServiceTests AllProxiesMap = allProxiesMap ?? new(), SimpleDnsItem = new SimpleDNSItem(), IsTunEnabled = isTunEnabled, - TunProtectSocksPort = tunProtectSsPort, - ProxyRelaySocksPort = proxyRelaySsPort, }; } diff --git a/v2rayN/ServiceLib/Common/WindowsUtils.cs b/v2rayN/ServiceLib/Common/WindowsUtils.cs index 2215a3e3..d801c343 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 { "singbox_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($"wintun{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/Global.cs b/v2rayN/ServiceLib/Global.cs index d6792115..5df4e1fc 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"; @@ -48,6 +50,7 @@ public class Global 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"; diff --git a/v2rayN/ServiceLib/Handler/Builder/CoreConfigContextBuilder.cs b/v2rayN/ServiceLib/Handler/Builder/CoreConfigContextBuilder.cs index 5017250e..d0db8bea 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; } /// diff --git a/v2rayN/ServiceLib/Handler/ConfigHandler.cs b/v2rayN/ServiceLib/Handler/ConfigHandler.cs index 78229e6c..9fbc5613 100644 --- a/v2rayN/ServiceLib/Handler/ConfigHandler.cs +++ b/v2rayN/ServiceLib/Handler/ConfigHandler.cs @@ -1417,10 +1417,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() { 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/V2rayConfig.cs b/v2rayN/ServiceLib/Models/V2rayConfig.cs index 1bde2dc2..4f73e65e 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 @@ -511,6 +523,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/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/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..d1cf14d7 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()) { @@ -272,139 +265,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/V2rayInboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayInboundService.cs index 7ae12c7c..4831b5bc 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..f5e8cd1e 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) @@ -825,4 +829,10 @@ public partial class CoreConfigV2rayService } } } + + private static Outbounds4Ray BuildDnsOutbound() + { + var outbound = new Outbounds4Ray { tag = Global.DnsOutboundTag, protocol = "dns", }; + return outbound; + } } 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/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); }); From 9f0ef36cc09bb5c3e2b4f36b4f4ae71522ccb289 Mon Sep 17 00:00:00 2001 From: DHR60 Date: Thu, 16 Apr 2026 12:21:10 +0000 Subject: [PATCH 02/21] Refactor Transport (#9004) * Refactor transport * Rename tcp to raw * Fix * Fix Fix raw http ui Fill xhttp default mode Fix share uri Remove RawHost Fix singbox tcp http path Fix vmess share uri * Tidy Resx * Fix * Rename TransportExtra to TransportExtraItem --------- Co-authored-by: 2dust <31833384+2dust@users.noreply.github.com> --- v2rayN/GlobalHotKeys | 2 +- v2rayN/ServiceLib/Enums/ETransport.cs | 2 +- v2rayN/ServiceLib/Global.cs | 20 +- .../Builder/CoreConfigContextBuilder.cs | 5 +- .../Handler/Builder/NodeValidator.cs | 9 +- v2rayN/ServiceLib/Handler/ConfigHandler.cs | 34 +- v2rayN/ServiceLib/Handler/Fmt/BaseFmt.cs | 174 ++++--- .../ServiceLib/Handler/Fmt/ShadowsocksFmt.cs | 33 +- v2rayN/ServiceLib/Handler/Fmt/VmessFmt.cs | 65 ++- v2rayN/ServiceLib/Manager/AppManager.cs | 128 ++++- v2rayN/ServiceLib/Models/ProfileItem.cs | 31 +- .../ServiceLib/Models/TransportExtraItem.cs | 18 + v2rayN/ServiceLib/Models/V2rayConfig.cs | 4 +- v2rayN/ServiceLib/Resx/ResUI.Designer.cs | 65 +-- v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx | 37 +- v2rayN/ServiceLib/Resx/ResUI.fr.resx | 37 +- v2rayN/ServiceLib/Resx/ResUI.hu.resx | 37 +- v2rayN/ServiceLib/Resx/ResUI.resx | 37 +- v2rayN/ServiceLib/Resx/ResUI.ru.resx | 37 +- v2rayN/ServiceLib/Resx/ResUI.zh-Hans.resx | 37 +- v2rayN/ServiceLib/Resx/ResUI.zh-Hant.resx | 37 +- .../Singbox/SingboxOutboundService.cs | 64 +-- .../CoreConfig/V2ray/V2rayOutboundService.cs | 115 ++--- .../ViewModels/AddServerViewModel.cs | 217 +++++++- .../Views/AddServerWindow.axaml | 371 ++++++++++---- .../Views/AddServerWindow.axaml.cs | 158 +++--- v2rayN/v2rayN/Views/AddServerWindow.xaml | 469 +++++++++++++----- v2rayN/v2rayN/Views/AddServerWindow.xaml.cs | 174 ++++--- 28 files changed, 1612 insertions(+), 805 deletions(-) create mode 100644 v2rayN/ServiceLib/Models/TransportExtraItem.cs diff --git a/v2rayN/GlobalHotKeys b/v2rayN/GlobalHotKeys index 50f615b6..ffb2850d 160000 --- a/v2rayN/GlobalHotKeys +++ b/v2rayN/GlobalHotKeys @@ -1 +1 @@ -Subproject commit 50f615b671ff8d4a6a850aed19da5f94f58b5d96 +Subproject commit ffb2850df0991495d0918e13cc5701737f26175a 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 5df4e1fc..267ec60a 100644 --- a/v2rayN/ServiceLib/Global.cs +++ b/v2rayN/ServiceLib/Global.cs @@ -44,9 +44,11 @@ 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"; @@ -185,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" }, @@ -296,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 = diff --git a/v2rayN/ServiceLib/Handler/Builder/CoreConfigContextBuilder.cs b/v2rayN/ServiceLib/Handler/Builder/CoreConfigContextBuilder.cs index d0db8bea..886a1971 100644 --- a/v2rayN/ServiceLib/Handler/Builder/CoreConfigContextBuilder.cs +++ b/v2rayN/ServiceLib/Handler/Builder/CoreConfigContextBuilder.cs @@ -313,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 9fbc5613..eab544da 100644 --- a/v2rayN/ServiceLib/Handler/ConfigHandler.cs +++ b/v2rayN/ServiceLib/Handler/ConfigHandler.cs @@ -236,9 +236,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 +247,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 +254,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 +294,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 +745,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 +992,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 +1060,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 +1128,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 +1140,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) 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/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/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 4f73e65e..a5ac2e24 100644 --- a/v2rayN/ServiceLib/Models/V2rayConfig.cs +++ b/v2rayN/ServiceLib/Models/V2rayConfig.cs @@ -331,7 +331,7 @@ public class StreamSettings4Ray public TlsSettings4Ray? tlsSettings { get; set; } - public TcpSettings4Ray? tcpSettings { get; set; } + public RawSettings4Ray? rawSettings { get; set; } public KcpSettings4Ray? kcpSettings { get; set; } @@ -385,7 +385,7 @@ public class CertificateSettings4Ray public string? usage { get; set; } } -public class TcpSettings4Ray +public class RawSettings4Ray { public Header4Ray header { get; set; } } diff --git a/v2rayN/ServiceLib/Resx/ResUI.Designer.cs b/v2rayN/ServiceLib/Resx/ResUI.Designer.cs index d323889a..234cdef3 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.Designer.cs +++ b/v2rayN/ServiceLib/Resx/ResUI.Designer.cs @@ -2670,6 +2670,15 @@ namespace ServiceLib.Resx { } } + /// + /// 查找类似 Camouflage domain 的本地化字符串。 + /// + public static string TbCamouflageDomain { + get { + return ResourceManager.GetString("TbCamouflageDomain", resourceCulture); + } + } + /// /// 查找类似 Cancel 的本地化字符串。 /// @@ -3087,6 +3096,15 @@ namespace ServiceLib.Resx { } } + /// + /// 查找类似 Host 的本地化字符串。 + /// + public static string TbHost { + get { + return ResourceManager.GetString("TbHost", resourceCulture); + } + } + /// /// 查找类似 ICMP routing policy 的本地化字符串。 /// @@ -3393,15 +3411,6 @@ namespace ServiceLib.Resx { } } - /// - /// 查找类似 Camouflage domain(host) 的本地化字符串。 - /// - public static string TbRequestHost { - get { - return ResourceManager.GetString("TbRequestHost", resourceCulture); - } - } - /// /// 查找类似 Reserved (2,3,4) 的本地化字符串。 /// @@ -3772,7 +3781,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 { @@ -4654,7 +4663,7 @@ namespace ServiceLib.Resx { } /// - /// 查找类似 *Default value tcp 的本地化字符串。 + /// 查找类似 *Default value raw 的本地化字符串。 /// public static string TipNetwork { get { @@ -4681,47 +4690,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); } } @@ -4753,7 +4762,7 @@ namespace ServiceLib.Resx { } /// - /// 查找类似 *grpc service name 的本地化字符串。 + /// 查找类似 gRPC service name 的本地化字符串。 /// public static string TransportPathTip4 { get { @@ -4807,7 +4816,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 eda45653..08aaf893 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,8 +1317,8 @@ 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 } @@ -1701,4 +1698,10 @@ 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 + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.fr.resx b/v2rayN/ServiceLib/Resx/ResUI.fr.resx index dd4ac94b..907eb02c 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] @@ -1326,8 +1323,8 @@ Veuillez saisir l’adresse IPv4 correcte de SendThrough. - - *Mode XHTTP + + Mode XHTTP JSON brut XHTTP Extra, format : { XHTTPObject } @@ -1707,4 +1704,10 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if Pour environnements multi-interfaces, entrez l’adresse IPv4 de la machine locale. + + Domaine de camouflage + + + Host + diff --git a/v2rayN/ServiceLib/Resx/ResUI.hu.resx b/v2rayN/ServiceLib/Resx/ResUI.hu.resx index 4437eafa..f761cca9 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,8 +1317,8 @@ 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 } @@ -1701,4 +1698,10 @@ 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 + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.resx b/v2rayN/ServiceLib/Resx/ResUI.resx index 6bbf3f72..d30c3f31 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,8 +1326,8 @@ Please fill in the correct IPv4 address for SendThrough. - - *xhttp mode + + xhttp mode XHTTP Extra raw JSON, format: { XHTTP Object } @@ -1707,4 +1704,10 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if Legacy TUN Protect + + Camouflage domain + + + Host + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.ru.resx b/v2rayN/ServiceLib/Resx/ResUI.ru.resx index c777c4d9..1521e67c 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,8 +1317,8 @@ Пароль sudo будет проверен в терминале. Если из-за ошибки проверки приложение начнёт работать некорректно, перезапустите его. Пароль не сохраняется — его нужно вводить после каждого перезапуска. - - *XHTTP-режим + + XHTTP-режим Дополнительный сырой JSON для XHTTP, формат: { XHTTP Object } @@ -1701,4 +1698,10 @@ For multi-interface environments, enter the local machine's IPv4 address + + Камуфляжный домен + + + Host + \ 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 b26059ad..379fb4ba 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,8 +1323,8 @@ 请填写正确的 SendThrough IPv4 地址。 - - *XHTTP 模式 + + XHTTP 模式 XHTTP Extra 原始 JSON,格式: { XHTTPObject } @@ -1704,4 +1701,10 @@ 旧版 TUN 保护 + + 伪装域名 + + + Host + \ 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 bacf2f11..a903d168 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,8 +1314,8 @@ 密碼將調用命令行校驗,如果因為校驗錯誤導致無法正常運行時,請重啟本應用。密碼不會存儲,每次重啟後都需要再次輸入。 - - *xhttp 模式 + + xhttp 模式 XHTTP Extra 原始 JSON,格式: { XHTTPObject } @@ -1698,4 +1695,10 @@ For multi-interface environments, enter the local machine's IPv4 address + + 偽裝域名 + + + Host + \ No newline at end of file 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/V2ray/V2rayOutboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs index f5e8cd1e..a0d4099f 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs @@ -353,8 +353,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; @@ -440,19 +481,19 @@ public partial class CoreConfigV2rayService kcpSettings.readBufferSize = _config.KcpItem.ReadBufferSize; kcpSettings.writeBufferSize = _config.KcpItem.WriteBufferSize; 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 { @@ -464,7 +505,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; @@ -522,63 +563,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, @@ -645,20 +648,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()}"); @@ -671,9 +674,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; } diff --git a/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs b/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs index e5c307c8..9fbb6125 100644 --- a/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs @@ -73,6 +73,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 +258,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,6 +285,7 @@ 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; @@ -139,6 +304,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 +361,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 +401,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 +457,7 @@ public class AddServerViewModel : MyReactiveObject var serverName = SelectedSource.Sni; if (serverName.IsNullOrEmpty()) { - serverName = SelectedSource.RequestHost; + serverName = GetCurrentTransportHost(); } if (serverName.IsNullOrEmpty()) { @@ -286,7 +482,7 @@ public class AddServerViewModel : MyReactiveObject var serverName = SelectedSource.Sni; if (serverName.IsNullOrEmpty()) { - serverName = SelectedSource.RequestHost; + serverName = GetCurrentTransportHost(); } if (serverName.IsNullOrEmpty()) { @@ -301,4 +497,17 @@ public class AddServerViewModel : MyReactiveObject 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/v2rayN.Desktop/Views/AddServerWindow.axaml b/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml index 4dc378b4..1d2bb899 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); @@ -253,8 +281,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 +315,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/Views/AddServerWindow.xaml b/v2rayN/v2rayN/Views/AddServerWindow.xaml index 827410c3..25a1234b 100644 --- a/v2rayN/v2rayN/Views/AddServerWindow.xaml +++ b/v2rayN/v2rayN/Views/AddServerWindow.xaml @@ -150,7 +150,7 @@ + Visibility="Collapsed"> @@ -234,7 +234,7 @@ + Visibility="Collapsed"> @@ -308,7 +308,7 @@ + Visibility="Collapsed"> @@ -353,7 +353,7 @@ + Visibility="Collapsed"> @@ -437,7 +437,7 @@ + Visibility="Collapsed"> @@ -497,7 +497,7 @@ + Visibility="Collapsed"> @@ -610,7 +610,7 @@ + Visibility="Collapsed"> @@ -670,7 +670,7 @@ + Visibility="Collapsed"> @@ -767,7 +767,7 @@ + Visibility="Collapsed"> @@ -796,7 +796,7 @@ + Visibility="Collapsed"> @@ -907,143 +907,356 @@ - - - - - - - - - - - - - - - - + + + + + + + + + - - + + + + + + + + + + + + - + + + + + + + + + + + + + - - - - + Style="{StaticResource ToolbarTextBlock}" + Text="{x:Static resx:ResUI.TbCamouflageDomain}" /> + + + + + - - - + + + + + + + + + + + + + + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1117,7 +1330,7 @@ + Visibility="Collapsed"> @@ -1306,7 +1519,7 @@ + Visibility="Collapsed"> diff --git a/v2rayN/v2rayN/Views/AddServerWindow.xaml.cs b/v2rayN/v2rayN/Views/AddServerWindow.xaml.cs index cc04b4c8..46f62a70 100644 --- a/v2rayN/v2rayN/Views/AddServerWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/AddServerWindow.xaml.cs @@ -11,6 +11,7 @@ public partial class AddServerWindow Owner = Application.Current.MainWindow; Loaded += Window_Loaded; cmbNetwork.SelectionChanged += CmbNetwork_SelectionChanged; + cmbHeaderTypeRaw.SelectionChanged += CmbHeaderTypeRaw_SelectionChanged; cmbStreamSecurity.SelectionChanged += CmbStreamSecurity_SelectionChanged; btnGUID.Click += btnGUID_Click; btnGUID5.Click += btnGUID_Click; @@ -19,6 +20,20 @@ public partial class AddServerWindow cmbCoreType.ItemsSource = Global.CoreTypes.AppendEmpty(); cmbNetwork.ItemsSource = Global.Networks; + if (ViewModel.SelectedSource.Network.IsNullOrEmpty() || !Global.Networks.Contains(ViewModel.SelectedSource.Network)) + { + ViewModel.SelectedSource.Network = Global.DefaultNetwork; + } + + cmbHeaderTypeRaw.ItemsSource = new List { 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; @@ -114,7 +129,7 @@ public partial class AddServerWindow } cmbStreamSecurity.ItemsSource = lstStreamSecurity; - gridTlsMore.Visibility = Visibility.Hidden; + gridTlsMore.Visibility = Visibility.Collapsed; this.WhenActivated(disposables => { @@ -195,10 +210,27 @@ public partial class AddServerWindow break; } this.Bind(ViewModel, vm => vm.SelectedSource.Network, v => v.cmbNetwork.Text).DisposeWith(disposables); - this.Bind(ViewModel, vm => vm.SelectedSource.HeaderType, v => v.cmbHeaderType.Text).DisposeWith(disposables); - this.Bind(ViewModel, vm => vm.SelectedSource.RequestHost, v => v.txtRequestHost.Text).DisposeWith(disposables); - this.Bind(ViewModel, vm => vm.SelectedSource.Path, v => v.txtPath.Text).DisposeWith(disposables); - this.Bind(ViewModel, vm => vm.SelectedSource.Extra, v => v.txtExtra.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.RawHeaderType, v => v.cmbHeaderTypeRaw.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostRaw.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.Path, v => v.txtPathRaw.Text).DisposeWith(disposables); + + this.Bind(ViewModel, vm => vm.KcpHeaderType, v => v.cmbHeaderTypeKcp.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.KcpSeed, v => v.txtKcpSeed.Text).DisposeWith(disposables); + + this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostWs.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.Path, v => v.txtPathWs.Text).DisposeWith(disposables); + + this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostHttpupgrade.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.Path, v => v.txtPathHttpupgrade.Text).DisposeWith(disposables); + + this.Bind(ViewModel, vm => vm.XhttpMode, v => v.cmbHeaderTypeXhttp.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.Host, v => v.txtRequestHostXhttp.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.Path, v => v.txtPathXhttp.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.XhttpExtra, v => v.txtExtraXhttp.Text).DisposeWith(disposables); + + this.Bind(ViewModel, vm => vm.GrpcMode, v => v.cmbHeaderTypeGrpc.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.GrpcAuthority, v => v.txtRequestHostGrpc.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.GrpcServiceName, v => v.txtPathGrpc.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SelectedSource.StreamSecurity, v => v.cmbStreamSecurity.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SelectedSource.Sni, v => v.txtSNI.Text).DisposeWith(disposables); @@ -249,8 +281,12 @@ public partial class AddServerWindow private void CmbNetwork_SelectionChanged(object sender, SelectionChangedEventArgs e) { - SetHeaderType(); - SetTips(); + SetTransportGridVisibility(); + } + + private void CmbHeaderTypeRaw_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + SetRawHttpFieldsVisibility(); } private void CmbStreamSecurity_SelectionChanged(object sender, SelectionChangedEventArgs e) @@ -259,17 +295,17 @@ public partial class AddServerWindow if (security == Global.StreamSecurityReality) { gridRealityMore.Visibility = Visibility.Visible; - gridTlsMore.Visibility = Visibility.Hidden; + gridTlsMore.Visibility = Visibility.Collapsed; } else if (security == Global.StreamSecurity) { - gridRealityMore.Visibility = Visibility.Hidden; + gridRealityMore.Visibility = Visibility.Collapsed; gridTlsMore.Visibility = Visibility.Visible; } else { - gridRealityMore.Visibility = Visibility.Hidden; - gridTlsMore.Visibility = Visibility.Hidden; + gridRealityMore.Visibility = Visibility.Collapsed; + gridTlsMore.Visibility = Visibility.Collapsed; } } @@ -279,102 +315,62 @@ public partial class AddServerWindow 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.Visibility = Visibility.Visible; - popExtra.Visibility = Visibility.Hidden; - tipRequestHost.Text = - tipPath.Text = - tipHeaderType.Text = string.Empty; + + gridTransportRaw.Visibility = Visibility.Collapsed; + gridTransportKcp.Visibility = Visibility.Collapsed; + gridTransportWs.Visibility = Visibility.Collapsed; + gridTransportHttpupgrade.Visibility = Visibility.Collapsed; + gridTransportXhttp.Visibility = Visibility.Collapsed; + gridTransportGrpc.Visibility = Visibility.Collapsed; switch (network) { - case nameof(ETransport.tcp): - tipRequestHost.Text = ResUI.TransportRequestHostTip1; - tipHeaderType.Text = ResUI.TransportHeaderTypeTip1; + case nameof(ETransport.raw): + gridTransportRaw.Visibility = Visibility.Visible; break; - case nameof(ETransport.kcp): - tipHeaderType.Text = ResUI.TransportHeaderTypeTip2; - tipPath.Text = ResUI.TransportPathTip5; + gridTransportKcp.Visibility = Visibility.Visible; break; - case nameof(ETransport.ws): + gridTransportWs.Visibility = Visibility.Visible; + break; case nameof(ETransport.httpupgrade): - tipRequestHost.Text = ResUI.TransportRequestHostTip2; - tipPath.Text = ResUI.TransportPathTip1; + gridTransportHttpupgrade.Visibility = Visibility.Visible; break; - case nameof(ETransport.xhttp): - tipRequestHost.Text = ResUI.TransportRequestHostTip2; - tipPath.Text = ResUI.TransportPathTip1; - tipHeaderType.Text = ResUI.TransportHeaderTypeTip5; - labHeaderType.Visibility = Visibility.Hidden; - popExtra.Visibility = Visibility.Visible; + gridTransportXhttp.Visibility = Visibility.Visible; break; - - case nameof(ETransport.h2): - tipRequestHost.Text = ResUI.TransportRequestHostTip3; - tipPath.Text = ResUI.TransportPathTip2; - break; - - case nameof(ETransport.quic): - tipRequestHost.Text = ResUI.TransportRequestHostTip4; - tipPath.Text = ResUI.TransportPathTip3; - tipHeaderType.Text = ResUI.TransportHeaderTypeTip3; - break; - case nameof(ETransport.grpc): - tipRequestHost.Text = ResUI.TransportRequestHostTip5; - tipPath.Text = ResUI.TransportPathTip4; - tipHeaderType.Text = ResUI.TransportHeaderTypeTip4; - labHeaderType.Visibility = Visibility.Hidden; + gridTransportGrpc.Visibility = Visibility.Visible; + break; + default: + gridTransportRaw.Visibility = Visibility.Visible; break; } + + SetRawHttpFieldsVisibility(); + } + + private void SetRawHttpFieldsVisibility() + { + var network = cmbNetwork.SelectedItem?.ToString(); + if (network.IsNullOrEmpty()) + { + network = Global.DefaultNetwork; + } + + var rawHeaderType = cmbHeaderTypeRaw.SelectedItem?.ToString(); + var showRawHttpFields = network == nameof(ETransport.raw) + && rawHeaderType == Global.RawHeaderHttp; + gridTransportRawHttp.Visibility = showRawHttpFields + ? Visibility.Visible + : Visibility.Collapsed; } } From 5305b0843bcdbacabd889a9bf164cc6d83a85f98 Mon Sep 17 00:00:00 2001 From: DHR60 Date: Fri, 17 Apr 2026 05:36:42 +0000 Subject: [PATCH 03/21] Fix (#9128) --- v2rayN/GlobalHotKeys | 2 +- v2rayN/ServiceLib/Common/WindowsUtils.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/v2rayN/GlobalHotKeys b/v2rayN/GlobalHotKeys index ffb2850d..50f615b6 160000 --- a/v2rayN/GlobalHotKeys +++ b/v2rayN/GlobalHotKeys @@ -1 +1 @@ -Subproject commit ffb2850df0991495d0918e13cc5701737f26175a +Subproject commit 50f615b671ff8d4a6a850aed19da5f94f58b5d96 diff --git a/v2rayN/ServiceLib/Common/WindowsUtils.cs b/v2rayN/ServiceLib/Common/WindowsUtils.cs index d801c343..6cd47f0a 100644 --- a/v2rayN/ServiceLib/Common/WindowsUtils.cs +++ b/v2rayN/ServiceLib/Common/WindowsUtils.cs @@ -53,12 +53,12 @@ internal static class WindowsUtils public static async Task RemoveTunDevice() { - var tunNameList = new List { "singbox_tun", "xray_tun" }; + var tunNameList = new List { "wintunsingbox_tun", "xray_tun" }; foreach (var tunName in tunNameList) { try { - var sum = MD5.HashData(Encoding.UTF8.GetBytes($"wintun{tunName}")); + 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}}}" """; From 452478434cc01fe4fbf2293abdfab0febfe3f989 Mon Sep 17 00:00:00 2001 From: JieXu Date: Fri, 17 Apr 2026 15:29:51 +0800 Subject: [PATCH 04/21] Fix & Update (#9126) * Update build-linux.yml * Update build-all.yml * Update build-linux.yml * Update build-linux.yml * Update build-linux.yml * Update OptionSettingWindow.axaml.cs * Update ResUI.fr.resx * Update package-rhel-riscv.sh * Update build-linux.yml * Update build-linux.yml * Update build-all.yml --------- Co-authored-by: xujie86 <167618598+xujie86@users.noreply.github.com> --- .github/workflows/build-linux.yml | 6 +++--- package-rhel-riscv.sh | 8 ++++---- v2rayN/ServiceLib/Resx/ResUI.fr.resx | 5 +---- v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs | 3 ++- 4 files changed, 10 insertions(+), 12 deletions(-) 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/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/ServiceLib/Resx/ResUI.fr.resx b/v2rayN/ServiceLib/Resx/ResUI.fr.resx index 907eb02c..8540727f 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.fr.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.fr.resx @@ -1318,7 +1318,7 @@ 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. @@ -1701,9 +1701,6 @@ 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 diff --git a/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs index 26e55646..6501468d 100644 --- a/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs @@ -99,7 +99,8 @@ public partial class OptionSettingWindow : WindowBase this.Bind(ViewModel, vm => vm.SpeedPingTestUrl, v => v.cmbSpeedPingTestUrl.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.MixedConcurrencyCount, v => v.cmbMixedConcurrencyCount.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SubConvertUrl, v => v.cmbSubConvertUrl.Text).DisposeWith(disposables); - this.Bind(ViewModel, vm => vm.MainGirdOrientation, v => v.cmbMainGirdOrientation.SelectedIndex).DisposeWith(disposables); + this.Bind(ViewModel, + vm => vm.MainGirdOrientation, view => view.cmbMainGirdOrientation.SelectedIndex).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.GeoFileSourceUrl, v => v.cmbGetFilesSourceUrl.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SrsFileSourceUrl, v => v.cmbSrsFilesSourceUrl.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.RoutingRulesSourceUrl, v => v.cmbRoutingRulesSourceUrl.SelectedValue).DisposeWith(disposables); From 021e64e20bc2e3b4462c89d18df371077f32b295 Mon Sep 17 00:00:00 2001 From: DHR60 Date: Sat, 18 Apr 2026 07:23:42 +0000 Subject: [PATCH 05/21] Fix (#9141) --- v2rayN/ServiceLib/Global.cs | 2 +- v2rayN/ServiceLib/Models/ConfigItems.cs | 2 +- v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/v2rayN/ServiceLib/Global.cs b/v2rayN/ServiceLib/Global.cs index 267ec60a..7c0f98d8 100644 --- a/v2rayN/ServiceLib/Global.cs +++ b/v2rayN/ServiceLib/Global.cs @@ -94,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"; diff --git a/v2rayN/ServiceLib/Models/ConfigItems.cs b/v2rayN/ServiceLib/Models/ConfigItems.cs index fa766f0d..d47d2876 100644 --- a/v2rayN/ServiceLib/Models/ConfigItems.cs +++ b/v2rayN/ServiceLib/Models/ConfigItems.cs @@ -197,7 +197,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/ViewModels/AddServerViewModel.cs b/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs index 9fbb6125..0264bc1f 100644 --- a/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs @@ -292,7 +292,7 @@ public class AddServerViewModel : MyReactiveObject 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; From eeecef4db95df5014634d95ccf93c7e443468a7e Mon Sep 17 00:00:00 2001 From: DHR60 Date: Sat, 18 Apr 2026 11:18:17 +0000 Subject: [PATCH 06/21] Fix (#9143) * Adjust XHTTP style * Add xray tun custom support --- v2rayN/ServiceLib/Resx/ResUI.Designer.cs | 11 ++++- v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx | 5 ++- v2rayN/ServiceLib/Resx/ResUI.fr.resx | 7 +++- v2rayN/ServiceLib/Resx/ResUI.hu.resx | 5 ++- v2rayN/ServiceLib/Resx/ResUI.resx | 5 ++- v2rayN/ServiceLib/Resx/ResUI.ru.resx | 5 ++- v2rayN/ServiceLib/Resx/ResUI.zh-Hans.resx | 5 ++- v2rayN/ServiceLib/Resx/ResUI.zh-Hant.resx | 5 ++- .../V2ray/V2rayConfigTemplateService.cs | 10 ++++- .../CoreConfig/V2ray/V2rayDnsService.cs | 10 ++--- .../ViewModels/DNSSettingViewModel.cs | 19 +++++++++ .../ViewModels/FullConfigTemplateViewModel.cs | 30 ++++++++++---- .../Views/AddServerWindow.axaml | 16 ++++---- .../Views/DNSSettingWindow.axaml | 27 ++++++++---- .../Views/DNSSettingWindow.axaml.cs | 1 + .../Views/FullConfigTemplateWindow.axaml | 27 ++++++++---- .../Views/FullConfigTemplateWindow.axaml.cs | 3 +- v2rayN/v2rayN/Views/AddServerWindow.xaml | 6 ++- v2rayN/v2rayN/Views/DNSSettingWindow.xaml | 41 ++++++++++++++----- v2rayN/v2rayN/Views/DNSSettingWindow.xaml.cs | 1 + .../Views/FullConfigTemplateWindow.xaml | 41 ++++++++++++++----- .../Views/FullConfigTemplateWindow.xaml.cs | 1 + 22 files changed, 211 insertions(+), 70 deletions(-) diff --git a/v2rayN/ServiceLib/Resx/ResUI.Designer.cs b/v2rayN/ServiceLib/Resx/ResUI.Designer.cs index 234cdef3..0743b6c7 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.Designer.cs +++ b/v2rayN/ServiceLib/Resx/ResUI.Designer.cs @@ -4681,7 +4681,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 { diff --git a/v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx b/v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx index 08aaf893..84f9722e 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx @@ -1321,7 +1321,7 @@ حالت xhttp - جیسون خام XHTTP Extra, فرمت: { XHTTPObject } + Raw JSON, format: { XHTTP Object } هنگام بستن پنجره در سینی پنهان شوید @@ -1704,4 +1704,7 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if Host + + XHTTP Extra + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.fr.resx b/v2rayN/ServiceLib/Resx/ResUI.fr.resx index 8540727f..84033130 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.fr.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.fr.resx @@ -1327,7 +1327,7 @@ 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 @@ -1707,4 +1707,7 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if Host - + + XHTTP Extra + + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.hu.resx b/v2rayN/ServiceLib/Resx/ResUI.hu.resx index f761cca9..e58ae6f0 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.hu.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.hu.resx @@ -1321,7 +1321,7 @@ 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 @@ -1704,4 +1704,7 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if Host + + XHTTP Extra + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.resx b/v2rayN/ServiceLib/Resx/ResUI.resx index d30c3f31..b4120d3c 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.resx @@ -1330,7 +1330,7 @@ xhttp mode - XHTTP Extra raw JSON, format: { XHTTP Object } + Raw JSON, format: { XHTTP Object } Hide to tray when closing the window @@ -1710,4 +1710,7 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if Host + + XHTTP Extra + \ No newline at end of file diff --git a/v2rayN/ServiceLib/Resx/ResUI.ru.resx b/v2rayN/ServiceLib/Resx/ResUI.ru.resx index 1521e67c..4d30949c 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.ru.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.ru.resx @@ -1321,7 +1321,7 @@ XHTTP-режим - Дополнительный сырой JSON для XHTTP, формат: { XHTTP Object } + Raw JSON, format: { XHTTP Object } Сворачивать в трей при закрытии окна @@ -1704,4 +1704,7 @@ Host + + XHTTP Extra + \ 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 379fb4ba..b47b832e 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.zh-Hans.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.zh-Hans.resx @@ -1327,7 +1327,7 @@ XHTTP 模式 - XHTTP Extra 原始 JSON,格式: { XHTTPObject } + 原始 JSON,格式: { XHTTPObject } 关闭窗口时隐藏至托盘 @@ -1707,4 +1707,7 @@ 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 a903d168..7ba89b33 100644 --- a/v2rayN/ServiceLib/Resx/ResUI.zh-Hant.resx +++ b/v2rayN/ServiceLib/Resx/ResUI.zh-Hant.resx @@ -1318,7 +1318,7 @@ xhttp 模式 - XHTTP Extra 原始 JSON,格式: { XHTTPObject } + 原始 JSON,格式: { XHTTPObject } 關閉視窗時隱藏至托盤 @@ -1701,4 +1701,7 @@ Host + + XHTTP Extra + \ No newline at end of file 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/ViewModels/DNSSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/DNSSettingViewModel.cs index 00178d17..25fbe4b9 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,6 +127,21 @@ 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); @@ -149,6 +167,7 @@ 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); 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/v2rayN.Desktop/Views/AddServerWindow.axaml b/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml index 1d2bb899..56a579db 100644 --- a/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml +++ b/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml @@ -814,17 +814,17 @@ Grid.Column="0" Margin="{StaticResource Margin4}" VerticalAlignment="Top" - Text="{x:Static resx:ResUI.TransportExtraTip}" + Text="{x:Static resx:ResUI.TransportExtra}" TextWrapping="Wrap" /> - + IsExpanded="True"> + + + + + - - - + + + + + + + + + + + + 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/Views/AddServerWindow.xaml b/v2rayN/v2rayN/Views/AddServerWindow.xaml index 25a1234b..ec86e904 100644 --- a/v2rayN/v2rayN/Views/AddServerWindow.xaml +++ b/v2rayN/v2rayN/Views/AddServerWindow.xaml @@ -1071,7 +1071,7 @@ Margin="{StaticResource Margin4}" VerticalAlignment="Top" Style="{StaticResource ToolbarTextBlock}" - Text="{x:Static resx:ResUI.TransportExtraTip}" + Text="{x:Static resx:ResUI.TransportExtra}" TextWrapping="Wrap" /> diff --git a/v2rayN/v2rayN/Views/DNSSettingWindow.xaml b/v2rayN/v2rayN/Views/DNSSettingWindow.xaml index 8788e97d..d27188a4 100644 --- a/v2rayN/v2rayN/Views/DNSSettingWindow.xaml +++ b/v2rayN/v2rayN/Views/DNSSettingWindow.xaml @@ -453,16 +453,37 @@ - + + + + + + + + + + + + + diff --git a/v2rayN/v2rayN/Views/DNSSettingWindow.xaml.cs b/v2rayN/v2rayN/Views/DNSSettingWindow.xaml.cs index 2710b102..a7f1bd12 100644 --- a/v2rayN/v2rayN/Views/DNSSettingWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/DNSSettingWindow.xaml.cs @@ -50,6 +50,7 @@ public partial class DNSSettingWindow this.Bind(ViewModel, vm => vm.DomainStrategy4FreedomCompatible, v => v.cmbdomainStrategy4FreedomCompatible.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.DomainDNSAddressCompatible, v => v.cmbdomainDNSAddressCompatible.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.NormalDNSCompatible, v => v.txtnormalDNSCompatible.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.TunDNSCompatible, v => v.txttunDNSCompatible.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.DomainStrategy4Freedom2Compatible, v => v.cmbdomainStrategy4OutCompatible.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.DomainDNSAddress2Compatible, v => v.cmbdomainDNSAddress2Compatible.Text).DisposeWith(disposables); diff --git a/v2rayN/v2rayN/Views/FullConfigTemplateWindow.xaml b/v2rayN/v2rayN/Views/FullConfigTemplateWindow.xaml index d3ca8af7..4b9953d7 100644 --- a/v2rayN/v2rayN/Views/FullConfigTemplateWindow.xaml +++ b/v2rayN/v2rayN/Views/FullConfigTemplateWindow.xaml @@ -107,16 +107,37 @@ - + + + + + + + + + + + + + diff --git a/v2rayN/v2rayN/Views/FullConfigTemplateWindow.xaml.cs b/v2rayN/v2rayN/Views/FullConfigTemplateWindow.xaml.cs index a9f95a53..031dc40a 100644 --- a/v2rayN/v2rayN/Views/FullConfigTemplateWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/FullConfigTemplateWindow.xaml.cs @@ -17,6 +17,7 @@ public partial class FullConfigTemplateWindow { this.Bind(ViewModel, vm => vm.EnableFullConfigTemplate4Ray, v => v.rayFullConfigTemplateEnable.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.FullConfigTemplate4Ray, v => v.rayFullConfigTemplate.Text).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.FullTunConfigTemplate4Ray, v => v.rayFullTunConfigTemplate.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.AddProxyOnly4Ray, v => v.togAddProxyProtocolOutboundOnly4Ray.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.ProxyDetour4Ray, v => v.txtProxyDetour4Ray.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableFullConfigTemplate4Singbox, v => v.sbFullConfigTemplateEnable.IsChecked).DisposeWith(disposables); From cabd0df2820f5354ed833865307eddc2071e830c Mon Sep 17 00:00:00 2001 From: DHR60 Date: Sat, 18 Apr 2026 11:19:03 +0000 Subject: [PATCH 07/21] Support kcp cwndMultiplier (#9113) --- v2rayN/ServiceLib/Handler/ConfigHandler.cs | 7 ++++--- v2rayN/ServiceLib/Models/ConfigItems.cs | 6 ++---- v2rayN/ServiceLib/Models/V2rayConfig.cs | 6 ++---- .../Services/CoreConfig/V2ray/V2rayOutboundService.cs | 5 ++--- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/v2rayN/ServiceLib/Handler/ConfigHandler.cs b/v2rayN/ServiceLib/Handler/ConfigHandler.cs index eab544da..da7258a7 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, diff --git a/v2rayN/ServiceLib/Models/ConfigItems.cs b/v2rayN/ServiceLib/Models/ConfigItems.cs index d47d2876..1988d3b7 100644 --- a/v2rayN/ServiceLib/Models/ConfigItems.cs +++ b/v2rayN/ServiceLib/Models/ConfigItems.cs @@ -49,11 +49,9 @@ public class KcpItem public int DownlinkCapacity { get; set; } - public bool Congestion { get; set; } + public int CwndMultiplier { get; set; } - public int ReadBufferSize { get; set; } - - public int WriteBufferSize { get; set; } + public int MaxSendingWindow { get; set; } } [Serializable] diff --git a/v2rayN/ServiceLib/Models/V2rayConfig.cs b/v2rayN/ServiceLib/Models/V2rayConfig.cs index a5ac2e24..909a37fb 100644 --- a/v2rayN/ServiceLib/Models/V2rayConfig.cs +++ b/v2rayN/ServiceLib/Models/V2rayConfig.cs @@ -409,11 +409,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 diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs index a0d4099f..d40ed8a3 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs @@ -477,9 +477,8 @@ 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(headerType, out var header)) { From 35b98f945fb2628d5aca5adf050f53703aea7501 Mon Sep 17 00:00:00 2001 From: DHR60 Date: Sun, 19 Apr 2026 05:42:55 +0000 Subject: [PATCH 08/21] Support new fragment (#9122) --- v2rayN/ServiceLib/Handler/ConfigHandler.cs | 2 +- v2rayN/ServiceLib/Models/V2rayConfig.cs | 18 +++- .../CoreConfig/V2ray/V2rayOutboundService.cs | 97 +++++++++++++------ 3 files changed, 84 insertions(+), 33 deletions(-) diff --git a/v2rayN/ServiceLib/Handler/ConfigHandler.cs b/v2rayN/ServiceLib/Handler/ConfigHandler.cs index da7258a7..a49f12f7 100644 --- a/v2rayN/ServiceLib/Handler/ConfigHandler.cs +++ b/v2rayN/ServiceLib/Handler/ConfigHandler.cs @@ -162,7 +162,7 @@ public static class ConfigHandler config.Fragment4RayItem ??= new() { Packets = "tlshello", - Length = "100-200", + Length = "50-100", Interval = "10-20" }; config.GlobalHotkeys ??= new(); diff --git a/v2rayN/ServiceLib/Models/V2rayConfig.cs b/v2rayN/ServiceLib/Models/V2rayConfig.cs index 909a37fb..b6aaa2df 100644 --- a/v2rayN/ServiceLib/Models/V2rayConfig.cs +++ b/v2rayN/ServiceLib/Models/V2rayConfig.cs @@ -140,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; } @@ -501,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 diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs index d40ed8a3..8b3da6b5 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 (_config.CoreBasicItem.EnableFragment) + { + ApplyOutboundFragment(); + } if (context.IsTunEnabled) { _coreConfig.outbounds.Add(BuildDnsOutbound()); @@ -29,35 +33,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; } @@ -837,4 +812,68 @@ public partial class CoreConfigV2rayService 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; + } + } } From b604a5b78763f8f409274d23005aba7ed9f7af6e Mon Sep 17 00:00:00 2001 From: Mangoo Date: Sun, 19 Apr 2026 08:25:53 +0200 Subject: [PATCH 09/21] fix: remove Save/Cancel from routing settings, save edits immediately (#9133) --- .../ViewModels/RoutingSettingViewModel.cs | 34 +++++++-------- .../Views/RoutingSettingWindow.axaml | 18 -------- .../Views/RoutingSettingWindow.axaml.cs | 42 +++++++------------ v2rayN/v2rayN/Views/RoutingSettingWindow.xaml | 20 --------- .../v2rayN/Views/RoutingSettingWindow.xaml.cs | 20 +-------- 5 files changed, 33 insertions(+), 101 deletions(-) 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/Views/RoutingSettingWindow.axaml b/v2rayN/v2rayN.Desktop/Views/RoutingSettingWindow.axaml index a9155f7d..1eb4d5b9 100644 --- a/v2rayN/v2rayN.Desktop/Views/RoutingSettingWindow.axaml +++ b/v2rayN/v2rayN.Desktop/Views/RoutingSettingWindow.axaml @@ -20,24 +20,6 @@ - -