Compare commits

...

95 Commits

Author SHA1 Message Date
ChsBuffer
af5100fe73 bump version to 1.6.4 2020-10-21 21:48:23 +08:00
ChsBuffer
f8bcef7ac9 fix: Updater parse multiple space path 2020-10-21 21:40:55 +08:00
ChsBuffer
591f8e5a5c feat: V2Ray TLS AllowInsecure Setting 2020-10-21 21:34:28 +08:00
ChsBuffer
00047a5030 refactor: SettingForm
feat: KCPSettings
2020-10-21 21:25:07 +08:00
ChsBuffer
6d4dab573e feat: split SettingForm settings 2020-10-21 17:50:22 +08:00
ChsBuffer
141fc58df4 fix: #415 Mode 4 start failed 2020-10-21 16:38:30 +08:00
ChsBuffer
4210f36814 fix: VLESSForm UseMux CheckBox 2020-10-20 17:52:17 +08:00
ChsBuffer
98adb01760 bump version to 1.6.3 2020-10-20 14:37:28 +08:00
ChsBuffer
a2ae28d3ae refactor: resize MainForm when no Profile 2020-10-20 10:59:53 +08:00
ChsBuffer
30854deba6 fix: TAP Mode first time searching adapter 2020-10-19 17:41:01 +08:00
ChsBuffer
ef8013c073 fix: installed NF Driver version output 2020-10-19 17:30:03 +08:00
ChsBuffer
abfae4a9a0 refactor: MainForm change Enabled to change State 2020-10-19 17:29:59 +08:00
Connection Refused
4731e27d2e Update Redirector 2020-10-19 15:27:07 +08:00
ChsBuffer
a993df7f2f fix: upgrade package and upgrade Test.csproj to new format 2020-10-17 18:03:26 +08:00
ChsBuffer
3c6c2bde31 refactor: cut IPNetwork2 2020-10-17 17:27:01 +08:00
ChsBuffer
f8299fb7be refactor: Add in keyword as need 2020-10-17 17:18:40 +08:00
ChsBuffer
b54bc6fa40 feat: Redirector socks5 authentication support
refactor: Redirector dial
2020-10-17 16:18:40 +08:00
ChsBuffer
b2ac98b21f refactor: change port type to ushort 2020-10-17 15:20:56 +08:00
Connection Refused
86a86a94d8 Update Redirector 2020-10-17 15:08:23 +08:00
ChsBuffer
7bbffb002f refactor: Add GetModeControllerByType 2020-10-16 15:42:35 +08:00
ChsBuffer
1b6fe29085 refactor: Remove Server argument in IModeController.Start 2020-10-15 19:17:04 +08:00
ChsBuffer
918e260f3e refactor: Add IServerController.Server and use in ModeControllers 2020-10-15 19:15:13 +08:00
ChsBuffer
508e77759c fix: ServerController is not assigned 2020-10-15 15:03:20 +08:00
Amazing_DM
a21d7ff6fd 修复停止后代理进程未结束的问题 2020-10-15 14:27:28 +08:00
AmazingDM
b4050f2fa4 Update Advanced_Usage.zh-CN.md 2020-10-15 09:41:32 +08:00
ChsBuffer
1b1a9fc05d fix: PrivoxyController typo 2020-10-14 20:01:26 +08:00
ChsBuffer
985330f564 refactor: change port type to ushort
refactor: StatusPortInfoText
2020-10-14 17:40:48 +08:00
ChsBuffer
eb6b87e4aa refacotr: StartServer 2020-10-14 17:19:03 +08:00
ChsBuffer
5af2749760 refactor: updater argument parse to fix path with space 2020-10-13 19:13:46 +08:00
ChsBuffer
be4a18d599 feat: Trojan GetShareLink
fix: Socks5 Auth ShareLink
2020-10-13 11:24:07 +08:00
ChsBuffer
5d0bcbd6b0 fix: disable ResolveServerHostname default 2020-10-13 10:15:40 +08:00
ChsBuffer
ab6a2ecc30 fix: mode 2 try to delete 0.0.0.0/0 route entry twice 2020-10-13 10:05:32 +08:00
ChsBuffer
ceb57dcc1a refactor: move IModeController.TestNatRequired to Mode 2020-10-13 09:48:21 +08:00
ChsBuffer
79b6e5da43 feat: Mode.SupportSocks5Auth 2020-10-13 09:45:30 +08:00
ChsBuffer
2d95d8b257 refactor: NFController dial host 2020-10-13 09:43:19 +08:00
ChsBuffer
50eb07badf feat: warning mode self-reference 2020-10-13 09:08:58 +08:00
ChsBuffer
3f902a2d3d refactor: SetupRouteTable() rules creation order
fix: #397
2020-10-13 09:08:57 +08:00
Connection Refused
72b094e641 Update submodule 2020-10-13 08:43:25 +08:00
Connection Refused
c7fb7e3959 Update REAMDE.md 2020-10-13 08:38:52 +08:00
ChsBuffer
9e249bc211 refactor: boundStreamSettings
fix: #405
2020-10-13 08:15:12 +08:00
ChsBuffer
2332c9ec50 fix: VLESS Config Generate 2020-10-12 22:27:28 +08:00
ChsBuffer
202fdfe5a0 feat: support socks5 authentication 2020-10-12 22:18:56 +08:00
ChsBuffer
18b905ed0c feat: remove v2ray config file when exit 2020-10-12 21:56:53 +08:00
ChsBuffer
3f1b21c4e5 feat: VLESS support 2020-10-12 21:44:58 +08:00
ChsBuffer
477c6e3fc1 refactor: Generate V2ray Config 2020-10-12 21:39:37 +08:00
ChsBuffer
5e58708895 fix: Add Socks5 Authentication TextBox 2020-10-12 15:12:55 +08:00
ChsBuffer
c3eb07005e bump version to 1.6.2 2020-10-11 19:57:54 +08:00
ChsBuffer
12b2989755 feat: Resolve Server hostname option 2020-10-11 02:08:43 +08:00
ChsBuffer
0222792361 refactor: IServerController client config 2020-10-11 01:58:14 +08:00
ChsBuffer
3e5e3a7275 clean: remove SS DLL's No ACL support remark
refactor: Enable SS DLL by default
2020-10-11 00:56:55 +08:00
ChsBuffer
a49e280e03 refactor: NetTraffic record pid
fix: #399
2020-10-11 00:51:41 +08:00
ChsBuffer
45b6352553 feat: -console argument 2020-10-10 22:37:23 +08:00
Bruce Wayne
406fbd8b7e Merge pull request #398 from NetchX/fixCI 2020-10-10 22:35:16 +08:00
Bruce Wayne
454b03a69f Fix build scripts 2020-10-10 22:22:41 +08:00
ChsBuffer
98ab8864eb fix: SS DLL config 2020-10-10 21:43:53 +08:00
Bruce Wayne
f3358f3da2 Drop Nuget cache 2020-10-10 21:12:14 +08:00
Bruce Wayne
fa1593de49 Fix CI 2020-10-10 20:27:04 +08:00
Bruce Wayne
f26d09bf9f Update GetSHA256.ps1 2020-10-10 20:08:38 +08:00
ChsBuffer
35859a19f7 fix: #396 2020-10-10 13:13:44 +08:00
ChsBuffer
e3e595d469 cut: edit process mode endwith ".exe" check 2020-10-10 00:05:31 +08:00
ChsBuffer
36718e774c feat: mode reference( #include <RelativePathWithoutExtesion.h> ) 2020-10-10 00:02:44 +08:00
ChsBuffer
bf6d3aae95 fix: Process Form high dpi scale 2020-10-09 22:15:36 +08:00
ChsBuffer
477509b12f refactor: VMess.ParseUri
- break: version 1 support
- break: mux config in uri
2020-10-09 20:23:46 +08:00
ChsBuffer
910f6818b0 Revert "mode 2 remove outbound 0.0.0.0/0"
This reverts commit d369858273.
2020-10-09 20:02:59 +08:00
ChsBuffer
ed3f4d1763 refactor: ShareLink.ParseText Non-Nullable
refactor: UpdateServersFromSubscribe
2020-10-09 19:56:47 +08:00
ChsBuffer
be53432a2e refactor: try catch ICSHelper exception #393 2020-10-09 19:21:00 +08:00
ChsBuffer
9d78de0f6c refactor: SubscribeForm Save
- remove: duplicate link check
- fix: check remark duplicate not work
2020-10-08 20:31:50 +08:00
ChsBuffer
75bf753a65 reafactor: ICS Check State 2020-10-08 20:30:42 +08:00
ChsBuffer
3efbad5e5e bump version to 1.6.1 2020-10-07 21:18:37 +08:00
ChsBuffer
020c2d7e67 refactor: merge ServerForm's parital declarations 2020-10-07 21:11:39 +08:00
ChsBuffer
adcc6a75c9 fix: MainForm Text reload got exception when increase profile count #389 2020-10-07 20:54:00 +08:00
ChsBuffer
7e907eef6f fix: ServerForm High DPI Scale #388 2020-10-07 20:37:23 +08:00
ChsBuffer
d213872bde refact: rename TUNTAPController Gateway to Outbound 2020-10-07 19:26:30 +08:00
ChsBuffer
71687c1da6 Revert "Use GetLocalEndPoint to replace GetBestRoute"
This reverts commit 801e8e3b8a.
2020-10-07 19:26:25 +08:00
ChsBuffer
2eb6b23ca7 fix: trojan form 2020-10-07 10:07:55 +08:00
ChsBuffer
5490364217 bump version to 1.6.0 2020-10-06 19:18:19 +08:00
ChsBuffer
e1d66970e2 refactor: move china_ip_list to rule 2020-10-06 01:40:02 +08:00
ChsBuffer
af05878cc5 refactor: load mode head 2020-10-06 01:32:04 +08:00
ChsBuffer
a59cfdf066 clean: modes 2020-10-06 01:04:17 +08:00
ChsBuffer
513667d983 fix: IsWindows10Upper not assigned caused NetTraffic won't be displayed at the first start
fix: SupportFakeDns flag lazyload
2020-10-06 00:57:54 +08:00
ChsBuffer
2e89011f56 clean: translation 2020-10-05 22:52:56 +08:00
ChsBuffer
d369858273 fix: searchOutbound logging,mode 2 remove outbound 0.0.0.0/0 2020-10-05 22:52:04 +08:00
ChsBuffer
78def0ae1d fix: lookup server hostname before start 2020-10-05 16:19:50 +08:00
ChsBuffer
2dc4bb771e refactor: TUNTAPController SearchTapAdapter
change: Reinstall TUN/TAP Adapter to Uninstall TUN/TAP Adapter
rename: ICS to Tap Network Sharing
2020-10-04 22:05:08 +08:00
ChsBuffer
4b4280c06b remove: ServerForm.CreateComboBox parse argument 2020-10-04 12:39:47 +08:00
ChsBuffer
23ac571ade refactor: ServerForm AddControl methods
test: Parse VMess Uri
2020-10-04 10:19:09 +08:00
ChsBuffer
6f9e364444 remove: Server.Country 2020-10-04 03:51:39 +08:00
ChsBuffer
9fbac446e3 refactor: Servers Forms 2020-10-04 03:47:38 +08:00
ChsBuffer
73c7a9fe32 fix aiodns rules 2020-10-03 23:39:38 +08:00
ChsBuffer
4617de3fda Refactroing Server.ToString, Remove country name in ServerComboBox Text 2020-10-03 21:14:42 +08:00
ChsBuffer
40db9adc0d fix mode 4 start failed 2020-10-03 21:14:42 +08:00
Connection Refused
ec4e98db62 Update submodules 2020-10-03 20:53:47 +08:00
ChsBuffer
4f3b0e5afb rename namespace and move some classes 2020-10-02 16:18:53 +08:00
ChsBuffer
36dc4a07f1 Reset items in ModeComboBox before start profile 2020-10-02 01:35:31 +08:00
Bruce Wayne
cc99d32232 Update CI 2020-09-30 20:08:14 +08:00
117 changed files with 4090 additions and 28701 deletions

View File

@@ -5,43 +5,29 @@ jobs:
name: Build
runs-on: windows-latest
steps:
- name: Setup NuGet
uses: nuget/setup-nuget@v1
- name: Setup MSBuild
uses: microsoft/setup-msbuild@v1.0.0
uses: microsoft/setup-msbuild@v1.0.2
- name: Checkout
uses: actions/checkout@v2
with:
submodules: true
- name: Restore NuGet Packages Cache
uses: actions/cache@v2
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('Netch/Netch.csproj') }}
restore-keys: |
${{ runner.os }}-nuget-
- name: Restore NuGet Package
run: nuget restore Netch.sln
- name: Build Solution
shell: pwsh
run: |
.\BUILD.ps1
New-Item -ItemType Directory -Path C:\builtfiles -Force > $null
7z a -mx9 C:\builtfiles\Netch.7z .\Netch\bin\x64\Release\win-x64\
7z rn C:\builtfiles\Netch.7z win-x64 Netch
echo "::set-env name=Netch_SHA256::$(.\GetSHA256.ps1 C:\builtfiles\Netch.7z)"
echo "::set-env name=Netch_EXE_SHA256::$(.\GetSHA256.ps1 Netch\bin\x64\Release\win-x64\Netch.exe)"
7z a -mx9 C:\builtfiles\Netch.7z .\Netch\bin\x64\Release\
7z rn C:\builtfiles\Netch.7z Release Netch
echo "Netch_SHA256=$(.\GetSHA256.ps1 C:\builtfiles\Netch.7z)" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
echo "Netch_EXE_SHA256=$(.\GetSHA256.ps1 Netch\bin\x64\Release\Netch.exe)" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
- name: Upload Artifact
uses: actions/upload-artifact@v2
with:
name: Netch
path: Netch\bin\x64\Release\win-x64
path: Netch\bin\x64\Release
- name: Release
uses: softprops/action-gh-release@v1

View File

@@ -1,33 +1,12 @@
param([string]$buildtfm = 'all')
Write-Host 'Building'
Write-Host 'DotNet SDK Version'
dotnet --version
msbuild -v:n -m:1 /p:Configuration="Release" `
/p:Platform="x64" `
/p:TargetFramework=net48 `
/p:SolutionDir="..\" `
/restore `
Netch\Netch.csproj
$exe = 'Netch.exe'
$mainDir = (Get-Item -Path ".\").FullName
$net_baseoutput = "$mainDir\Netch\bin\$configuration"
if ($LASTEXITCODE) { exit $LASTEXITCODE }
Write-Host $mainDir
Write-Host $net_baseoutput
function Build-NetFrameworkx64
{
Write-Host 'Building .NET Framework x64'
$outdir = "$net_baseoutput\x64"
msbuild -v:n -m:1 /p:Configuration="Release" `
/p:Platform="x64" `
/p:TargetFramework=net48 `
/p:Runtimeidentifier=win-x64 `
/restore
if ($LASTEXITCODE) { cd $mainDir ; exit $LASTEXITCODE }
Write-Host 'Build done'
}
cd $mainDir
Build-NetFrameworkx64
cd $mainDir
exit 0
Write-Host 'Build done'

View File

@@ -1,5 +1,6 @@
param([string]$file)
$hash = [Security.Cryptography.HashAlgorithm]::Create( "SHA256" )
$stream = ([IO.StreamReader]$file).BaseStream
-join ($hash.ComputeHash($stream) | ForEach { "{0:x2}" -f $_ })
$stream.Close()
$path = (Resolve-Path -Path $file).Path
$stream = ([IO.StreamReader]$path).BaseStream
-join ($hash.ComputeHash($stream) | ForEach-Object { "{0:x2}" -f $_ })
$stream.Close()

View File

@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetchLib", "NetchLib\NetchL
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetchUpdater", "NetchUpdater\NetchUpdater.csproj", "{828318A8-9B90-4A5F-BD6B-E632CC9D8933}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test", "Test\Test.csproj", "{53397641-35CA-4336-8E22-2CE12EF476AC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@@ -27,6 +29,10 @@ Global
{828318A8-9B90-4A5F-BD6B-E632CC9D8933}.Debug|x64.Build.0 = Debug|x64
{828318A8-9B90-4A5F-BD6B-E632CC9D8933}.Release|x64.ActiveCfg = Release|x64
{828318A8-9B90-4A5F-BD6B-E632CC9D8933}.Release|x64.Build.0 = Release|x64
{53397641-35CA-4336-8E22-2CE12EF476AC}.Debug|x64.ActiveCfg = Debug|Any CPU
{53397641-35CA-4336-8E22-2CE12EF476AC}.Debug|x64.Build.0 = Debug|Any CPU
{53397641-35CA-4336-8E22-2CE12EF476AC}.Release|x64.ActiveCfg = Release|Any CPU
{53397641-35CA-4336-8E22-2CE12EF476AC}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -4,13 +4,10 @@ using System.Text;
namespace Netch.Controllers
{
public class DNSController : Controller
public class DNSController : IController
{
public DNSController()
{
Name = "DNS Service";
RedirectStd = false;
}
public string Name { get; } = "DNS Service";
/// <summary>
/// 启动DNS服务
@@ -27,7 +24,7 @@ namespace Netch.Controllers
aiodns_init();
}
public override void Stop()
public void Stop()
{
aiodns_free();
}

View File

@@ -12,12 +12,18 @@ using Timer = System.Timers.Timer;
namespace Netch.Controllers
{
abstract partial class Controller
public abstract class Guard
{
public abstract string Name { get; protected set; }
/// <summary>
/// 主程序名
/// </summary>
public string MainFile { get; protected set; }
public abstract string MainFile { get; protected set; }
protected State State { get; set; } = State.Waiting;
public abstract void Stop();
/// <summary>
/// 成功启动关键词

View File

@@ -4,53 +4,34 @@ using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
using Netch.Models;
using Netch.ServerEx.Socks5;
using Netch.Servers.Socks5;
using Netch.Utils;
namespace Netch.Controllers
{
public class HTTPController : ModeController
public class HTTPController : IModeController
{
public override bool TestNatRequired { get; } = false;
public const string IEProxyExceptions = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*";
/// <summary>
/// 实例
/// </summary>
public PrivoxyController pPrivoxyController = new PrivoxyController();
private string prevBypass, prevHTTP, prevPAC;
private bool prevEnabled;
public HTTPController()
{
Name = "HTTP";
}
public string Name { get; } = "HTTP";
/// <summary>
/// 启动
/// </summary>
/// <param name="s">服务器</param>
/// <param name="mode">模式</param>
/// <returns>是否启动成功</returns>
public override bool Start(Server s, Mode mode)
public bool Start(in Mode mode)
{
RecordPrevious();
try
{
if (s.IsSocks5())
{
var server = (Socks5) s;
if (!string.IsNullOrWhiteSpace(server.Username) && !string.IsNullOrWhiteSpace(server.Password)) return false;
pPrivoxyController.Start(s, mode);
}
else
{
pPrivoxyController.Start(s, mode);
}
pPrivoxyController.Start(MainController.ServerController.Server, mode);
if (mode.Type == 3) NativeMethods.SetGlobal($"127.0.0.1:{Global.Settings.HTTPLocalPort}", IEProxyExceptions);
}
@@ -97,7 +78,7 @@ namespace Netch.Controllers
/// <summary>
/// 停止
/// </summary>
public override void Stop()
public void Stop()
{
var tasks = new[]
{

View File

@@ -0,0 +1,15 @@
namespace Netch.Controllers
{
public interface IController
{
/// <summary>
/// 控制器名
/// </summary>
public string Name { get; }
/// <summary>
/// 停止
/// </summary>
public abstract void Stop();
}
}

View File

@@ -2,16 +2,13 @@ using Netch.Models;
namespace Netch.Controllers
{
public abstract class ModeController : Controller
public interface IModeController : IController
{
/// <summary>
/// 启动
/// </summary>
/// <param name="s">服务器</param>
/// <param name="mode">模式</param>
/// <returns>是否成功</returns>
public abstract bool Start(Server s, Mode mode);
public abstract bool TestNatRequired { get; }
public abstract bool Start(in Mode mode);
}
}

View File

@@ -0,0 +1,34 @@
using Netch.Models;
namespace Netch.Controllers
{
public interface IServerController : IController
{
public Server Server { get; set; }
public ushort? Socks5LocalPort { get; set; }
public string LocalAddress { get; set; }
/// <summary>
/// 启动
/// </summary>
/// <param name="s">服务器</param>
/// <param name="mode">模式</param>
/// <returns>是否启动成功</returns>
public abstract bool Start(in Server s, in Mode mode);
}
public static class ServerControllerExtension
{
public static ushort Socks5LocalPort(this IServerController controller)
{
return controller.Socks5LocalPort ?? Global.Settings.Socks5LocalPort;
}
public static string LocalAddress(this IServerController controller)
{
return controller.LocalAddress ?? Global.Settings.LocalAddress;
}
}
}

View File

@@ -1,22 +0,0 @@
using Netch.Models;
namespace Netch.Controllers
{
public abstract partial class Controller
{
/// <summary>
/// 控制器名
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// 当前状态
/// </summary>
public State State { get; protected set; } = State.Waiting;
/// <summary>
/// 停止
/// </summary>
public abstract void Stop();
}
}

View File

@@ -1,7 +1,9 @@
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Netch.Models;
using Netch.Servers.Socks5;
using Netch.Utils;
using static Netch.Forms.MainForm;
using static Netch.Utils.PortHelper;
@@ -10,12 +12,18 @@ namespace Netch.Controllers
{
public static class MainController
{
public static ServerController ServerController { get; private set; }
public static ModeController ModeController { get; private set; }
public static IServerController ServerController
{
get => _serverController;
private set => _serverController = value;
}
public static IModeController ModeController { get; private set; }
public static bool NttTested;
private static readonly NTTController NTTController = new NTTController();
private static IServerController _serverController;
/// <summary>
/// 启动
@@ -27,24 +35,36 @@ namespace Netch.Controllers
{
Logging.Info($"启动主控制器: {server.Type} [{mode.Type}]{mode.Remark}");
if (server.IsSocks5() && mode.Type == 4)
if (server is Socks5 && mode.Type == 4)
{
return false;
}
// 刷新DNS缓存
NativeMethods.FlushDNSResolverCache();
if (!Utils.Utils.SearchOutboundAdapter(false))
try
{
WebUtil.BestLocalEndPoint(new IPEndPoint(0x72727272, 53));
}
catch (Exception)
{
MessageBoxX.Show("No internet connection");
return false;
}
if (Global.Settings.ResolveServerHostname && DNS.Lookup(server.Hostname) == null)
{
MessageBoxX.Show("Lookup Server hostname failed");
return false;
}
// 添加Netch到防火墙
_ = Task.Run(Firewall.AddNetchFwRules);
try
{
if (!await StartServer(server, mode))
if (!await Task.Run(() => StartServer(server, mode, ref _serverController)))
{
throw new StartFailedException();
}
@@ -54,7 +74,7 @@ namespace Netch.Controllers
throw new StartFailedException();
}
if (ModeController.TestNatRequired)
if (mode.TestNatRequired)
NatTest();
return true;
@@ -88,23 +108,23 @@ namespace Netch.Controllers
}
}
private static async Task<bool> StartServer(Server server, Mode mode)
private static bool StartServer(Server server, Mode mode, ref IServerController controller)
{
if (server.IsSocks5())
controller = ServerHelper.GetUtilByTypeName(server.Type).GetController();
if (controller is Guard instanceController)
{
return true;
Utils.Utils.KillProcessByName(instanceController.MainFile);
}
ServerController = Servers.GetUtilByTypeName(server.Type).GetController();
PortCheckAndShowMessageBox(controller.Socks5LocalPort(), "Socks5");
Utils.Utils.KillProcessByName(ServerController.MainFile);
PortCheckAndShowMessageBox(Global.Settings.Socks5LocalPort, "Socks5");
Global.MainForm.StatusText(i18N.Translate("Starting ", ServerController.Name));
if (await Task.Run(() => ServerController.Start(server, mode)))
Global.MainForm.StatusText(i18N.TranslateFormat("Starting {0}", controller.Name));
if (controller.Start(in server, mode))
{
UsingPorts.Add(StatusPortInfoText.Socks5Port = Global.Settings.Socks5LocalPort);
StatusPortInfoText.ShareLan = Global.Settings.LocalAddress == "0.0.0.0";
UsingPorts.Add(StatusPortInfoText.Socks5Port = controller.Socks5LocalPort());
StatusPortInfoText.ShareLan = controller.LocalAddress == "0.0.0.0";
return true;
}
@@ -113,45 +133,20 @@ namespace Netch.Controllers
private static async Task<bool> StartMode(Server server, Mode mode)
{
var port = 0;
switch (mode.Type)
ModeController = ModeHelper.GetModeControllerByType(mode.Type, out var port, out var portName, out var portType);
if (port != null)
{
case 0:
ModeController = new NFController();
PortCheckAndShowMessageBox(port = Global.Settings.RedirectorTCPPort, "Redirector TCP");
break;
case 1:
case 2:
ModeController = new TUNTAPController();
break;
case 3:
case 5:
ModeController = new HTTPController();
PortCheckAndShowMessageBox(port = Global.Settings.HTTPLocalPort, "HTTP");
break;
case 4:
return true;
default:
Logging.Error("未知模式类型");
return false;
PortCheckAndShowMessageBox((ushort) port, portName, portType);
UsingPorts.Add((ushort) port);
}
Global.MainForm.StatusText(i18N.Translate("Starting ", ModeController.Name));
if (await Task.Run(() => ModeController.Start(server, mode)))
if (ModeController != null)
{
switch (mode.Type)
{
case 3:
case 5:
StatusPortInfoText.HttpPort = port;
break;
}
UsingPorts.Add(port);
return true;
Global.MainForm.StatusText(i18N.TranslateFormat("Starting {0}", ModeController.Name));
return await Task.Run(() => ModeController.Start(mode));
}
return false;
return true;
}
/// <summary>
@@ -160,6 +155,7 @@ namespace Netch.Controllers
public static async Task Stop()
{
UsingPorts.Clear();
StatusPortInfoText.Reset();
_ = Task.Run(() => NTTController.Stop());
@@ -169,6 +165,8 @@ namespace Netch.Controllers
Task.Run(() => ModeController?.Stop()),
};
await Task.WhenAll(tasks);
ModeController = null;
ServerController = null;
}
@@ -180,7 +178,7 @@ namespace Netch.Controllers
/// <param name="portName">端口用途名称</param>
/// <param name="portType"></param>
/// <exception cref="PortInUseException"></exception>
private static void PortCheckAndShowMessageBox(int port, string portName, PortType portType = PortType.Both)
private static void PortCheckAndShowMessageBox(ushort port, string portName, PortType portType = PortType.Both)
{
if (PortInUse(port, portType))
{

View File

@@ -1,410 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Netch.Models;
using Netch.Utils;
namespace Netch.Controllers
{
public class TUNTAPController : ModeController
{
public override bool TestNatRequired { get; } = true;
// ByPassLan IP
private readonly List<string> _bypassLanIPs = new List<string>
{"10.0.0.0/8", "172.16.0.0/16", "192.168.0.0/16"};
private Mode _savedMode = new Mode();
private Server _savedServer = new Server();
/// <summary>
/// 服务器 IP 地址
/// </summary>
private IPAddress[] _serverAddresses = new IPAddress[0];
/// <summary>
/// 本地 DNS 服务控制器
/// </summary>
public DNSController pDNSController = new DNSController();
public TUNTAPController()
{
Name = "tun2socks";
MainFile = "tun2socks.exe";
StartedKeywords.Add("Running");
StoppedKeywords.AddRange(new[] {"failed", "invalid vconfig file"});
}
/// <summary>
/// 配置 TUNTAP 适配器
/// </summary>
private bool Configure()
{
// 查询服务器 IP 地址
var destination = Dns.GetHostAddressesAsync(_savedServer.Hostname);
if (destination.Wait(1000))
{
if (destination.Result.Length == 0) return false;
_serverAddresses = destination.Result;
}
// 搜索出口
return SearchTapAdapter();
}
private readonly List<IPNetwork> _directIPs = new List<IPNetwork>();
private readonly List<IPNetwork> _proxyIPs = new List<IPNetwork>();
/// <summary>
/// 设置绕行规则
/// </summary>
/// <returns>是否设置成功</returns>
private bool SetupRouteTable()
{
Logging.Info("收集路由表规则");
Global.MainForm.StatusText(i18N.Translate("SetupBypass"));
Logging.Info("绕行 → 全局绕过 IP");
_directIPs.AddRange(Global.Settings.BypassIPs.Select(IPNetwork.Parse));
Logging.Info("绕行 → 服务器 IP");
_directIPs.AddRange(_serverAddresses.Where(address => !IPAddress.IsLoopback(address))
.Select(address => IPNetwork.Parse(address.ToString(), 32)));
Logging.Info("绕行 → 局域网 IP");
_directIPs.AddRange(_bypassLanIPs.Select(IPNetwork.Parse));
switch (_savedMode.Type)
{
case 1:
// 代理规则
Logging.Info("代理 → 规则 IP");
_proxyIPs.AddRange(_savedMode.Rule.Select(IPNetwork.Parse));
//处理 NAT 类型检测,由于协议的原因,无法仅通过域名确定需要代理的 IP自己记录解析了返回的 IP仅支持默认检测服务器
if (Global.Settings.STUN_Server == "stun.stunprotocol.org")
try
{
Logging.Info("代理 → STUN 服务器 IP");
_proxyIPs.AddRange(new[]
{
Dns.GetHostAddresses(Global.Settings.STUN_Server)[0],
Dns.GetHostAddresses("stunresponse.coldthunder11.com")[0]
}.Select(ip => IPNetwork.Parse(ip.ToString(), 32)));
}
catch
{
Logging.Info("NAT 类型测试域名解析失败,将不会被添加到代理列表");
}
if (Global.Settings.TUNTAP.ProxyDNS)
{
Logging.Info("代理 → 自定义 DNS");
if (Global.Settings.TUNTAP.UseCustomDNS)
{
var dns = string.Empty;
foreach (var value in Global.Settings.TUNTAP.DNS)
{
dns += value;
dns += ',';
}
dns = dns.Trim();
dns = dns.Substring(0, dns.Length - 1);
RouteAction(Action.Create, dns, 32, RouteType.TUNTAP);
}
else
{
_proxyIPs.AddRange(
new[] {"1.1.1.1", "8.8.8.8", "9.9.9.9", "185.222.222.222"}.Select(ip =>
IPNetwork.Parse(ip, 32)));
}
}
break;
case 2:
// 绕过规则
// 将 TUN/TAP 网卡权重放到最高
Process.Start(new ProcessStartInfo
{
FileName = "netsh",
Arguments = $"interface ip set interface {Global.TUNTAP.Index} metric=0",
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = true,
CreateNoWindow = true
}
);
if (_savedMode.BypassChina)
{
Logging.Info("绕行 → 中国 IP");
foreach (var str in File.ReadAllLines("bin\\china_ip_list", Encoding.UTF8))
{
if (IPNetwork.TryParse(str, out var entry))
{
_directIPs.Add(entry);
}
}
}
Logging.Info("绕行 → 规则 IP");
_directIPs.AddRange(_savedMode.Rule.Select(IPNetwork.Parse));
Logging.Info("代理 → 全局");
if (!RouteAction(Action.Create, IPNetwork.Parse("0.0.0.0", 0), RouteType.TUNTAP))
{
State = State.Stopped;
return false;
}
break;
}
Logging.Info("设置路由规则");
RouteAction(Action.Create, _directIPs, RouteType.Gateway);
RouteAction(Action.Create, _proxyIPs, RouteType.TUNTAP);
return true;
}
/// <summary>
/// 清除绕行规则
/// </summary>
private bool ClearRouteTable()
{
switch (_savedMode.Type)
{
case 1:
break;
case 2:
RouteAction(Action.Delete, "0.0.0.0", 0, RouteType.TUNTAP, 10);
break;
}
RouteAction(Action.Delete, _directIPs, RouteType.Gateway);
RouteAction(Action.Delete, _proxyIPs, RouteType.TUNTAP);
_directIPs.Clear();
_proxyIPs.Clear();
return true;
}
public override bool Start(Server s, Mode mode)
{
_savedMode = mode;
_savedServer = s;
if (!Configure()) return false;
SetupRouteTable();
var adapterName = TUNTAP.GetName(Global.TUNTAP.ComponentID);
string dns;
if (Global.Settings.TUNTAP.UseCustomDNS)
{
if (Global.Settings.TUNTAP.DNS.Any())
{
dns = Global.Settings.TUNTAP.DNS.Aggregate((current, ip) => $"{current},{ip}");
}
else
{
Global.Settings.TUNTAP.DNS.Add("1.1.1.1");
dns = "1.1.1.1";
}
}
else
{
var _ = pDNSController.Start();
dns = "127.0.0.1";
}
var argument = new StringBuilder();
if (s.IsSocks5())
argument.Append($"-proxyServer {s.Hostname}:{s.Port} ");
else
argument.Append($"-proxyServer 127.0.0.1:{Global.Settings.Socks5LocalPort} ");
argument.Append(
$"-tunAddr {Global.Settings.TUNTAP.Address} -tunMask {Global.Settings.TUNTAP.Netmask} -tunGw {Global.Settings.TUNTAP.Gateway} -tunDns {dns} -tunName \"{adapterName}\" ");
if (Global.Settings.TUNTAP.UseFakeDNS && Global.Flags.SupportFakeDns)
argument.Append("-fakeDns ");
return StartInstanceAuto(argument.ToString(), ProcessPriorityClass.RealTime);
}
/// <summary>
/// TUN/TAP停止
/// </summary>
public override void Stop()
{
var tasks = new[]
{
Task.Factory.StartNew(StopInstance),
Task.Factory.StartNew(ClearRouteTable),
Task.Factory.StartNew(pDNSController.Stop)
};
Task.WaitAll(tasks);
}
public bool TestFakeDNS()
{
var exited = false;
var helpStr = new StringBuilder();
try
{
void OnOutputDataReceived(object sender,DataReceivedEventArgs e)
{
if (e.Data == null)
{
exited = true;
return;
}
helpStr.Append(e.Data);
}
InitInstance("-h");
// Instance.OutputDataReceived += OnOutputDataReceived;
Instance.ErrorDataReceived += OnOutputDataReceived;
Instance.Start();
Instance.BeginOutputReadLine();
Instance.BeginErrorReadLine();
while (!exited)
{
Thread.Sleep(200);
}
return helpStr.ToString().Contains("-fakeDns");
}
catch
{
return false;
}
}
/// <summary>
/// 搜索出口和TUNTAP适配器
/// </summary>
public static bool SearchTapAdapter()
{
// 搜索 TUN/TAP 适配器的索引
if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
{
Logging.Info("找不到 TAP 适配器");
if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"),
confirm: true) == DialogResult.OK)
{
TUNTAP.addtap();
// 给点时间不然立马安装完毕就查找适配器可能会导致找不到适配器ID
Thread.Sleep(1000);
if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
{
Logging.Error("找不到 TAP 适配器,驱动可能安装失败");
return false;
}
}
else
{
Logging.Info("取消安装 TAP 驱动 ");
return false;
}
}
// 根据 ComponentID 寻找 Tap适配器
try
{
var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
Global.TUNTAP.Adapter = adapter;
Global.TUNTAP.Index = adapter.GetIPProperties().GetIPv4Properties().Index;
Logging.Info(
$"TAP 适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
}
catch (Exception e)
{
var msg = e switch
{
InvalidOperationException _ => $"找不到标识符为 {Global.TUNTAP.ComponentID} 的 TAP 适配器: {e.Message}",
NetworkInformationException _ => $"获取 Tap 适配器信息错误: {e.Message}",
_ => $"Tap 适配器其他异常: {e}"
};
Logging.Error(msg);
return false;
}
return true;
}
private enum RouteType
{
Gateway,
TUNTAP
}
private enum Action
{
Create,
Delete
}
private static void RouteAction(Action action, IEnumerable<IPNetwork> ipNetworks, RouteType routeType,
int metric = 0)
{
foreach (var address in ipNetworks)
{
RouteAction(action, address, routeType, metric);
}
}
private static bool RouteAction(Action action, string address, byte cidr, RouteType routeType, int metric = 0)
{
return RouteAction(action, IPNetwork.Parse(address, cidr), routeType, metric);
}
private static bool RouteAction(Action action, IPNetwork ipNetwork, RouteType routeType, int metric = 0)
{
string gateway;
int index;
switch (routeType)
{
case RouteType.Gateway:
gateway = Global.Outbound.Gateway.ToString();
index = Global.Outbound.Index;
break;
case RouteType.TUNTAP:
gateway = Global.Settings.TUNTAP.Gateway;
index = Global.TUNTAP.Index;
break;
default:
throw new ArgumentOutOfRangeException(nameof(routeType), routeType, null);
}
var result = action switch
{
Action.Create => NativeMethods.CreateRoute(ipNetwork.Network.ToString(), ipNetwork.Cidr, gateway, index,
metric),
Action.Delete => NativeMethods.DeleteRoute(ipNetwork.Network.ToString(), ipNetwork.Cidr, gateway, index,
metric),
_ => throw new ArgumentOutOfRangeException(nameof(action), action, null)
};
if (!result)
{
Logging.Warning($"{action} Route on {routeType} Adapter failed: {ipNetwork} metric {metric}");
}
return result;
}
}
}

View File

@@ -3,58 +3,60 @@ using System.IO;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading.Tasks;
using Netch.Forms;
using Netch.Models;
using Netch.Servers.Socks5;
using Netch.Utils;
using nfapinet;
namespace Netch.Controllers
{
public class NFController : ModeController
public class NFController : IModeController
{
public override bool TestNatRequired { get; } = true;
private static readonly ServiceController NFService = new ServiceController("netfilter2");
private static readonly string BinDriver = string.Empty;
private static readonly string SystemDriver = $"{Environment.SystemDirectory}\\drivers\\netfilter2.sys";
private static string _sysDns;
public string Name { get; } = "Redirector";
static NFController()
{
string fileName;
switch ($"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor}")
{
case "10.0":
BinDriver = "Win-10.sys";
fileName = "Win-10.sys";
break;
case "6.3":
case "6.2":
BinDriver = "Win-8.sys";
fileName = "Win-8.sys";
break;
case "6.1":
case "6.0":
BinDriver = "Win-7.sys";
fileName = "Win-7.sys";
break;
default:
Logging.Error($"不支持的系统版本:{Environment.OSVersion.Version}");
return;
}
BinDriver = "bin\\" + BinDriver;
BinDriver = "bin\\" + fileName;
}
public NFController()
public bool Start(in Mode mode)
{
Name = "Redirector";
}
var binFileVersion = Utils.Utils.GetFileVersion(BinDriver);
var systemFileVersion = Utils.Utils.GetFileVersion(SystemDriver);
public override bool Start(Server s, Mode mode)
{
Logging.Info("内置驱动版本: " + Utils.Utils.FileVersion(BinDriver));
if (Utils.Utils.FileVersion(SystemDriver) != Utils.Utils.FileVersion(BinDriver))
Logging.Info("内置驱动版本: " + binFileVersion);
Logging.Info("系统驱动版本: " + systemFileVersion);
if (!systemFileVersion.Equals(binFileVersion))
{
if (File.Exists(SystemDriver))
{
Logging.Info("系统驱动版本: " + Utils.Utils.FileVersion(SystemDriver));
Logging.Info("更新驱动");
UninstallDriver();
}
@@ -63,31 +65,14 @@ namespace Netch.Controllers
return false;
}
aio_dial((int) NameList.TYPE_CLRNAME, "");
foreach (var rule in mode.Rule)
{
aio_dial((int) NameList.TYPE_ADDNAME, rule);
}
aio_dial((int) NameList.TYPE_FILTERLOOPBACK, "false");
aio_dial((int) NameList.TYPE_FILTERTCP, "true");
aio_dial((int) NameList.TYPE_FILTERUDP, "true");
aio_dial((int) NameList.TYPE_TCPLISN, Global.Settings.RedirectorTCPPort.ToString());
aio_dial((int) NameList.TYPE_ADDNAME, "NTT.exe");
SetServer(MainController.ServerController, PortType.Both);
if (s.IsSocks5())
{
var result = DNS.Lookup(s.Hostname);
if (result == null)
{
Logging.Info("无法解析服务器 IP 地址");
return false;
}
aio_dial((int) NameList.TYPE_TCPHOST, $"{result}:{s.Port}");
aio_dial((int) NameList.TYPE_UDPHOST, $"{result}:{s.Port}");
}
else
{
aio_dial((int) NameList.TYPE_TCPHOST, $"127.0.0.1:{Global.Settings.Socks5LocalPort}");
aio_dial((int) NameList.TYPE_UDPHOST, $"127.0.0.1:{Global.Settings.Socks5LocalPort}");
}
SetName(mode);
if (Global.Settings.ModifySystemDNS)
{
@@ -99,7 +84,47 @@ namespace Netch.Controllers
return aio_init();
}
public override void Stop()
private void SetServer(in IServerController controller, in PortType portType)
{
if (portType == PortType.Both)
{
SetServer(controller, PortType.TCP);
SetServer(controller, PortType.UDP);
return;
}
var offset = portType == PortType.UDP ? UdpNameListOffset : 0;
aio_dial((int) NameList.TYPE_TCPTYPE + offset, "Socks5");
if (controller.Server is Socks5 socks5)
{
aio_dial((int) NameList.TYPE_TCPHOST + offset, $"{socks5.AutoResolveHostname()}:{socks5.Port}");
aio_dial((int) NameList.TYPE_TCPUSER + offset, socks5.Username ?? string.Empty);
aio_dial((int) NameList.TYPE_TCPPASS + offset, socks5.Password ?? string.Empty);
}
else
{
aio_dial((int) NameList.TYPE_TCPHOST + offset, $"127.0.0.1:{controller.Socks5LocalPort()}");
aio_dial((int) NameList.TYPE_TCPUSER + offset, string.Empty);
aio_dial((int) NameList.TYPE_TCPPASS + offset, string.Empty);
}
aio_dial((int) NameList.TYPE_TCPMETH + offset, string.Empty);
}
private void SetName(Mode mode)
{
aio_dial((int) NameList.TYPE_CLRNAME, "");
foreach (var rule in mode.FullRule)
{
aio_dial((int) NameList.TYPE_ADDNAME, rule);
}
aio_dial((int) NameList.TYPE_ADDNAME, "NTT.exe");
}
public void Stop()
{
Task.Run(() =>
{
@@ -113,6 +138,8 @@ namespace Netch.Controllers
#region NativeMethods
private const int UdpNameListOffset = (int) NameList.TYPE_UDPTYPE - (int) NameList.TYPE_TCPTYPE;
[DllImport("Redirector.bin", CallingConvention = CallingConvention.Cdecl)]
public static extern bool aio_dial(int name, [MarshalAs(UnmanagedType.LPWStr)] string value);
@@ -128,6 +155,28 @@ namespace Netch.Controllers
[DllImport("Redirector.bin", CallingConvention = CallingConvention.Cdecl)]
public static extern ulong aio_getDL();
public enum NameList : int
{
TYPE_FILTERLOOPBACK,
TYPE_FILTERTCP,
TYPE_FILTERUDP,
TYPE_TCPLISN,
TYPE_TCPTYPE,
TYPE_TCPHOST,
TYPE_TCPUSER,
TYPE_TCPPASS,
TYPE_TCPMETH,
TYPE_UDPTYPE,
TYPE_UDPHOST,
TYPE_UDPUSER,
TYPE_UDPPASS,
TYPE_UDPMETH,
TYPE_ADDNAME,
TYPE_BYPNAME,
TYPE_CLRNAME
}
#endregion
#region Utils
@@ -171,7 +220,7 @@ namespace Netch.Controllers
/// <returns>是否成功卸载</returns>
public static bool UninstallDriver()
{
Global.MainForm.StatusText(i18N.Translate("Uninstalling NF Service"));
Global.MainForm.StatusText(i18N.TranslateFormat("Uninstalling {0}", "NF Service"));
Logging.Info("卸载 NF 驱动");
try
{

View File

@@ -5,18 +5,14 @@ using Netch.Utils;
namespace Netch.Controllers
{
public class NTTController : Controller
public class NTTController : Guard, IController
{
private string _localEnd;
private string _publicEnd;
private string _result;
private string _bindingTest;
public NTTController()
{
Name = "NTT";
MainFile = "NTT.exe";
}
public override string Name { get; protected set; } = "NTT";
public override string MainFile { get; protected set; } = "NTT.exe";
/// <summary>
/// 启动 NatTypeTester
@@ -55,6 +51,7 @@ namespace Netch.Controllers
}
}
private new void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (string.IsNullOrEmpty(e.Data)) return;

View File

@@ -1,26 +1,38 @@
using System.IO;
using System.Text;
using Netch.Models;
using Netch.Servers.Socks5;
namespace Netch.Controllers
{
public class PrivoxyController : Controller
public class PrivoxyController : Guard, IController
{
public PrivoxyController()
{
Name = "Privoxy";
MainFile = "Privoxy.exe";
RedirectStd = false;
}
public override string Name { get; protected set; } = "Privoxy";
public override string MainFile { get; protected set; } = "Privoxy.exe";
public bool Start(Server server, Mode mode)
{
var text = File.ReadAllText("bin\\default.conf")
.Replace("_BIND_PORT_", Global.Settings.HTTPLocalPort.ToString())
.Replace("_DEST_PORT_", (server.IsSocks5() ? server.Port : Global.Settings.Socks5LocalPort).ToString())
.Replace("0.0.0.0", Global.Settings.LocalAddress);
if (server.IsSocks5())
text = text.Replace("/ 127.0.0.1", $"/ {server.Hostname}");
File.WriteAllText("data\\privoxy.conf", text);
var text = new StringBuilder(File.ReadAllText("bin\\default.conf"));
text.Replace("_BIND_PORT_", Global.Settings.HTTPLocalPort.ToString());
text.Replace("0.0.0.0", Global.Settings.LocalAddress); /* BIND_HOST */
if (server is Socks5 socks5 && !socks5.Auth())
{
text.Replace("/ 127.0.0.1", $"/ {server.AutoResolveHostname()}"); /* DEST_HOST */
text.Replace("_DEST_PORT_", socks5.Port.ToString());
}
text.Replace("_DEST_PORT_", Global.Settings.Socks5LocalPort.ToString());
File.WriteAllText("data\\privoxy.conf", text.ToString());
return StartInstanceAuto("..\\data\\privoxy.conf");
}

View File

@@ -0,0 +1,403 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Netch.Models;
using Netch.Servers.Socks5;
using Netch.Utils;
namespace Netch.Controllers
{
public class TUNTAPController : Guard, IModeController
{
private Mode _savedMode = new Mode();
private Server _savedServer = new Server();
/// <summary>
/// 服务器 IP 地址
/// </summary>
private IPAddress _serverAddresses;
/// <summary>
/// 本地 DNS 服务控制器
/// </summary>
public DNSController DNSController = new DNSController();
public TUNTAPController()
{
StartedKeywords.Add("Running");
StoppedKeywords.AddRange(new[] {"failed", "invalid vconfig file"});
}
public override string Name { get; protected set; } = "tun2socks";
public override string MainFile { get; protected set; } = "tun2socks.exe";
public bool Start(in Mode mode)
{
_savedMode = mode;
_savedServer = MainController.ServerController.Server;
// 查询服务器 IP 地址
_serverAddresses = DNS.Lookup(_savedServer.Hostname);
// 查找出口适配器
if (!Utils.Utils.SearchOutboundAdapter())
{
return false;
}
// 查找并安装 TAP 适配器
if (!SearchTapAdapter())
{
if (!AddTap())
{
Logging.Error("Tap 适配器安装失败");
return false;
}
SearchTapAdapter();
}
SetupRouteTable();
string dns;
if (Global.Settings.TUNTAP.UseCustomDNS)
{
if (Global.Settings.TUNTAP.DNS.Any())
{
dns = Global.Settings.TUNTAP.DNS.Aggregate((current, ip) => $"{current},{ip}");
}
else
{
Global.Settings.TUNTAP.DNS.Add("1.1.1.1");
dns = "1.1.1.1";
}
}
else
{
var _ = DNSController.Start();
dns = "127.0.0.1";
}
var argument = new StringBuilder();
if (_savedServer is Socks5 socks5 && !socks5.Auth())
argument.Append($"-proxyServer {_serverAddresses}:{_savedServer.Port} ");
else
argument.Append($"-proxyServer 127.0.0.1:{Global.Settings.Socks5LocalPort} ");
argument.Append(
$"-tunAddr {Global.Settings.TUNTAP.Address} -tunMask {Global.Settings.TUNTAP.Netmask} -tunGw {Global.Settings.TUNTAP.Gateway} -tunDns {dns} -tunName \"{TUNTAP.GetName(Global.TUNTAP.ComponentID)}\" ");
if (Global.Settings.TUNTAP.UseFakeDNS && Global.Flags.SupportFakeDns)
argument.Append("-fakeDns ");
return StartInstanceAuto(argument.ToString(), ProcessPriorityClass.RealTime);
}
/// <summary>
/// TUN/TAP停止
/// </summary>
public override void Stop()
{
var tasks = new[]
{
Task.Factory.StartNew(StopInstance),
Task.Factory.StartNew(ClearRouteTable),
Task.Factory.StartNew(DNSController.Stop)
};
Task.WaitAll(tasks);
}
private readonly List<string> _directIPs = new List<string>();
private readonly List<string> _proxyIPs = new List<string>();
/// <summary>
/// 设置绕行规则
/// </summary>
/// <returns>是否设置成功</returns>
private void SetupRouteTable()
{
Global.MainForm.StatusText(i18N.Translate("SetupBypass"));
Logging.Info("设置路由规则");
#region Rule IPs
if (_savedMode.Type == 1)
{
// 代理规则
Logging.Info("代理 → 规则 IP");
RouteAction(Action.Create, _savedMode.FullRule, RouteType.TUNTAP);
//处理 NAT 类型检测,由于协议的原因,无法仅通过域名确定需要代理的 IP自己记录解析了返回的 IP仅支持默认检测服务器
if (Global.Settings.STUN_Server == "stun.stunprotocol.org")
{
try
{
Logging.Info("代理 → STUN 服务器 IP");
RouteAction(Action.Create,
new[]
{
Dns.GetHostAddresses(Global.Settings.STUN_Server)[0],
Dns.GetHostAddresses("stunresponse.coldthunder11.com")[0]
}.Select(ip => $"{ip}/32"),
RouteType.TUNTAP);
}
catch
{
Logging.Info("NAT 类型测试域名解析失败,将不会被添加到代理列表");
}
}
if (Global.Settings.TUNTAP.ProxyDNS)
{
Logging.Info("代理 → 自定义 DNS");
if (Global.Settings.TUNTAP.UseCustomDNS)
{
RouteAction(Action.Create,
Global.Settings.TUNTAP.DNS.Select(ip => $"{ip}/32"),
RouteType.TUNTAP);
}
else
{
RouteAction(Action.Create,
new[] {"1.1.1.1", "8.8.8.8", "9.9.9.9", "185.222.222.222"}.Select(ip => $"{ip}/32"),
RouteType.TUNTAP);
}
}
}
else if (_savedMode.Type == 2)
{
// 绕过规则
// 将 TUN/TAP 网卡权重放到最高
Process.Start(new ProcessStartInfo
{
FileName = "netsh",
Arguments = $"interface ip set interface {Global.TUNTAP.Index} metric=0",
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = true,
CreateNoWindow = true
}
);
Logging.Info("绕行 → 规则 IP");
RouteAction(Action.Create, _savedMode.FullRule, RouteType.Outbound);
}
#endregion
Logging.Info("绕行 → 服务器 IP");
if (!IPAddress.IsLoopback(_serverAddresses))
RouteAction(Action.Create, $"{_serverAddresses}/32", RouteType.Outbound);
Logging.Info("绕行 → 全局绕过 IP");
RouteAction(Action.Create, Global.Settings.BypassIPs, RouteType.Outbound);
if (_savedMode.Type == 2)
{
// 绕过规则
Logging.Info("代理 → 全局");
RouteAction(Action.Create, "0.0.0.0/0", RouteType.TUNTAP);
}
}
/// <summary>
/// 清除绕行规则
/// </summary>
private bool ClearRouteTable()
{
RouteAction(Action.Delete, _directIPs, RouteType.Outbound);
RouteAction(Action.Delete, _proxyIPs, RouteType.TUNTAP);
_directIPs.Clear();
_proxyIPs.Clear();
return true;
}
public bool TestFakeDNS()
{
var exited = false;
var helpStr = new StringBuilder();
try
{
void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
exited = true;
return;
}
helpStr.Append(e.Data);
}
InitInstance("-h");
// Instance.OutputDataReceived += OnOutputDataReceived;
Instance.ErrorDataReceived += OnOutputDataReceived;
Instance.Start();
Instance.BeginOutputReadLine();
Instance.BeginErrorReadLine();
while (!exited)
{
Thread.Sleep(200);
}
return helpStr.ToString().Contains("-fakeDns");
}
catch
{
return false;
}
}
/// <summary>
/// 搜索出口和TUNTAP适配器
/// </summary>
public static bool SearchTapAdapter()
{
Global.TUNTAP.Adapter = null;
Global.TUNTAP.Index = -1;
Global.TUNTAP.ComponentID = TUNTAP.GetComponentID();
// 搜索 TUN/TAP 适配器的索引
if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID))
{
Logging.Info("TAP 适配器未安装");
return false;
}
// 根据 ComponentID 寻找 Tap适配器
try
{
var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
Global.TUNTAP.Adapter = adapter;
Global.TUNTAP.Index = adapter.GetIPProperties().GetIPv4Properties().Index;
Logging.Info(
$"TAP 适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
return true;
}
catch (Exception e)
{
var msg = e switch
{
InvalidOperationException _ => $"找不到标识符为 {Global.TUNTAP.ComponentID} 的 TAP 适配器: {e.Message}",
NetworkInformationException _ => $"获取 Tap 适配器信息错误: {e.Message}",
_ => $"Tap 适配器其他异常: {e}"
};
Logging.Error(msg);
return false;
}
}
private static bool AddTap()
{
TUNTAP.addtap();
// 给点时间不然立马安装完毕就查找适配器可能会导致找不到适配器ID
Thread.Sleep(1000);
if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
{
Logging.Error("找不到 TAP 适配器,驱动可能安装失败");
return false;
}
return true;
}
private enum RouteType
{
Outbound,
TUNTAP
}
private enum Action
{
Create,
Delete
}
private void RouteAction(Action action, in IEnumerable<string> ipNetworks, RouteType routeType,
int metric = 0)
{
foreach (var address in ipNetworks)
{
RouteAction(action, address, routeType, metric);
}
}
private bool RouteAction(Action action, in string ipNetwork, RouteType routeType, int metric = 0)
{
string gateway;
int index;
switch (routeType)
{
case RouteType.Outbound:
gateway = Global.Outbound.Gateway.ToString();
index = Global.Outbound.Index;
break;
case RouteType.TUNTAP:
gateway = Global.Settings.TUNTAP.Gateway;
index = Global.TUNTAP.Index;
break;
default:
throw new ArgumentOutOfRangeException(nameof(routeType), routeType, null);
}
string network;
ushort cidr;
try
{
var s = ipNetwork.Split('/');
network = s[0];
cidr = ushort.Parse(s[1]);
}
catch
{
Logging.Warning($"Failed to parse rule {ipNetwork}");
return false;
}
bool result;
switch (action)
{
case Action.Create:
{
result = NativeMethods.CreateRoute(network, cidr, gateway, index, metric);
switch (routeType)
{
case RouteType.Outbound:
_directIPs.Add(ipNetwork);
break;
case RouteType.TUNTAP:
_proxyIPs.Add(ipNetwork);
break;
}
break;
}
case Action.Delete:
result = NativeMethods.DeleteRoute(network, cidr, gateway, index, metric);
break;
default:
throw new ArgumentOutOfRangeException(nameof(action), action, null);
}
if (!result)
{
Logging.Warning($"Failed to {action} Route on {routeType} Adapter: {ipNetwork} metric {metric}");
}
return result;
}
}
}

View File

@@ -15,8 +15,8 @@ namespace Netch.Controllers
public const string Name = @"Netch";
public const string Copyright = @"Copyright © 2019 - 2020";
public const string AssemblyVersion = @"1.6.0";
private const string Suffix = @"Beta1";
public const string AssemblyVersion = @"1.6.4";
private const string Suffix = @"";
public static readonly string Version = $"{AssemblyVersion}{(string.IsNullOrEmpty(Suffix) ? "" : $"-{Suffix}")}";

View File

@@ -45,7 +45,7 @@
this.UpdateACLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.updateACLWithProxyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.UninstallServiceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.reinstallTapDriverToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.UninstallTapDriverToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.HelpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.CheckForUpdatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fAQToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
@@ -85,6 +85,8 @@
this.SettingsButton = new System.Windows.Forms.Button();
this.ProfileGroupBox = new System.Windows.Forms.GroupBox();
this.ProfileTable = new System.Windows.Forms.TableLayoutPanel();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.ButtomControlContainerControl = new System.Windows.Forms.ContainerControl();
this.MenuStrip.SuspendLayout();
this.ConfigurationGroupBox.SuspendLayout();
this.configLayoutPanel.SuspendLayout();
@@ -99,6 +101,8 @@
this.StatusStrip.SuspendLayout();
this.NotifyMenu.SuspendLayout();
this.ProfileGroupBox.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.ButtomControlContainerControl.SuspendLayout();
this.SuspendLayout();
//
// MenuStrip
@@ -118,7 +122,7 @@
this.MenuStrip.Location = new System.Drawing.Point(0, 0);
this.MenuStrip.Name = "MenuStrip";
this.MenuStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
this.MenuStrip.Size = new System.Drawing.Size(733, 26);
this.MenuStrip.Size = new System.Drawing.Size(740, 26);
this.MenuStrip.TabIndex = 0;
//
// ServerToolStripMenuItem
@@ -193,7 +197,7 @@
this.UpdateACLToolStripMenuItem,
this.updateACLWithProxyToolStripMenuItem,
this.UninstallServiceToolStripMenuItem,
this.reinstallTapDriverToolStripMenuItem});
this.UninstallTapDriverToolStripMenuItem});
this.OptionsToolStripMenuItem.Margin = new System.Windows.Forms.Padding(0, 0, 0, 1);
this.OptionsToolStripMenuItem.Name = "OptionsToolStripMenuItem";
this.OptionsToolStripMenuItem.Size = new System.Drawing.Size(66, 21);
@@ -202,44 +206,44 @@
// OpenDirectoryToolStripMenuItem
//
this.OpenDirectoryToolStripMenuItem.Name = "OpenDirectoryToolStripMenuItem";
this.OpenDirectoryToolStripMenuItem.Size = new System.Drawing.Size(219, 22);
this.OpenDirectoryToolStripMenuItem.Size = new System.Drawing.Size(220, 22);
this.OpenDirectoryToolStripMenuItem.Text = "Open Directory";
this.OpenDirectoryToolStripMenuItem.Click += new System.EventHandler(this.OpenDirectoryToolStripMenuItem_Click);
//
// CleanDNSCacheToolStripMenuItem
//
this.CleanDNSCacheToolStripMenuItem.Name = "CleanDNSCacheToolStripMenuItem";
this.CleanDNSCacheToolStripMenuItem.Size = new System.Drawing.Size(219, 22);
this.CleanDNSCacheToolStripMenuItem.Size = new System.Drawing.Size(220, 22);
this.CleanDNSCacheToolStripMenuItem.Text = "Clean DNS Cache";
this.CleanDNSCacheToolStripMenuItem.Click += new System.EventHandler(this.CleanDNSCacheToolStripMenuItem_Click);
//
// UpdateACLToolStripMenuItem
//
this.UpdateACLToolStripMenuItem.Name = "UpdateACLToolStripMenuItem";
this.UpdateACLToolStripMenuItem.Size = new System.Drawing.Size(219, 22);
this.UpdateACLToolStripMenuItem.Size = new System.Drawing.Size(220, 22);
this.UpdateACLToolStripMenuItem.Text = "Update ACL";
this.UpdateACLToolStripMenuItem.Click += new System.EventHandler(this.updateACLToolStripMenuItem_Click);
//
// updateACLWithProxyToolStripMenuItem
//
this.updateACLWithProxyToolStripMenuItem.Name = "updateACLWithProxyToolStripMenuItem";
this.updateACLWithProxyToolStripMenuItem.Size = new System.Drawing.Size(219, 22);
this.updateACLWithProxyToolStripMenuItem.Size = new System.Drawing.Size(220, 22);
this.updateACLWithProxyToolStripMenuItem.Text = "Update ACL with proxy";
this.updateACLWithProxyToolStripMenuItem.Click += new System.EventHandler(this.updateACLWithProxyToolStripMenuItem_Click);
//
// UninstallServiceToolStripMenuItem
//
this.UninstallServiceToolStripMenuItem.Name = "UninstallServiceToolStripMenuItem";
this.UninstallServiceToolStripMenuItem.Size = new System.Drawing.Size(219, 22);
this.UninstallServiceToolStripMenuItem.Size = new System.Drawing.Size(220, 22);
this.UninstallServiceToolStripMenuItem.Text = "Uninstall NF Service";
this.UninstallServiceToolStripMenuItem.Click += new System.EventHandler(this.UninstallServiceToolStripMenuItem_Click);
//
// reinstallTapDriverToolStripMenuItem
// UninstallTapDriverToolStripMenuItem
//
this.reinstallTapDriverToolStripMenuItem.Name = "reinstallTapDriverToolStripMenuItem";
this.reinstallTapDriverToolStripMenuItem.Size = new System.Drawing.Size(219, 22);
this.reinstallTapDriverToolStripMenuItem.Text = "Reinstall TUN/TAP driver";
this.reinstallTapDriverToolStripMenuItem.Click += new System.EventHandler(this.reinstallTapDriverToolStripMenuItem_Click);
this.UninstallTapDriverToolStripMenuItem.Name = "UninstallTapDriverToolStripMenuItem";
this.UninstallTapDriverToolStripMenuItem.Size = new System.Drawing.Size(220, 22);
this.UninstallTapDriverToolStripMenuItem.Text = "Uninstall TUN/TAP driver";
this.UninstallTapDriverToolStripMenuItem.Click += new System.EventHandler(this.reinstallTapDriverToolStripMenuItem_Click);
//
// HelpToolStripMenuItem
//
@@ -311,7 +315,7 @@
// ConfigurationGroupBox
//
this.ConfigurationGroupBox.Controls.Add(this.configLayoutPanel);
this.ConfigurationGroupBox.Location = new System.Drawing.Point(12, 28);
this.ConfigurationGroupBox.Location = new System.Drawing.Point(3, 3);
this.ConfigurationGroupBox.Name = "ConfigurationGroupBox";
this.ConfigurationGroupBox.Size = new System.Drawing.Size(709, 115);
this.ConfigurationGroupBox.TabIndex = 1;
@@ -320,6 +324,8 @@
//
// configLayoutPanel
//
this.configLayoutPanel.AutoSize = true;
this.configLayoutPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.configLayoutPanel.ColumnCount = 3;
this.configLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.configLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
@@ -336,9 +342,9 @@
this.configLayoutPanel.Location = new System.Drawing.Point(3, 19);
this.configLayoutPanel.Name = "configLayoutPanel";
this.configLayoutPanel.RowCount = 3;
this.configLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.configLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.configLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.configLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.configLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.configLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.configLayoutPanel.Size = new System.Drawing.Size(703, 93);
this.configLayoutPanel.TabIndex = 15;
//
@@ -346,7 +352,7 @@
//
this.ProfileLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.ProfileLabel.AutoSize = true;
this.ProfileLabel.Location = new System.Drawing.Point(3, 69);
this.ProfileLabel.Location = new System.Drawing.Point(3, 68);
this.ProfileLabel.Name = "ProfileLabel";
this.ProfileLabel.Size = new System.Drawing.Size(45, 17);
this.ProfileLabel.TabIndex = 10;
@@ -356,7 +362,7 @@
//
this.ModeLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.ModeLabel.AutoSize = true;
this.ModeLabel.Location = new System.Drawing.Point(3, 38);
this.ModeLabel.Location = new System.Drawing.Point(3, 36);
this.ModeLabel.Name = "ModeLabel";
this.ModeLabel.Size = new System.Drawing.Size(43, 17);
this.ModeLabel.TabIndex = 3;
@@ -366,7 +372,7 @@
//
this.ServerLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.ServerLabel.AutoSize = true;
this.ServerLabel.Location = new System.Drawing.Point(3, 7);
this.ServerLabel.Location = new System.Drawing.Point(3, 6);
this.ServerLabel.Name = "ServerLabel";
this.ServerLabel.Size = new System.Drawing.Size(45, 17);
this.ServerLabel.TabIndex = 0;
@@ -375,7 +381,7 @@
// ProfileNameText
//
this.ProfileNameText.Dock = System.Windows.Forms.DockStyle.Fill;
this.ProfileNameText.Location = new System.Drawing.Point(54, 65);
this.ProfileNameText.Location = new System.Drawing.Point(54, 63);
this.ProfileNameText.Name = "ProfileNameText";
this.ProfileNameText.Size = new System.Drawing.Size(546, 23);
this.ProfileNameText.TabIndex = 11;
@@ -387,7 +393,7 @@
this.ModeComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.ModeComboBox.FormattingEnabled = true;
this.ModeComboBox.IntegralHeight = false;
this.ModeComboBox.Location = new System.Drawing.Point(54, 34);
this.ModeComboBox.Location = new System.Drawing.Point(54, 33);
this.ModeComboBox.Name = "ModeComboBox";
this.ModeComboBox.Size = new System.Drawing.Size(546, 24);
this.ModeComboBox.TabIndex = 2;
@@ -481,7 +487,7 @@
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.tableLayoutPanel3.Controls.Add(this.EditModePictureBox, 0, 0);
this.tableLayoutPanel3.Controls.Add(this.DeleteModePictureBox, 1, 0);
this.tableLayoutPanel3.Location = new System.Drawing.Point(606, 34);
this.tableLayoutPanel3.Location = new System.Drawing.Point(606, 33);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
this.tableLayoutPanel3.RowCount = 1;
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
@@ -521,9 +527,9 @@
this.blankToolStripStatusLabel,
this.NatTypeStatusLabel,
this.NatTypeStatusLightLabel});
this.StatusStrip.Location = new System.Drawing.Point(0, 250);
this.StatusStrip.Location = new System.Drawing.Point(0, 272);
this.StatusStrip.Name = "StatusStrip";
this.StatusStrip.Size = new System.Drawing.Size(733, 22);
this.StatusStrip.Size = new System.Drawing.Size(740, 22);
this.StatusStrip.SizingGrip = false;
this.StatusStrip.TabIndex = 2;
//
@@ -558,7 +564,7 @@
// blankToolStripStatusLabel
//
this.blankToolStripStatusLabel.Name = "blankToolStripStatusLabel";
this.blankToolStripStatusLabel.Size = new System.Drawing.Size(487, 17);
this.blankToolStripStatusLabel.Size = new System.Drawing.Size(494, 17);
this.blankToolStripStatusLabel.Spring = true;
//
// NatTypeStatusLabel
@@ -584,7 +590,7 @@
// ControlButton
//
this.ControlButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ControlButton.Location = new System.Drawing.Point(646, 214);
this.ControlButton.Location = new System.Drawing.Point(631, 3);
this.ControlButton.Name = "ControlButton";
this.ControlButton.Size = new System.Drawing.Size(75, 27);
this.ControlButton.TabIndex = 3;
@@ -627,7 +633,7 @@
// SettingsButton
//
this.SettingsButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.SettingsButton.Location = new System.Drawing.Point(12, 215);
this.SettingsButton.Location = new System.Drawing.Point(1, 3);
this.SettingsButton.Name = "SettingsButton";
this.SettingsButton.Size = new System.Drawing.Size(72, 27);
this.SettingsButton.TabIndex = 4;
@@ -638,7 +644,7 @@
// ProfileGroupBox
//
this.ProfileGroupBox.Controls.Add(this.ProfileTable);
this.ProfileGroupBox.Location = new System.Drawing.Point(12, 146);
this.ProfileGroupBox.Location = new System.Drawing.Point(3, 124);
this.ProfileGroupBox.Name = "ProfileGroupBox";
this.ProfileGroupBox.Size = new System.Drawing.Size(709, 65);
this.ProfileGroupBox.TabIndex = 13;
@@ -661,17 +667,40 @@
this.ProfileTable.Size = new System.Drawing.Size(703, 43);
this.ProfileTable.TabIndex = 0;
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AutoSize = true;
this.flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.flowLayoutPanel1.Controls.Add(this.ConfigurationGroupBox);
this.flowLayoutPanel1.Controls.Add(this.ProfileGroupBox);
this.flowLayoutPanel1.Controls.Add(this.ButtomControlContainerControl);
this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.flowLayoutPanel1.Location = new System.Drawing.Point(12, 29);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(715, 256);
this.flowLayoutPanel1.TabIndex = 14;
//
// ButtomControlContainerControl
//
this.ButtomControlContainerControl.Controls.Add(this.ControlButton);
this.ButtomControlContainerControl.Controls.Add(this.SettingsButton);
this.ButtomControlContainerControl.Location = new System.Drawing.Point(3, 195);
this.ButtomControlContainerControl.Name = "ButtomControlContainerControl";
this.ButtomControlContainerControl.Size = new System.Drawing.Size(706, 58);
this.ButtomControlContainerControl.TabIndex = 14;
this.ButtomControlContainerControl.TabStop = false;
this.ButtomControlContainerControl.Text = "groupBox1";
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(733, 272);
this.Controls.Add(this.ProfileGroupBox);
this.Controls.Add(this.SettingsButton);
this.Controls.Add(this.ControlButton);
this.Controls.Add(this.StatusStrip);
this.Controls.Add(this.ConfigurationGroupBox);
this.AutoSize = true;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.ClientSize = new System.Drawing.Size(740, 294);
this.Controls.Add(this.MenuStrip);
this.Controls.Add(this.StatusStrip);
this.Controls.Add(this.flowLayoutPanel1);
this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
@@ -685,6 +714,7 @@
this.MenuStrip.ResumeLayout(false);
this.MenuStrip.PerformLayout();
this.ConfigurationGroupBox.ResumeLayout(false);
this.ConfigurationGroupBox.PerformLayout();
this.configLayoutPanel.ResumeLayout(false);
this.configLayoutPanel.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
@@ -700,6 +730,8 @@
this.NotifyMenu.ResumeLayout(false);
this.ProfileGroupBox.ResumeLayout(false);
this.ProfileGroupBox.PerformLayout();
this.flowLayoutPanel1.ResumeLayout(false);
this.ButtomControlContainerControl.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
@@ -735,7 +767,7 @@
private System.Windows.Forms.Label ProfileLabel;
private System.Windows.Forms.TextBox ProfileNameText;
private System.Windows.Forms.TableLayoutPanel ProfileTable;
private System.Windows.Forms.ToolStripMenuItem reinstallTapDriverToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem UninstallTapDriverToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem CheckForUpdatesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem ReloadModesToolStripMenuItem;
private System.Windows.Forms.ComboBox ServerComboBox;
@@ -763,5 +795,7 @@
#endregion
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.ContainerControl ButtomControlContainerControl;
}
}

View File

@@ -26,19 +26,8 @@ namespace Netch.Forms
var texts = Clipboard.GetText();
if (!string.IsNullOrWhiteSpace(texts))
{
var result = ShareLink.ParseText(texts);
if (result != null)
{
foreach (var server in result)
{
Global.Settings.Server.Add(server);
}
}
else
{
MessageBoxX.Show(i18N.Translate("Import servers error!"), LogLevel.ERROR);
}
Global.Settings.Server.AddRange(ShareLink.ParseText(texts));
NotifyTip(i18N.TranslateFormat("Import {0} server(s) form Clipboard", ShareLink.ParseText(texts).Count));
InitServer();
Configuration.Save();
@@ -54,7 +43,7 @@ namespace Netch.Forms
var result = s.Substring(start, end - start);
Hide();
Servers.GetUtilByFullName(result).Create();
ServerHelper.GetUtilByFullName(result).Create();
InitServer();
Configuration.Save();
@@ -77,7 +66,7 @@ namespace Netch.Forms
Enabled = false;
try
{
Modes.Load();
ModeHelper.Load();
InitMode();
NotifyTip(i18N.Translate("Modes have been reload"));
}
@@ -108,6 +97,9 @@ namespace Netch.Forms
await UpdateServersFromSubscribe();
}
private readonly object _serverLock = new object();
public async Task UpdateServersFromSubscribe()
{
void DisableItems(bool v)
@@ -144,8 +136,6 @@ namespace Netch.Forms
await MainController.Start(ServerComboBox.SelectedItem as Server, mode);
}
var serverLock = new object();
await Task.WhenAll(Global.Settings.SubscribeLink.Select(async item => await Task.Run(async () =>
{
try
@@ -156,31 +146,25 @@ namespace Netch.Forms
if (Global.Settings.UseProxyToUpdateSubscription)
request.Proxy = new WebProxy($"http://127.0.0.1:{Global.Settings.HTTPLocalPort}");
var str = await WebUtil.DownloadStringAsync(request);
var servers = ShareLink.ParseText(await WebUtil.DownloadStringAsync(request));
lock (serverLock)
foreach (var server in servers)
{
Global.Settings.Server.RemoveAll(server => server.Group == item.Remark);
var result = ShareLink.ParseText(str);
if (result != null)
{
foreach (var server in result)
{
server.Group = item.Remark;
Global.Settings.Server.Add(server);
}
}
NotifyTip(i18N.TranslateFormat("Update {1} server(s) from {0}", item.Remark, result?.Count ?? 0));
server.Group = item.Remark;
}
}
catch (WebException e)
{
NotifyTip($"{i18N.TranslateFormat("Update servers error from {0}", item.Remark)}\n{e.Message}", info: false);
lock (_serverLock)
{
Global.Settings.Server.RemoveAll(server => server.Group.Equals(item.Remark));
Global.Settings.Server.AddRange(servers);
}
NotifyTip(i18N.TranslateFormat("Update {1} server(s) from {0}", item.Remark, servers.Count));
}
catch (Exception e)
{
NotifyTip($"{i18N.TranslateFormat("Update servers error from {0}", item.Remark)}\n{e.Message}", info: false);
Logging.Error(e.ToString());
}
})).ToArray());
@@ -314,45 +298,46 @@ namespace Netch.Forms
private async void UninstallServiceToolStripMenuItem_Click(object sender, EventArgs e)
{
Enabled = false;
StatusText(i18N.Translate("Uninstalling NF Service"));
State = State.Starting;
StatusText(i18N.TranslateFormat("Uninstalling {0}", "NF Service"));
var result = false;
try
{
await Task.Run(() =>
{
if (NFController.UninstallDriver())
{
StatusText(i18N.Translate("Service has been uninstalled"));
result = true;
}
});
}
finally
{
Enabled = true;
State = State.Stopped;
if (result)
StatusText(i18N.TranslateFormat("{0} has been uninstalled", "NF Service"));
}
}
private async void reinstallTapDriverToolStripMenuItem_Click(object sender, EventArgs e)
{
StatusText(i18N.Translate("Reinstalling TUN/TAP driver"));
Enabled = false;
State = State.Starting;
StatusText(i18N.TranslateFormat("Uninstalling {0}", "TUN/TAP driver"));
var result = false;
try
{
await Task.Run(() =>
{
TUNTAP.deltapall();
TUNTAP.addtap();
});
StatusText(i18N.Translate("Reinstall TUN/TAP driver successfully"));
await Task.Run(TUNTAP.deltapall);
result = true;
}
catch
catch (Exception exception)
{
NotifyTip(i18N.Translate("Reinstall TUN/TAP driver failed"), info: false);
Logging.Error($"卸载 TUN/TAP 适配器失败: {exception}");
}
finally
{
State = State.Waiting;
Enabled = true;
State = State.Stopped;
if (result)
StatusText(i18N.TranslateFormat("{0} has been uninstalled", "TUN/TAP driver"));
}
}

View File

@@ -73,7 +73,7 @@ namespace Netch.Forms
{
FileName = Path.Combine(Global.NetchDir, "NetchUpdater.exe"),
Arguments =
$"{Global.Settings.UDPSocketPort} {fileFullPath} {Global.NetchDir}"
$"{Global.Settings.UDPSocketPort} \"{fileFullPath}\" \"{Global.NetchDir}\""
});
}
}

View File

@@ -15,12 +15,8 @@ namespace Netch.Forms
partial class MainForm
{
/// init at <see cref="MainForm_Load"/>
private int _sizeHeight;
private int _profileConfigurationHeight;
private int _profileGroupboxHeight;
private int _configurationGroupBoxHeight;
private int _profileConfigurationHeight;
private void InitProfile()
{
@@ -41,7 +37,6 @@ namespace Netch.Forms
ProfileGroupBox.Visible = false;
ConfigurationGroupBox.Size = new Size(ConfigurationGroupBox.Size.Width, _configurationGroupBoxHeight - _profileConfigurationHeight);
Size = new Size(Size.Width, _sizeHeight - (_profileConfigurationHeight + _profileGroupboxHeight));
}
else
{
@@ -75,11 +70,9 @@ namespace Netch.Forms
ProfileTable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 1));
}
if (Size.Height == _sizeHeight) return;
configLayoutPanel.RowStyles[2].SizeType = SizeType.AutoSize;
ProfileGroupBox.Visible = true;
ConfigurationGroupBox.Size = new Size(ConfigurationGroupBox.Size.Width, _configurationGroupBoxHeight);
Size = new Size(Size.Width, _sizeHeight);
}
}
@@ -167,6 +160,9 @@ namespace Netch.Forms
return;
}
// Reset Mode ComboBox Items
ModeComboBox.Text = string.Empty;
try
{
LoadProfile(index);

View File

@@ -157,7 +157,7 @@ namespace Netch.Forms
private void AddAddServerToolStripMenuItems()
{
foreach (var serversUtil in Servers.ServerUtils.Where(i => !string.IsNullOrEmpty(i.FullName)))
foreach (var serversUtil in ServerHelper.ServerUtils.Where(i => !string.IsNullOrEmpty(i.FullName)))
{
var fullName = serversUtil.FullName;
var control = new ToolStripMenuItem

View File

@@ -37,7 +37,7 @@ namespace Netch.Forms
UninstallServiceToolStripMenuItem.Enabled =
updateACLWithProxyToolStripMenuItem.Enabled =
UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled =
reinstallTapDriverToolStripMenuItem.Enabled =
UninstallTapDriverToolStripMenuItem.Enabled =
ReloadModesToolStripMenuItem.Enabled = enabled;
}
@@ -183,34 +183,55 @@ namespace Netch.Forms
public static class StatusPortInfoText
{
public static int Socks5Port = 0;
public static int HttpPort = 0;
public static bool ShareLan = false;
private static ushort? _socks5Port;
private static ushort? _httpPort;
private static bool? _shareLan;
public static bool ShareLan
{
set => _shareLan = value;
}
public static ushort HttpPort
{
set => _httpPort = value;
}
public static ushort Socks5Port
{
set => _socks5Port = value;
}
public static string Value
{
get
{
if (Socks5Port == 0 && HttpPort == 0)
if (_socks5Port == null && _httpPort == null)
return string.Empty;
var text = new StringBuilder();
if (ShareLan)
if (_shareLan == true)
text.Append(i18N.Translate("Allow other Devices to connect") + " ");
if (Socks5Port != 0)
text.Append($"Socks5 {i18N.Translate("Local Port", ": ")}{Socks5Port}");
if (_socks5Port != null)
text.Append($"Socks5 {i18N.Translate("Local Port", ": ")}{_socks5Port}");
if (HttpPort != 0)
if (_httpPort != null)
{
if (Socks5Port != 0)
if (_socks5Port != null)
text.Append(" | ");
text.Append($"HTTP {i18N.Translate("Local Port", ": ")}{HttpPort}");
text.Append($"HTTP {i18N.Translate("Local Port", ": ")}{_httpPort}");
}
return $" ({text})";
}
}
public static void Reset()
{
_httpPort = _socks5Port = null;
_shareLan = null;
}
}
}
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -41,11 +42,18 @@ namespace Netch.Forms
{
AddAddServerToolStripMenuItems();
#region i18N Translations
_mainFormText.Add(UninstallServiceToolStripMenuItem.Name, new[] {"Uninstall {0}", "NF Service"});
_mainFormText.Add(UninstallTapDriverToolStripMenuItem.Name, new[] {"Uninstall {0}", "TUN/TAP driver"});
#endregion
OnlyInstance.Called += OnCalled;
// 计算 ComboBox绘制 目标宽度
_eWidth = ServerComboBox.Width / 10;
Modes.Load();
ModeHelper.Load();
InitMode();
InitServer();
_comboBoxInitialized = true;
@@ -56,10 +64,8 @@ namespace Netch.Forms
// 隐藏 NatTypeStatusLabel
NatTypeStatusText();
_sizeHeight = Size.Height;
_configurationGroupBoxHeight = ConfigurationGroupBox.Height;
_profileConfigurationHeight = ConfigurationGroupBox.Controls[0].Height / 3; // 因为 AutoSize, 所以得到的是Controls的总高度
_profileGroupboxHeight = ProfileGroupBox.Height;
// 加载快速配置
InitProfile();
@@ -168,6 +174,7 @@ namespace Netch.Forms
{
i18N.Load(Global.Settings.Language);
InitText();
InitMode();
InitProfile();
}
@@ -226,11 +233,12 @@ namespace Netch.Forms
case ListControl _:
break;
case Control c:
c.Text = ControlText(c.Name);
if (_mainFormText.ContainsKey(c.Name))
c.Text = ControlText(c.Name);
break;
case ToolStripItem c:
c.Text = ControlText(c.Name);
if (_mainFormText.ContainsKey(c.Name))
c.Text = ControlText(c.Name);
break;
}
@@ -274,6 +282,10 @@ namespace Netch.Forms
}
Configuration.Save();
if (File.Exists("data\\last.json"))
File.Delete("data\\last.json");
State = State.Terminating;
}
@@ -314,7 +326,7 @@ namespace Netch.Forms
Hide();
var server = Global.Settings.Server[ServerComboBox.SelectedIndex];
Servers.GetUtilByTypeName(server.Type).Edit(server);
ServerHelper.GetUtilByTypeName(server.Type).Edit(server);
InitServer();
Configuration.Save();
Show();
@@ -322,7 +334,7 @@ namespace Netch.Forms
private async void SpeedPictureBox_Click(object sender, EventArgs e)
{
Enabled = false;
State = State.Starting;
StatusText(i18N.Translate("Testing"));
try
{
@@ -330,7 +342,7 @@ namespace Netch.Forms
}
finally
{
Enabled = true;
State = State.Stopped;
StatusText(i18N.Translate("Test done"));
Refresh();
}
@@ -372,7 +384,7 @@ namespace Netch.Forms
return;
}
Modes.Delete((Models.Mode) ModeComboBox.SelectedItem);
ModeHelper.Delete((Models.Mode) ModeComboBox.SelectedItem);
SelectLastMode();
}

View File

@@ -47,19 +47,21 @@ namespace Netch.Forms.Mode
this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.ControlButton = new System.Windows.Forms.Button();
this.DeleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.containerControl1 = new System.Windows.Forms.ContainerControl();
this.ConfigurationGroupBox.SuspendLayout();
this.ProcessGroupBox.SuspendLayout();
this.contextMenuStrip.SuspendLayout();
this.containerControl1.SuspendLayout();
this.SuspendLayout();
//
// ConfigurationGroupBox
//
this.ConfigurationGroupBox.Controls.Add(this.containerControl1);
this.ConfigurationGroupBox.Controls.Add(this.UseCustomFilenameBox);
this.ConfigurationGroupBox.Controls.Add(this.FilenameLabel);
this.ConfigurationGroupBox.Controls.Add(this.FilenameTextBox);
this.ConfigurationGroupBox.Controls.Add(this.ScanButton);
this.ConfigurationGroupBox.Controls.Add(this.ProcessGroupBox);
this.ConfigurationGroupBox.Controls.Add(this.RuleListBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkTextBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkLabel);
this.ConfigurationGroupBox.Location = new System.Drawing.Point(12, 12);
@@ -136,8 +138,9 @@ namespace Netch.Forms.Mode
// RuleListBox
//
this.RuleListBox.FormattingEnabled = true;
this.RuleListBox.Dock = DockStyle.Fill;
this.RuleListBox.ItemHeight = 17;
this.RuleListBox.Location = new System.Drawing.Point(6, 100);
this.RuleListBox.Location = new System.Drawing.Point(0, 0);
this.RuleListBox.Name = "RuleListBox";
this.RuleListBox.Size = new System.Drawing.Size(328, 157);
this.RuleListBox.TabIndex = 2;
@@ -183,6 +186,16 @@ namespace Netch.Forms.Mode
this.DeleteToolStripMenuItem.Text = "Delete";
this.DeleteToolStripMenuItem.Click += new System.EventHandler(this.deleteRule_Click);
//
// containerControl1
//
this.containerControl1.Controls.Add(this.RuleListBox);
this.containerControl1.Location = new System.Drawing.Point(6, 100);
this.containerControl1.Name = "containerControl1";
this.containerControl1.Size = new System.Drawing.Size(328, 157);
this.containerControl1.TabIndex = 10;
this.containerControl1.Padding = new Padding(0);
this.containerControl1.Text = "containerControl1";
//
// Process
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
@@ -204,11 +217,13 @@ namespace Netch.Forms.Mode
this.ProcessGroupBox.ResumeLayout(false);
this.ProcessGroupBox.PerformLayout();
this.contextMenuStrip.ResumeLayout(false);
this.containerControl1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ContainerControl containerControl1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem DeleteToolStripMenuItem;
public System.Windows.Forms.GroupBox ConfigurationGroupBox;

View File

@@ -142,10 +142,6 @@ namespace Netch.Forms.Mode
if (!string.IsNullOrWhiteSpace(ProcessNameTextBox.Text))
{
var process = ProcessNameTextBox.Text;
if (!process.EndsWith(".exe"))
{
process += ".exe";
}
if (!RuleListBox.Items.Contains(process))
{
@@ -207,14 +203,14 @@ namespace Netch.Forms.Mode
_mode.Rule.Clear();
_mode.Rule.AddRange(RuleListBox.Items.Cast<string>());
Modes.WriteFile(_mode);
ModeHelper.WriteFile(_mode);
Global.MainForm.InitMode();
Edited = false;
MessageBoxX.Show(i18N.Translate("Mode updated successfully"));
}
else
{
var fullName = Modes.GetFullPath(FilenameTextBox.Text + ".txt");
var fullName = ModeHelper.GetFullPath(FilenameTextBox.Text + ".txt");
if (File.Exists(fullName))
{
MessageBoxX.Show(i18N.Translate("File already exists.\n Please Change the filename"));
@@ -230,8 +226,8 @@ namespace Netch.Forms.Mode
};
mode.Rule.AddRange(RuleListBox.Items.Cast<string>());
Modes.WriteFile(mode);
Modes.Add(mode);
ModeHelper.WriteFile(mode);
ModeHelper.Add(mode);
MessageBoxX.Show(i18N.Translate("Mode added successfully"));
}

316
Netch/Forms/ServerForm.cs Normal file
View File

@@ -0,0 +1,316 @@
using System.ComponentModel;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Netch.Models;
using Netch.Properties;
using Netch.Utils;
namespace Netch.Forms
{
public abstract class ServerForm : Form
{
protected abstract string TypeName { get; }
protected Server Server { get; set; }
private int _controlLines = 2;
private const int ControlLineHeight = 28;
private const int InputBoxWidth = 294;
protected ServerForm()
{
InitializeComponent();
_checkActions.Add(RemarkTextBox, s => true);
_saveActions.Add(RemarkTextBox, s => Server.Remark = (string) s);
_checkActions.Add(AddressTextBox, s => s != string.Empty);
_saveActions.Add(AddressTextBox, s => Server.Hostname = (string) s);
_checkActions.Add(PortTextBox, s => ushort.TryParse(s, out var port) && port != 0);
_saveActions.Add(PortTextBox, s => Server.Port = ushort.Parse((string) s));
}
public new void ShowDialog()
{
AfterFactor();
base.ShowDialog();
}
public new void Show()
{
AfterFactor();
base.Show();
}
private void AfterFactor()
{
Text = TypeName ?? string.Empty;
RemarkTextBox.Text = Server.Remark;
AddressTextBox.Text = Server.Hostname;
PortTextBox.Text = Server.Port.ToString();
AddSaveButton();
i18N.TranslateForm(this);
ConfigurationGroupBox.ResumeLayout(false);
ConfigurationGroupBox.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
protected void CreateTextBox(string name, string remark, Func<string, bool> check, Action<string> save, string value, int width = InputBoxWidth)
{
_controlLines++;
var textBox = new TextBox
{
Location = new Point(120, ControlLineHeight * _controlLines),
Name = $"{name}TextBox",
Size = new Size(width, 23),
TextAlign = HorizontalAlignment.Center,
Text = value
};
_checkActions.Add(textBox, check);
_saveActions.Add(textBox, o => save.Invoke((string) o));
ConfigurationGroupBox.Controls.AddRange(
new Control[]
{
textBox,
new Label
{
AutoSize = true,
Location = new Point(10, ControlLineHeight * _controlLines),
Name = $"{name}Label",
Size = new Size(56, 17),
Text = remark
}
}
);
}
protected void CreateComboBox(string name, string remark, List<string> values, Action<string> save, string value, int width = InputBoxWidth)
{
_controlLines++;
var comboBox = new ComboBox
{
Location = new Point(120, ControlLineHeight * _controlLines),
Name = $"{name}ComboBox",
Size = new Size(width, 23),
DrawMode = DrawMode.OwnerDrawFixed,
DropDownStyle = ComboBoxStyle.DropDownList,
FormattingEnabled = true
};
comboBox.Items.AddRange(values.ToArray());
comboBox.SelectedIndex = values.IndexOf(value);
comboBox.DrawItem += Utils.Utils.DrawCenterComboBox;
_saveActions.Add(comboBox, o => save.Invoke((string) o));
ConfigurationGroupBox.Controls.AddRange(
new Control[]
{
comboBox,
new Label
{
AutoSize = true,
Location = new Point(10, ControlLineHeight * _controlLines),
Name = $"{name}Label",
Size = new Size(56, 17),
Text = remark
}
}
);
}
protected void CreateCheckBox(string name, string remark, Action<bool> save, bool value)
{
_controlLines++;
var checkBox = new CheckBox
{
AutoSize = true,
Location = new Point(120, ControlLineHeight * _controlLines),
Name = $"{name}CheckBox",
Checked = value,
Text = remark
};
_saveActions.Add(checkBox, o => save.Invoke((bool) o));
ConfigurationGroupBox.Controls.AddRange(
new Control[]
{
checkBox
}
);
}
private readonly Dictionary<Control, Func<string, bool>> _checkActions = new Dictionary<Control, Func<string, bool>>();
private readonly Dictionary<Control, Action<object>> _saveActions = new Dictionary<Control, Action<object>>();
private void AddSaveButton()
{
_controlLines++;
var control = new Button
{
Location = new Point(340, _controlLines * ControlLineHeight + 10),
Name = "ControlButton",
Size = new Size(75, 23),
Text = "Save",
UseVisualStyleBackColor = true
};
control.Click += ControlButton_Click;
ConfigurationGroupBox.Controls.Add(control);
}
private void ControlButton_Click(object sender, EventArgs e)
{
if (_checkActions.All(pair => pair.Value.Invoke(pair.Key.Text)))
{
foreach (var pair in _saveActions)
{
switch (pair.Key)
{
case CheckBox c:
pair.Value.Invoke(c.Checked);
break;
default:
pair.Value.Invoke(pair.Key.Text);
break;
}
}
if (Global.Settings.Server.IndexOf(Server) == -1)
Global.Settings.Server.Add(Server);
MessageBoxX.Show(i18N.Translate("Saved"));
}
else
return;
Close();
}
private IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing)
{
components?.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
ConfigurationGroupBox = new GroupBox();
AddressLabel = new Label();
PortTextBox = new TextBox();
AddressTextBox = new TextBox();
RemarkTextBox = new TextBox();
RemarkLabel = new Label();
PortLabel = new Label();
ConfigurationGroupBox.SuspendLayout();
SuspendLayout();
//
// ConfigurationGroupBox
//
ConfigurationGroupBox.AutoSize = true;
ConfigurationGroupBox.AutoSizeMode = AutoSizeMode.GrowAndShrink;
ConfigurationGroupBox.Controls.Add(AddressLabel);
ConfigurationGroupBox.Controls.Add(PortTextBox);
ConfigurationGroupBox.Controls.Add(AddressTextBox);
ConfigurationGroupBox.Controls.Add(RemarkTextBox);
ConfigurationGroupBox.Controls.Add(RemarkLabel);
ConfigurationGroupBox.Controls.Add(PortLabel);
ConfigurationGroupBox.Dock = DockStyle.Fill;
ConfigurationGroupBox.Location = new Point(5, 5);
ConfigurationGroupBox.Name = "ConfigurationGroupBox";
ConfigurationGroupBox.Size = new Size(434, 127);
ConfigurationGroupBox.TabIndex = 0;
ConfigurationGroupBox.TabStop = false;
ConfigurationGroupBox.Text = "Configuration";
//
// AddressLabel
//
AddressLabel.AutoSize = true;
AddressLabel.Location = new Point(10, ControlLineHeight * 2);
AddressLabel.Name = "AddressLabel";
AddressLabel.Size = new Size(56, 17);
AddressLabel.TabIndex = 2;
AddressLabel.Text = "Address";
//
// PortTextBox
//
PortTextBox.Location = new Point(358, ControlLineHeight * 2);
PortTextBox.Name = "PortTextBox";
PortTextBox.Size = new Size(56, 23);
PortTextBox.TabIndex = 5;
PortTextBox.TextAlign = HorizontalAlignment.Center;
//
// AddressTextBox
//
AddressTextBox.Location = new Point(120, ControlLineHeight * 2);
AddressTextBox.Name = "AddressTextBox";
AddressTextBox.Size = new Size(232, 23);
AddressTextBox.TabIndex = 3;
AddressTextBox.TextAlign = HorizontalAlignment.Center;
//
// RemarkTextBox
//
RemarkTextBox.Location = new Point(120, ControlLineHeight);
RemarkTextBox.Name = "RemarkTextBox";
RemarkTextBox.Size = new Size(294, 23);
RemarkTextBox.TabIndex = 1;
RemarkTextBox.TextAlign = HorizontalAlignment.Center;
//
// RemarkLabel
//
RemarkLabel.AutoSize = true;
RemarkLabel.Location = new Point(10, ControlLineHeight);
RemarkLabel.Name = "RemarkLabel";
RemarkLabel.Size = new Size(53, 17);
RemarkLabel.TabIndex = 0;
RemarkLabel.Text = "Remark";
//
// PortLabel
//
PortLabel.AutoSize = true;
PortLabel.Location = new Point(351, ControlLineHeight * 2);
PortLabel.Name = "PortLabel";
PortLabel.Size = new Size(11, 17);
PortLabel.TabIndex = 4;
PortLabel.Text = ":";
//
// ServerForm
//
AutoScaleDimensions = new SizeF(96F, 96F);
AutoScaleMode = AutoScaleMode.Dpi;
AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink;
ClientSize = new Size(444, 137);
Controls.Add(ConfigurationGroupBox);
Font = new Font("微软雅黑", 9F, FontStyle.Regular, GraphicsUnit.Point, (byte) 134);
FormBorderStyle = FormBorderStyle.FixedSingle;
Icon = Icon.FromHandle(Resources.Netch.GetHicon());
Margin = new Padding(3, 4, 3, 4);
MaximizeBox = false;
Name = "ServerForm";
Padding = new Padding(11, 5, 11, 4);
StartPosition = FormStartPosition.CenterScreen;
}
private GroupBox ConfigurationGroupBox;
private Label RemarkLabel;
protected TextBox RemarkTextBox;
private Label PortLabel;
protected TextBox AddressTextBox;
private TextBox PortTextBox;
private Label AddressLabel;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,11 @@
using System;
using Netch.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
using Netch.Controllers;
using Netch.Utils;
using TaskScheduler;
namespace Netch.Forms
@@ -15,50 +15,196 @@ namespace Netch.Forms
public SettingForm()
{
InitializeComponent();
i18N.TranslateForm(this);
InitValue();
}
private void SettingForm2_Load(object sender, EventArgs e)
{
Task.Run(() => BeginInvoke(new Action(() => UseFakeDNSCheckBox.Visible = Global.Flags.SupportFakeDns)));
}
private void InitValue()
{
// Local Port
Socks5PortTextBox.Text = Global.Settings.Socks5LocalPort.ToString();
HTTPPortTextBox.Text = Global.Settings.HTTPLocalPort.ToString();
RedirectorTextBox.Text = Global.Settings.RedirectorTCPPort.ToString();
AllowDevicesCheckBox.Checked = Global.Settings.LocalAddress switch
{
"127.0.0.1" => false,
"0.0.0.0" => true,
_ => false
};
#region General
// TUN/TAP
TUNTAPAddressTextBox.Text = Global.Settings.TUNTAP.Address;
TUNTAPNetmaskTextBox.Text = Global.Settings.TUNTAP.Netmask;
TUNTAPGatewayTextBox.Text = Global.Settings.TUNTAP.Gateway;
UseCustomDNSCheckBox.Checked = Global.Settings.TUNTAP.UseCustomDNS;
TUNTAPUseCustomDNSCheckBox_CheckedChanged(null, null);
ProxyDNSCheckBox.Checked = Global.Settings.TUNTAP.ProxyDNS;
UseFakeDNSCheckBox.Checked = Global.Settings.TUNTAP.UseFakeDNS;
ICSCheckBox.Checked = ICSController.Enabled;
BindTextBox<ushort>(Socks5PortTextBox,
p => CheckPort("Socks5", p, Global.Settings.Socks5LocalPort),
p => Global.Settings.Socks5LocalPort = p,
Global.Settings.Socks5LocalPort);
BindTextBox<ushort>(HTTPPortTextBox,
p => CheckPort("HTTP", p, Global.Settings.HTTPLocalPort),
p => Global.Settings.HTTPLocalPort = p,
Global.Settings.HTTPLocalPort);
BindTextBox<ushort>(RedirectorTextBox,
s => CheckPort("RedirectorTCP", s, Global.Settings.RedirectorTCPPort),
s => Global.Settings.RedirectorTCPPort = s,
Global.Settings.HTTPLocalPort);
BindCheckBox(AllowDevicesCheckBox,
c => Global.Settings.LocalAddress = AllowDevicesCheckBox.Checked ? "0.0.0.0" : "127.0.0.1",
Global.Settings.LocalAddress switch
{
"127.0.0.1" => false,
"0.0.0.0" => true,
_ => false
});
// Behavior
ExitWhenClosedCheckBox.Checked = Global.Settings.ExitWhenClosed;
StopWhenExitedCheckBox.Checked = Global.Settings.StopWhenExited;
StartWhenOpenedCheckBox.Checked = Global.Settings.StartWhenOpened;
MinimizeWhenStartedCheckBox.Checked = Global.Settings.MinimizeWhenStarted;
RunAtStartupCheckBox.Checked = Global.Settings.RunAtStartup;
CheckUpdateWhenOpenedCheckBox.Checked = Global.Settings.CheckUpdateWhenOpened;
BootShadowsocksFromDLLCheckBox.Checked = Global.Settings.BootShadowsocksFromDLL;
CheckBetaUpdateCheckBox.Checked = Global.Settings.CheckBetaUpdate;
ModifySystemDNSCheckBox.Checked = Global.Settings.ModifySystemDNS;
UpdateSubscribeatWhenOpenedCheckBox.Checked = Global.Settings.UpdateSubscribeatWhenOpened;
ProfileCountTextBox.Text = Global.Settings.ProfileCount.ToString();
TcpingAtStartedCheckBox.Checked = Global.Settings.StartedTcping;
DetectionIntervalTextBox.Text = Global.Settings.StartedTcping_Interval.ToString();
BindCheckBox(BootShadowsocksFromDLLCheckBox,
c => Global.Settings.BootShadowsocksFromDLL = c,
Global.Settings.BootShadowsocksFromDLL);
BindCheckBox(ResolveServerHostnameCheckBox,
c => Global.Settings.ResolveServerHostname = c,
Global.Settings.ResolveServerHostname);
BindTextBox<int>(ProfileCountTextBox,
i => i > -1,
i => Global.Settings.ProfileCount = i,
Global.Settings.ProfileCount);
BindCheckBox(TcpingAtStartedCheckBox,
b => Global.Settings.StartedTcping = b,
Global.Settings.StartedTcping);
BindTextBox<int>(DetectionIntervalTextBox,
i => i >= 0,
i => Global.Settings.StartedTcping_Interval = i,
Global.Settings.StartedTcping_Interval);
InitSTUN();
BindTextBox<string>(AclAddrTextBox,
s => true,
s => Global.Settings.ACL = s,
Global.Settings.ACL);
AclAddrTextBox.Text = Global.Settings.ACL;
LanguageComboBox.Items.AddRange(i18N.GetTranslateList().ToArray());
LanguageComboBox.SelectedItem = Global.Settings.Language;
#endregion
#region Process Mode
BindCheckBox(ModifySystemDNSCheckBox,
b => Global.Settings.ModifySystemDNS = b,
Global.Settings.ModifySystemDNS);
#endregion
#region TUN/TAP
BindTextBox(TUNTAPAddressTextBox,
s => IPAddress.TryParse(s, out _),
s => Global.Settings.TUNTAP.Address = s,
Global.Settings.TUNTAP.Address);
BindTextBox(TUNTAPNetmaskTextBox,
s => IPAddress.TryParse(s, out _),
s => Global.Settings.TUNTAP.Netmask = s,
Global.Settings.TUNTAP.Netmask);
BindTextBox(TUNTAPGatewayTextBox,
s => IPAddress.TryParse(s, out _),
s => Global.Settings.TUNTAP.Gateway = s,
Global.Settings.TUNTAP.Gateway);
BindCheckBox(UseCustomDNSCheckBox,
b => { Global.Settings.TUNTAP.UseCustomDNS = b; },
Global.Settings.TUNTAP.UseCustomDNS);
TUNTAPUseCustomDNSCheckBox_CheckedChanged(null, null);
BindCheckBox(ProxyDNSCheckBox,
b => Global.Settings.TUNTAP.ProxyDNS = b,
Global.Settings.TUNTAP.ProxyDNS);
BindCheckBox(UseFakeDNSCheckBox,
b => Global.Settings.TUNTAP.UseFakeDNS = b,
Global.Settings.TUNTAP.UseFakeDNS);
try
{
var icsHelperEnabled = ICSHelper.Enabled;
if (icsHelperEnabled != null)
{
ICSCheckBox.Enabled = true;
ICSCheckBox.Checked = (bool) icsHelperEnabled;
}
}
catch
{
// ignored
}
#endregion
#region V2Ray
BindCheckBox(TLSAllowInsecureCheckBox,
b => Global.Settings.V2RayConfig.AllowInsecure = b,
Global.Settings.V2RayConfig.AllowInsecure);
BindTextBox<int>(mtuTextBox,
i => true,
i => Global.Settings.V2RayConfig.KcpConfig.mtu = i,
Global.Settings.V2RayConfig.KcpConfig.mtu);
BindTextBox<int>(ttiTextBox,
i => true,
i => Global.Settings.V2RayConfig.KcpConfig.tti = i,
Global.Settings.V2RayConfig.KcpConfig.tti);
BindTextBox<int>(uplinkCapacityTextBox,
i => true,
i => Global.Settings.V2RayConfig.KcpConfig.uplinkCapacity = i,
Global.Settings.V2RayConfig.KcpConfig.uplinkCapacity);
BindTextBox<int>(downlinkCapacityTextBox,
i => true,
i => Global.Settings.V2RayConfig.KcpConfig.downlinkCapacity = i,
Global.Settings.V2RayConfig.KcpConfig.downlinkCapacity);
BindTextBox<int>(readBufferSizeTextBox,
i => true,
i => Global.Settings.V2RayConfig.KcpConfig.readBufferSize = i,
Global.Settings.V2RayConfig.KcpConfig.readBufferSize);
BindTextBox<int>(writeBufferSizeTextBox,
i => true,
i => Global.Settings.V2RayConfig.KcpConfig.writeBufferSize = i,
Global.Settings.V2RayConfig.KcpConfig.writeBufferSize);
BindCheckBox(congestionCheckBox,
b => Global.Settings.V2RayConfig.KcpConfig.congestion = b,
Global.Settings.V2RayConfig.KcpConfig.congestion);
#endregion
#region Others
BindCheckBox(ExitWhenClosedCheckBox,
b => Global.Settings.ExitWhenClosed = b,
Global.Settings.ExitWhenClosed);
BindCheckBox(StopWhenExitedCheckBox,
b => Global.Settings.StopWhenExited = b,
Global.Settings.StopWhenExited);
BindCheckBox(StartWhenOpenedCheckBox,
b => Global.Settings.StartWhenOpened = b,
Global.Settings.StartWhenOpened);
BindCheckBox(MinimizeWhenStartedCheckBox,
b => Global.Settings.MinimizeWhenStarted = b,
Global.Settings.MinimizeWhenStarted);
BindCheckBox(RunAtStartupCheckBox,
b => Global.Settings.RunAtStartup = b,
Global.Settings.RunAtStartup);
BindCheckBox(CheckUpdateWhenOpenedCheckBox,
b => Global.Settings.CheckUpdateWhenOpened = b,
Global.Settings.CheckUpdateWhenOpened);
BindCheckBox(CheckBetaUpdateCheckBox,
b => Global.Settings.CheckBetaUpdate = b,
Global.Settings.CheckBetaUpdate);
BindCheckBox(UpdateSubscribeatWhenOpenedCheckBox,
b => Global.Settings.UpdateSubscribeatWhenOpened = b,
Global.Settings.UpdateSubscribeatWhenOpened);
#endregion
}
private void TUNTAPUseCustomDNSCheckBox_CheckedChanged(object sender, EventArgs e)
@@ -77,10 +223,6 @@ namespace Netch.Forms
}
}
private void InitText()
{
i18N.TranslateForm(this);
}
private void InitSTUN()
{
@@ -89,7 +231,7 @@ namespace Netch.Forms
var stuns = File.ReadLines("bin\\stun.txt");
STUN_ServerComboBox.Items.AddRange(stuns.ToArray());
}
catch (Exception)
catch
{
// ignored
}
@@ -97,13 +239,6 @@ namespace Netch.Forms
STUN_ServerComboBox.Text = $"{Global.Settings.STUN_Server}:{Global.Settings.STUN_Server_Port}";
}
private void SettingForm_Load(object sender, EventArgs e)
{
UseFakeDNSCheckBox.Visible = Global.Flags.SupportFakeDns;
InitText();
InitValue();
}
private void GlobalBypassIPsButton_Click(object sender, EventArgs e)
{
Hide();
@@ -113,63 +248,16 @@ namespace Netch.Forms
private void ControlButton_Click(object sender, EventArgs e)
{
#region Check
#region Port
int socks5LocalPort;
int httpLocalPort;
int redirectorTCPPort;
try
{
socks5LocalPort = int.Parse(Socks5PortTextBox.Text);
httpLocalPort = int.Parse(HTTPPortTextBox.Text);
redirectorTCPPort = int.Parse(RedirectorTextBox.Text);
static void CheckPort(string portName, int port, int originPort, PortType portType = PortType.Both)
{
if (port <= 0 || port > 65536)
throw new FormatException();
if (port == originPort)
return;
if (PortHelper.PortInUse(port, portType))
{
MessageBoxX.Show(i18N.TranslateFormat("The {0} port is in use.", portName));
throw new PortInUseException();
}
}
CheckPort("Socks5", socks5LocalPort, Global.Settings.Socks5LocalPort);
CheckPort("HTTP", httpLocalPort, Global.Settings.HTTPLocalPort);
CheckPort("RedirectorTCP", redirectorTCPPort, Global.Settings.RedirectorTCPPort);
}
catch (Exception exception)
{
switch (exception)
{
case FormatException _:
MessageBoxX.Show(i18N.Translate("Port value illegal. Try again."));
break;
case PortInUseException _:
break;
}
if (!_checkActions.All(pair => pair.Value.Invoke(pair.Key.Text)))
return;
}
#endregion
#region Check
#region TUNTAP
var dns = new string[0];
try
{
IPAddress.Parse(TUNTAPAddressTextBox.Text);
IPAddress.Parse(TUNTAPNetmaskTextBox.Text);
IPAddress.Parse(TUNTAPGatewayTextBox.Text);
if (UseCustomDNSCheckBox.Checked)
{
dns = TUNTAPDNSTextBox.Text.Split(',').Where(s => !string.IsNullOrEmpty(s)).Select(s => s.Trim())
@@ -191,11 +279,6 @@ namespace Netch.Forms
if (exception is FormatException)
MessageBoxX.Show(i18N.Translate("IP address format illegal. Try again."));
TUNTAPAddressTextBox.Text = Global.Settings.TUNTAP.Address;
TUNTAPNetmaskTextBox.Text = Global.Settings.TUNTAP.Netmask;
TUNTAPGatewayTextBox.Text = Global.Settings.TUNTAP.Gateway;
UseCustomDNSCheckBox.Checked = Global.Settings.TUNTAP.UseCustomDNS;
if (UseCustomDNSCheckBox.Checked)
{
TUNTAPDNSTextBox.Text = Global.Settings.TUNTAP.DNS.Aggregate((current, ip) => $"{current},{ip}");
@@ -208,44 +291,6 @@ namespace Netch.Forms
#region Behavior
// Profile
int profileCount;
try
{
profileCount = int.Parse(ProfileCountTextBox.Text);
if (profileCount <= -1)
{
throw new FormatException();
}
}
catch (FormatException)
{
ProfileCountTextBox.Text = Global.Settings.ProfileCount.ToString();
MessageBoxX.Show(i18N.Translate("ProfileCount value illegal. Try again."));
return;
}
// Started TCPing Interval
int detectionInterval;
try
{
detectionInterval = int.Parse(DetectionIntervalTextBox.Text);
if (detectionInterval <= 0)
{
throw new FormatException();
}
}
catch (FormatException)
{
ProfileCountTextBox.Text = Global.Settings.ProfileCount.ToString();
MessageBoxX.Show(i18N.Translate("Detection interval value illegal. Try again."));
return;
}
// STUN
string stunServer;
int stunServerPort;
@@ -265,7 +310,6 @@ namespace Netch.Forms
}
catch (FormatException)
{
ProfileCountTextBox.Text = Global.Settings.ProfileCount.ToString();
MessageBoxX.Show(i18N.Translate("STUN_ServerPort value illegal. Try again."));
return;
@@ -277,54 +321,14 @@ namespace Netch.Forms
#region Save
#region Port
Global.Settings.Socks5LocalPort = socks5LocalPort;
Global.Settings.HTTPLocalPort = httpLocalPort;
Global.Settings.RedirectorTCPPort = redirectorTCPPort;
Global.Settings.LocalAddress = AllowDevicesCheckBox.Checked ? "0.0.0.0" : "127.0.0.1";
#endregion
#region TUNTAP
Global.Settings.TUNTAP.Address = TUNTAPAddressTextBox.Text;
Global.Settings.TUNTAP.Netmask = TUNTAPNetmaskTextBox.Text;
Global.Settings.TUNTAP.Gateway = TUNTAPGatewayTextBox.Text;
Global.Settings.TUNTAP.UseCustomDNS = UseCustomDNSCheckBox.Checked;
if (Global.Settings.TUNTAP.UseCustomDNS)
foreach (var pair in _saveActions)
{
Global.Settings.TUNTAP.DNS.Clear();
Global.Settings.TUNTAP.DNS.AddRange(dns);
pair.Value.Invoke(pair.Key);
}
Global.Settings.TUNTAP.ProxyDNS = ProxyDNSCheckBox.Checked;
Global.Settings.TUNTAP.UseFakeDNS = UseFakeDNSCheckBox.Checked;
#endregion
#region Behavior
Global.Settings.ExitWhenClosed = ExitWhenClosedCheckBox.Checked;
Global.Settings.StopWhenExited = StopWhenExitedCheckBox.Checked;
Global.Settings.StartWhenOpened = StartWhenOpenedCheckBox.Checked;
Global.Settings.MinimizeWhenStarted = MinimizeWhenStartedCheckBox.Checked;
Global.Settings.RunAtStartup = RunAtStartupCheckBox.Checked;
Global.Settings.CheckUpdateWhenOpened = CheckUpdateWhenOpenedCheckBox.Checked;
Global.Settings.BootShadowsocksFromDLL = BootShadowsocksFromDLLCheckBox.Checked;
Global.Settings.CheckBetaUpdate = CheckBetaUpdateCheckBox.Checked;
Global.Settings.ModifySystemDNS = ModifySystemDNSCheckBox.Checked;
Global.Settings.UpdateSubscribeatWhenOpened = UpdateSubscribeatWhenOpenedCheckBox.Checked;
Global.Settings.ProfileCount = profileCount;
Global.Settings.StartedTcping = TcpingAtStartedCheckBox.Checked;
Global.Settings.StartedTcping_Interval = detectionInterval;
Global.Settings.TUNTAP.DNS = dns.ToList();
Global.Settings.STUN_Server = stunServer;
Global.Settings.STUN_Server_Port = stunServerPort;
Global.Settings.ACL = AclAddrTextBox.Text;
Global.Settings.Language = LanguageComboBox.SelectedItem.ToString();
#endregion
#endregion
@@ -380,22 +384,75 @@ namespace Netch.Forms
Close();
}
private bool CheckPort(string portName, ushort port, ushort originPort, PortType portType = PortType.Both)
{
if (port == originPort) return true;
if (!PortHelper.PortInUse(port, portType)) return true;
MessageBoxX.Show(i18N.TranslateFormat("The {0} port is in use.", portName));
return false;
}
private async void ICSCheckBox_CheckedChanged(object sender, EventArgs e)
{
ICSCheckBox.Enabled = false;
await Task.Run(() =>
try
{
if (ICSCheckBox.Checked)
ICSCheckBox.Enabled = false;
await Task.Run(() =>
{
if (!ICSController.Enabled)
ICSCheckBox.Checked = ICSController.Enable();
if (ICSCheckBox.Checked)
{
if (!(ICSHelper.Enabled ?? true))
ICSCheckBox.Checked = ICSHelper.Enable();
}
else
{
ICSHelper.Disable();
}
});
}
catch (Exception exception)
{
ICSCheckBox.Checked = false;
Logging.Error(exception.ToString());
}
finally
{
ICSCheckBox.Enabled = true;
}
}
private void BindTextBox(TextBox control, Func<string, bool> check, Action<string> save, object value)
{
BindTextBox<string>(control, check, save, value);
}
private void BindTextBox<T>(TextBox control, Func<T, bool> check, Action<T> save, object value)
{
control.Text = value.ToString();
_checkActions.Add(control, s =>
{
try
{
return check.Invoke((T) Convert.ChangeType(s, typeof(T)));
}
else
catch
{
ICSController.Disable();
return false;
}
});
ICSCheckBox.Enabled = true;
_saveActions.Add(control, c => save.Invoke((T) Convert.ChangeType(((TextBox) c).Text, typeof(T))));
}
private void BindCheckBox(CheckBox control, Action<bool> save, bool value)
{
control.Checked = value;
_checkActions.Add(control, s => true);
_saveActions.Add(control, c => save.Invoke(((CheckBox) c).Checked));
}
private readonly Dictionary<Control, Func<string, bool>> _checkActions = new Dictionary<Control, Func<string, bool>>();
private readonly Dictionary<Control, Action<Control>> _saveActions = new Dictionary<Control, Action<Control>>();
}
}

View File

@@ -81,11 +81,11 @@
//
// ClearButton
//
this.ClearButton.Location = new System.Drawing.Point(477, 103);
this.ClearButton.Location = new System.Drawing.Point(448, 103);
this.ClearButton.Name = "ClearButton";
this.ClearButton.Size = new System.Drawing.Size(58, 26);
this.ClearButton.Size = new System.Drawing.Size(87, 26);
this.ClearButton.TabIndex = 7;
this.ClearButton.Text = "Clear";
this.ClearButton.Text = "Unselect";
this.ClearButton.UseVisualStyleBackColor = true;
this.ClearButton.Click += new System.EventHandler(this.ClearButton_Click);
//
@@ -114,7 +114,6 @@
this.LinkTextBox.Name = "LinkTextBox";
this.LinkTextBox.Size = new System.Drawing.Size(545, 23);
this.LinkTextBox.TabIndex = 4;
this.LinkTextBox.TextChanged += new System.EventHandler(this.ListTextBox_TextChanged);
//
// LinkLabel
//

View File

@@ -105,43 +105,27 @@ namespace Netch.Forms
if (!LinkTextBox.Text.StartsWith("HTTP://", StringComparison.OrdinalIgnoreCase) && !LinkTextBox.Text.StartsWith("HTTPS://", StringComparison.OrdinalIgnoreCase))
{
MessageBoxX.Show(i18N.Translate("Links must start with http:// or https://"));
MessageBoxX.Show(i18N.Translate("Link must start with http:// or https://"));
return;
}
// 备注重复的订阅项
var duplicateRemarkItems = Global.Settings.SubscribeLink.Where(link => link.Remark.Equals(RemarkLabel.Text));
// 链接重复的订阅项
SubscribeLink duplicateLinkItem = null;
try
{
duplicateLinkItem = Global.Settings.SubscribeLink.First(link => link.Link.Equals(LinkTextBox.Text));
}
catch
{
// ignored
}
if (duplicateRemarkItems.Any())
if (Global.Settings.SubscribeLink.Any(link => link.Remark.Equals(RemarkTextBox.Text)))
{
MessageBoxX.Show("Remark Name Duplicate!");
return;
}
if (duplicateLinkItem != null)
if (_editingIndex == -1)
{
if (duplicateLinkItem.Remark != RemarkTextBox.Text)
Global.Settings.SubscribeLink.Add(new SubscribeLink
{
RenameServersGroup(duplicateLinkItem.Remark, RemarkTextBox.Text);
}
duplicateLinkItem.Remark = RemarkTextBox.Text;
duplicateLinkItem.UserAgent = UserAgentTextBox.Text;
Remark = RemarkTextBox.Text,
Link = LinkTextBox.Text,
UserAgent = UserAgentTextBox.Text
});
}
else if (_editingIndex != -1)
else
{
// 只修改备注/未修改被上面处理
var target = Global.Settings.SubscribeLink[_editingIndex];
if (MessageBox.Show(i18N.Translate("Delete the corresponding group of items in the server list?"), i18N.Translate("Confirm"), MessageBoxButtons.YesNo) == DialogResult.Yes)
{
@@ -156,15 +140,6 @@ namespace Netch.Forms
target.Remark = RemarkTextBox.Text;
target.UserAgent = UserAgentTextBox.Text;
}
else
{
Global.Settings.SubscribeLink.Add(new SubscribeLink
{
Remark = RemarkTextBox.Text,
Link = LinkTextBox.Text,
UserAgent = UserAgentTextBox.Text
});
}
Configuration.Save();
Global.Settings.UseProxyToUpdateSubscription = UseSelectedServerCheckBox.Checked;
@@ -260,17 +235,5 @@ namespace Netch.Forms
{
ResetEditingGroup();
}
private void ListTextBox_TextChanged(object sender, EventArgs e)
{
for (var i = 0; i < SubscribeLinkListView.Items.Count; i++)
{
if (((TextBox) sender).Text == SubscribeLinkListView.Items[i].SubItems[1].Text)
{
_editingIndex = i;
AddSubscriptionBox.Text = SubscribeLinkListView.Items[i].SubItems[0].Text;
}
}
}
}
}

View File

@@ -28,17 +28,10 @@ namespace Netch
public static class Flags
{
static Flags()
{
Task.Run(() =>
{
SupportFakeDns = new TUNTAPController().TestFakeDNS();
IsWindows10Upper = Environment.OSVersion.Version.Major >= 10;
});
}
public static bool SupportFakeDns => _supportFakeDns ??= new TUNTAPController().TestFakeDNS();
public static readonly bool IsWindows10Upper = Environment.OSVersion.Version.Major >= 10;
public static bool SupportFakeDns;
public static bool IsWindows10Upper;
private static bool? _supportFakeDns;
}
/// <summary>

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic;
using Netch.Controllers;
using Newtonsoft.Json.Linq;
namespace Netch.Models
@@ -20,20 +21,22 @@ namespace Netch.Models
/// </summary>
string FullName { get; }
string ShortName { get; }
/// <summary>
/// Support URI
/// </summary>
string[] UriScheme { get; }
Server ParseJObject(JObject j);
Server ParseJObject(in JObject j);
public void Edit(Server s);
public void Create();
string GetShareLink(Server server);
string GetShareLink(Server s);
public abstract ServerController GetController();
public abstract IServerController GetController();
public abstract IEnumerable<Server> ParseUri(string text);

View File

@@ -1,5 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Netch.Utils;
namespace Netch.Models
{
@@ -31,6 +33,20 @@ namespace Netch.Models
/// </summary>
public int Type = 0;
public bool SupportSocks5Auth => Type switch
{
0 => true,
_ => false
};
public bool TestNatRequired => Type switch
{
0 => true,
1 => true,
2 => true,
_ => false
};
/// <summary>
/// 绕过中国0. 不绕过 1. 绕过)
/// </summary>
@@ -41,13 +57,72 @@ namespace Netch.Models
/// </summary>
public readonly List<string> Rule = new List<string>();
public List<string> FullRule
{
get
{
var result = new List<string>();
foreach (var s in Rule)
{
if (string.IsNullOrWhiteSpace(s))
continue;
if (s.StartsWith("//"))
continue;
if (s.StartsWith("#include"))
{
var relativePath = new StringBuilder(s.Substring(8).Trim());
relativePath.Replace("<", "");
relativePath.Replace(">", "");
relativePath.Replace(".h", ".txt");
var mode = Global.Modes.FirstOrDefault(m => m.RelativePath.Equals(relativePath.ToString()));
if (mode == null)
{
Logging.Warning($"{relativePath} file included in {Remark} not found");
}
else if (mode == this)
{
Logging.Warning("Can't self-reference");
}
else
{
if (mode.Type != Type)
{
Logging.Warning($"{mode.Remark}'s mode is not as same as {Remark}'s mode");
}
else
{
if (mode.Rule.Any(rule => rule.StartsWith("#include")))
{
Logging.Warning("Cannot reference mode that reference other mode");
}
else
{
result.AddRange(mode.FullRule);
}
}
}
}
else
{
result.Add(s);
}
}
return result;
}
}
/// <summary>
/// 获取备注
/// </summary>
/// <returns>备注</returns>
public override string ToString()
{
return $"[{Type + 1}] {Remark}";
return $"[{Type + 1}] {i18N.Translate(Remark)}";
}
/// <summary>

View File

@@ -34,20 +34,13 @@ namespace Netch.Models
/// <summary>
/// 端口
/// </summary>
public int Port;
public ushort Port;
/// <summary>
/// 延迟
/// </summary>
public int Delay = -1;
/// <summary>
/// 地区
/// </summary>
public string Country;
public bool IsSocks5() => Type == "Socks5";
/// <summary>
/// 获取备注
/// </summary>
@@ -59,28 +52,9 @@ namespace Netch.Models
Remark = $"{Hostname}:{Port}";
}
if (Country == null)
{
Country = Utils.Utils.GetCityCode(Hostname);
}
Group = Group.Equals("None") || Group.Equals("") ? "NONE" : Group;
switch (Type)
{
case "Socks5":
return $"[S5][{Country}][{Group}] {Remark}";
case "SS":
return $"[SS][{Country}][{Group}] {Remark}";
case "SSR":
return $"[SR][{Country}][{Group}] {Remark}";
case "VMess":
return $"[V2][{Country}][{Group}] {Remark}";
case "Trojan":
return $"[TR][{Country}][{Group}] {Remark}";
default:
return "WTF";
}
return $"[{ServerHelper.GetUtilByTypeName(Type)?.ShortName ?? "WTF"}][{Group}] {Remark}";
}
/// <summary>
@@ -125,4 +99,12 @@ namespace Netch.Models
}
}
}
public static class ServerExtension
{
public static string AutoResolveHostname(this Server server)
{
return Global.Settings.ResolveServerHostname ? DNS.Lookup(server.Hostname).ToString() : server.Hostname;
}
}
}

View File

@@ -1,32 +0,0 @@
using Netch.Controllers;
namespace Netch.Models
{
public abstract class ServerController : Controller
{
private int? _socks5Port;
public int Socks5LocalPort
{
get => _socks5Port ?? Global.Settings.Socks5LocalPort;
set => _socks5Port = value;
}
private string _localAddress;
public string LocalAddress
{
get => _localAddress ?? Global.Settings.LocalAddress;
set => _localAddress = value;
}
/// <summary>
/// 启动
/// </summary>
/// <param name="server">服务器</param>
/// <param name="mode">模式</param>
/// <returns>是否启动成功</returns>
public abstract bool Start(Server server, Mode mode);
}
}

View File

@@ -43,6 +43,30 @@ namespace Netch.Models
public bool UseFakeDNS = false;
}
public class KcpConfig
{
public int mtu = 1350;
public int tti = 50;
public int uplinkCapacity = 12;
public int downlinkCapacity = 100;
public bool congestion = false;
public int readBufferSize = 2;
public int writeBufferSize = 2;
}
public class V2rayConfig
{
public bool AllowInsecure = true;
public KcpConfig KcpConfig = new KcpConfig();
}
/// <summary>
/// 用于读取和写入的配置的类
/// </summary>
@@ -103,6 +127,11 @@ namespace Netch.Models
/// </summary>
public bool ModifySystemDNS = false;
/// <summary>
/// 解析服务器主机名
/// </summary>
public bool ResolveServerHostname = false;
/// <summary>
/// 网页请求超时 毫秒
/// </summary>
@@ -111,22 +140,22 @@ namespace Netch.Models
/// <summary>
/// HTTP 本地端口
/// </summary>
public int HTTPLocalPort = 2802;
public ushort HTTPLocalPort = 2802;
/// <summary>
/// Socks5 本地端口
/// </summary>
public int Socks5LocalPort = 2801;
public ushort Socks5LocalPort = 2801;
/// <summary>
/// Redirector TCP 占用端口
/// </summary>
public int RedirectorTCPPort = 3901;
public ushort RedirectorTCPPort = 3901;
/// <summary>
/// UDP Socket 占用端口
/// </summary>
public int UDPSocketPort = 18291;
public ushort UDPSocketPort = 18291;
/// <summary>
/// HTTP 和 Socks5 本地代理地址
@@ -196,11 +225,13 @@ namespace Netch.Models
/// <summary>
/// 是否使用DLL启动Shadowsocks
/// </summary>
public bool BootShadowsocksFromDLL = false;
public bool BootShadowsocksFromDLL = true;
/// <summary>
/// 语言设置
/// </summary>
public string Language = "System";
public V2rayConfig V2RayConfig = new V2rayConfig();
}
}

View File

@@ -1,7 +1,7 @@
using System;
using NETCONLib;
namespace WinFW
namespace Netch.Models.WinFW
{
public class NetworkConnection : INetConnection, INetConnectionProps, INetSharingConfiguration
{

View File

@@ -1,8 +1,8 @@
using System.Collections;
using System.Collections;
using System.Linq;
using NETCONLib;
using NETCONLib;
namespace WinFW
namespace Netch.Models.WinFW
{
/// <summary>
/// A collection that stores 'NetworkConnection' objects.

View File

@@ -2,18 +2,6 @@
namespace Netch
{
public enum NameList : int
{
TYPE_FILTERLOOPBACK,
TYPE_FILTERTCP,
TYPE_FILTERUDP,
TYPE_TCPHOST,
TYPE_UDPHOST,
TYPE_ADDNAME,
TYPE_BYPNAME,
TYPE_CLRNAME
}
public static class NativeMethods
{
/// <summary>
@@ -66,5 +54,11 @@ namespace Netch
[DllImport("dnsapi", EntryPoint = "DnsFlushResolverCache")]
public static extern uint FlushDNSResolverCache();
[DllImport("kernel32.dll")]
public static extern bool AllocConsole();
[DllImport("kernel32.dll")]
public static extern bool AttachConsole(int dwProcessId);
}
}

View File

@@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
@@ -17,6 +18,12 @@ namespace Netch
[STAThread]
public static void Main(string[] args)
{
if (args.Contains("-console"))
{
NativeMethods.AllocConsole();
NativeMethods.AttachConsole(-1);
}
// 创建互斥体防止多次运行
using (var mutex = new Mutex(false, "Global\\Netch"))
{

View File

@@ -66,12 +66,11 @@
<ItemGroup>
<PackageReference Include="ILMerge" Version="3.0.41" />
<PackageReference Include="IPNetwork2" Version="2.5.211" />
<PackageReference Include="MaxMind.GeoIP2" Version="3.2.0" />
<PackageReference Include="Microsoft.Diagnostics.Tracing.TraceEvent" Version="2.0.58" />
<PackageReference Include="MaxMind.GeoIP2" Version="3.3.0" />
<PackageReference Include="Microsoft.Diagnostics.Tracing.TraceEvent" Version="2.0.61" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="System.Collections.Immutable" Version="5.0.0-preview.8.20407.11" />
<PackageReference Include="System.Reflection.Metadata" Version="5.0.0-preview.8.20407.11" />
<PackageReference Include="System.Collections.Immutable" Version="5.0.0-rc.2.20475.5" />
<PackageReference Include="System.Reflection.Metadata" Version="5.0.0-rc.2.20475.5" />
<PackageReference Include="WindowsAPICodePack-Shell" Version="1.1.1" />
</ItemGroup>

View File

@@ -11,18 +11,12 @@
"Stop": "停止",
"Waiting for command": "等待命令中",
"Starting": "正在启动中",
"Start failed": "启动失败请打开软件目录logging文件夹查看日志",
"Start failed": "启动失败",
"Started": "已启动",
"Stopping": "正在停止中",
"Stopped": "已停止",
"Starting ": "正在启动 ",
"Starting Tap": "正在启动 TUN/TAP",
"Starting {0}": "正在启动 {0}",
"Starting NatTester": "正在启动 NAT 测试",
"Starting LocalDns service": "正在启动本地 DNS 服务",
"Starting Redirector": "正在启动 Redirector",
"Restarting Redirector": "正常启动失败,正在尝试重新启动 Redirector",
"Starting netfilter2 Service": "正在启动 netfilter2 服务",
"Starting dns Service": "正在启动 DNS 服务",
"SetupBypass": "设置绕行规则",
"Test failed": "测试失败",
"Starting update subscription": "正在更新订阅",
@@ -78,9 +72,11 @@
"Update servers error from {0}": "从 {0} 更新服务器失败",
"Options": "选项",
"Uninstall NF Service": "卸载 NF 服务",
"Uninstalling NF Service": "正在卸载 NF 服务中",
"Service has been uninstalled": "服务已卸载",
"NF Service": "NF 服务",
"TUN/TAP driver": "TUN/TAP 驱动",
"Uninstall {0}": "卸载 {0}",
"Uninstalling {0}": "正在卸载 {0} 中",
"{0} has been uninstalled": "{0} 已卸载",
"Reload Modes": "重载模式",
"Modes have been reload": "模式已重载",
"Clean DNS Cache": "清理 DNS 缓存",
@@ -89,10 +85,6 @@
"Update ACL with proxy": "使用代理更新 ACL 规则",
"ACL updated successfully": "ACL 更新成功",
"ACL update failed": "ACL 更新失败",
"Reinstall TUN/TAP driver": "重新安装 TUN/TAP 驱动",
"Reinstall TUN/TAP driver successfully": "重装 TUN/TAP 驱动成功",
"Reinstall TUN/TAP driver failed": "重装 TUN/TAP 驱动失败",
"Reinstalling TUN/TAP driver": "正在重装 TUN/TAP 驱动",
"Open Directory": "打开目录",
"About": "关于",
@@ -118,8 +110,6 @@
"Remark": "备注",
"Filename": "文件名",
"Use Custom Filename": "使用自定义文件名",
"Stay the same": "保持一致",
"Time data": "时间数据",
"Add": "添加",
"Scan": "扫描",
"Save": "保存",
@@ -163,7 +153,7 @@
"Check update when opened": "打开软件时检查更新",
"Check Beta update": "检查 Beta 更新",
"Update subscribeat when opened": "自动更新订阅",
"SS DLL(No ACL support)": "SS DLL(不支持 ACL",
"SS DLL": "SS DLL",
"Modify System DNS": "修改系统 DNS",
"ProfileCount": "快捷配置数量",
"ProfileCount value illegal. Try again.": "快捷配置数值非法。请重试。",
@@ -178,6 +168,8 @@
"STUN Server Port": "STUN 服务器端口",
"Custom ACL": "自定义 ACL 规则",
"Language": "语言",
"Tap Network Sharing": "Tap 网络共享",
"Resolve Server Hostname": "解析服务器主机名",
"Profile": "配置名",
"Profiles": "配置",
@@ -189,10 +181,10 @@
"The {0} port is in use.": "{0} 端口已被占用",
"Bypass LAN": "[网页代理] 绕过局域网",
"Bypass LAN (Non System Proxy)": "[网页代理] 绕过局域网(不设置系统代理)",
"Bypass LAN (TUN/TAP)": "[TUN/TAP] 绕过局域网",
"Bypass LAN and China": "[网页代理] 绕过局域网和中国大陆",
"Bypass LAN and China (Non System Proxy)": "[网页代理] 绕过局域网和中国大陆 (不设置系统代理)",
"Bypass LAN and China (TUN/TAP)": "[TUN/TAP] 绕过局域网和中国大陆"
"[Web Proxy] Bypass LAN": "[网页代理] 绕过局域网",
"[Non Web Proxy] Bypass LAN": "[不设置代理] 绕过局域网",
"[TUN/TAP] Bypass LAN": "[TUN/TAP] 绕过局域网",
"[Web Proxy] Bypass LAN and China": "[网页代理] 绕过局域网和中国大陆",
"[Non Web Proxy] Bypass LAN and China": "[不设置代理] 绕过局域网和中国大陆",
"[TUN/TAP] Bypass LAN and China": "[TUN/TAP] 绕过局域网和中国大陆"
}

View File

@@ -1,247 +0,0 @@
namespace Netch.ServerEx.Shadowsocks.Form
{
partial class ShadowsocksForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ShadowsocksForm));
this.ConfigurationGroupBox = new System.Windows.Forms.GroupBox();
this.PluginOptionsTextBox = new System.Windows.Forms.TextBox();
this.PluginOptionsLabel = new System.Windows.Forms.Label();
this.PluginTextBox = new System.Windows.Forms.TextBox();
this.PluginLabel = new System.Windows.Forms.Label();
this.EncryptMethodLabel = new System.Windows.Forms.Label();
this.EncryptMethodComboBox = new System.Windows.Forms.ComboBox();
this.PasswordTextBox = new System.Windows.Forms.TextBox();
this.PasswordLabel = new System.Windows.Forms.Label();
this.AddressLabel = new System.Windows.Forms.Label();
this.PortTextBox = new System.Windows.Forms.TextBox();
this.AddressTextBox = new System.Windows.Forms.TextBox();
this.RemarkTextBox = new System.Windows.Forms.TextBox();
this.RemarkLabel = new System.Windows.Forms.Label();
this.PortLabel = new System.Windows.Forms.Label();
this.ControlButton = new System.Windows.Forms.Button();
this.ConfigurationGroupBox.SuspendLayout();
this.SuspendLayout();
//
// ConfigurationGroupBox
//
this.ConfigurationGroupBox.Controls.Add(this.PluginOptionsTextBox);
this.ConfigurationGroupBox.Controls.Add(this.PluginOptionsLabel);
this.ConfigurationGroupBox.Controls.Add(this.PluginTextBox);
this.ConfigurationGroupBox.Controls.Add(this.PluginLabel);
this.ConfigurationGroupBox.Controls.Add(this.EncryptMethodLabel);
this.ConfigurationGroupBox.Controls.Add(this.EncryptMethodComboBox);
this.ConfigurationGroupBox.Controls.Add(this.PasswordTextBox);
this.ConfigurationGroupBox.Controls.Add(this.PasswordLabel);
this.ConfigurationGroupBox.Controls.Add(this.AddressLabel);
this.ConfigurationGroupBox.Controls.Add(this.PortTextBox);
this.ConfigurationGroupBox.Controls.Add(this.AddressTextBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkTextBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkLabel);
this.ConfigurationGroupBox.Controls.Add(this.PortLabel);
this.ConfigurationGroupBox.Location = new System.Drawing.Point(12, 12);
this.ConfigurationGroupBox.Name = "ConfigurationGroupBox";
this.ConfigurationGroupBox.Size = new System.Drawing.Size(420, 197);
this.ConfigurationGroupBox.TabIndex = 0;
this.ConfigurationGroupBox.TabStop = false;
this.ConfigurationGroupBox.Text = "Configuration";
//
// PluginOptionsTextBox
//
this.PluginOptionsTextBox.Location = new System.Drawing.Point(120, 166);
this.PluginOptionsTextBox.Name = "PluginOptionsTextBox";
this.PluginOptionsTextBox.Size = new System.Drawing.Size(294, 23);
this.PluginOptionsTextBox.TabIndex = 13;
this.PluginOptionsTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// PluginOptionsLabel
//
this.PluginOptionsLabel.AutoSize = true;
this.PluginOptionsLabel.Location = new System.Drawing.Point(10, 169);
this.PluginOptionsLabel.Name = "PluginOptionsLabel";
this.PluginOptionsLabel.Size = new System.Drawing.Size(93, 17);
this.PluginOptionsLabel.TabIndex = 12;
this.PluginOptionsLabel.Text = "Plugin Options";
//
// PluginTextBox
//
this.PluginTextBox.Location = new System.Drawing.Point(120, 137);
this.PluginTextBox.Name = "PluginTextBox";
this.PluginTextBox.Size = new System.Drawing.Size(294, 23);
this.PluginTextBox.TabIndex = 11;
this.PluginTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// PluginLabel
//
this.PluginLabel.AutoSize = true;
this.PluginLabel.Location = new System.Drawing.Point(10, 140);
this.PluginLabel.Name = "PluginLabel";
this.PluginLabel.Size = new System.Drawing.Size(43, 17);
this.PluginLabel.TabIndex = 10;
this.PluginLabel.Text = "Plugin";
//
// EncryptMethodLabel
//
this.EncryptMethodLabel.AutoSize = true;
this.EncryptMethodLabel.Location = new System.Drawing.Point(10, 110);
this.EncryptMethodLabel.Name = "EncryptMethodLabel";
this.EncryptMethodLabel.Size = new System.Drawing.Size(101, 17);
this.EncryptMethodLabel.TabIndex = 8;
this.EncryptMethodLabel.Text = "Encrypt Method";
//
// EncryptMethodComboBox
//
this.EncryptMethodComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.EncryptMethodComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.EncryptMethodComboBox.FormattingEnabled = true;
this.EncryptMethodComboBox.Location = new System.Drawing.Point(120, 106);
this.EncryptMethodComboBox.Name = "EncryptMethodComboBox";
this.EncryptMethodComboBox.Size = new System.Drawing.Size(294, 24);
this.EncryptMethodComboBox.TabIndex = 9;
this.EncryptMethodComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ComboBox_DrawItem);
//
// PasswordTextBox
//
this.PasswordTextBox.Location = new System.Drawing.Point(120, 77);
this.PasswordTextBox.Name = "PasswordTextBox";
this.PasswordTextBox.Size = new System.Drawing.Size(294, 23);
this.PasswordTextBox.TabIndex = 7;
this.PasswordTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// PasswordLabel
//
this.PasswordLabel.AutoSize = true;
this.PasswordLabel.Location = new System.Drawing.Point(10, 80);
this.PasswordLabel.Name = "PasswordLabel";
this.PasswordLabel.Size = new System.Drawing.Size(64, 17);
this.PasswordLabel.TabIndex = 6;
this.PasswordLabel.Text = "Password";
//
// AddressLabel
//
this.AddressLabel.AutoSize = true;
this.AddressLabel.Location = new System.Drawing.Point(10, 51);
this.AddressLabel.Name = "AddressLabel";
this.AddressLabel.Size = new System.Drawing.Size(56, 17);
this.AddressLabel.TabIndex = 2;
this.AddressLabel.Text = "Address";
//
// PortTextBox
//
this.PortTextBox.Location = new System.Drawing.Point(358, 48);
this.PortTextBox.Name = "PortTextBox";
this.PortTextBox.Size = new System.Drawing.Size(56, 23);
this.PortTextBox.TabIndex = 5;
this.PortTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// AddressTextBox
//
this.AddressTextBox.Location = new System.Drawing.Point(120, 48);
this.AddressTextBox.Name = "AddressTextBox";
this.AddressTextBox.Size = new System.Drawing.Size(232, 23);
this.AddressTextBox.TabIndex = 3;
this.AddressTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// RemarkTextBox
//
this.RemarkTextBox.Location = new System.Drawing.Point(120, 19);
this.RemarkTextBox.Name = "RemarkTextBox";
this.RemarkTextBox.Size = new System.Drawing.Size(294, 23);
this.RemarkTextBox.TabIndex = 1;
this.RemarkTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// RemarkLabel
//
this.RemarkLabel.AutoSize = true;
this.RemarkLabel.Location = new System.Drawing.Point(10, 22);
this.RemarkLabel.Name = "RemarkLabel";
this.RemarkLabel.Size = new System.Drawing.Size(53, 17);
this.RemarkLabel.TabIndex = 0;
this.RemarkLabel.Text = "Remark";
//
// PortLabel
//
this.PortLabel.AutoSize = true;
this.PortLabel.Location = new System.Drawing.Point(351, 51);
this.PortLabel.Name = "PortLabel";
this.PortLabel.Size = new System.Drawing.Size(11, 17);
this.PortLabel.TabIndex = 4;
this.PortLabel.Text = ":";
//
// ControlButton
//
this.ControlButton.Location = new System.Drawing.Point(357, 215);
this.ControlButton.Name = "ControlButton";
this.ControlButton.Size = new System.Drawing.Size(75, 23);
this.ControlButton.TabIndex = 1;
this.ControlButton.Text = "Save";
this.ControlButton.UseVisualStyleBackColor = true;
this.ControlButton.Click += new System.EventHandler(this.ControlButton_Click);
//
// Shadowsocks
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(444, 248);
this.Controls.Add(this.ControlButton);
this.Controls.Add(this.ConfigurationGroupBox);
this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.MaximizeBox = false;
this.Name = "ShadowsocksForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Shadowsocks";
this.Load += new System.EventHandler(this.Shadowsocks_Load);
this.ConfigurationGroupBox.ResumeLayout(false);
this.ConfigurationGroupBox.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox ConfigurationGroupBox;
private System.Windows.Forms.Button ControlButton;
private System.Windows.Forms.Label RemarkLabel;
private System.Windows.Forms.TextBox RemarkTextBox;
private System.Windows.Forms.Label PortLabel;
private System.Windows.Forms.TextBox AddressTextBox;
private System.Windows.Forms.TextBox PortTextBox;
private System.Windows.Forms.Label AddressLabel;
private System.Windows.Forms.Label EncryptMethodLabel;
private System.Windows.Forms.ComboBox EncryptMethodComboBox;
private System.Windows.Forms.TextBox PasswordTextBox;
private System.Windows.Forms.Label PasswordLabel;
private System.Windows.Forms.TextBox PluginOptionsTextBox;
private System.Windows.Forms.Label PluginOptionsLabel;
private System.Windows.Forms.TextBox PluginTextBox;
private System.Windows.Forms.Label PluginLabel;
}
}

View File

@@ -1,59 +0,0 @@
using System;
using System.Windows.Forms;
using Netch.Utils;
namespace Netch.ServerEx.Shadowsocks.Form
{
public partial class ShadowsocksForm : System.Windows.Forms.Form
{
private readonly Shadowsocks _server;
public ShadowsocksForm(Shadowsocks server = default)
{
InitializeComponent();
_server = server ?? new Shadowsocks();
}
private void Shadowsocks_Load(object sender, EventArgs e)
{
i18N.TranslateForm(this);
EncryptMethodComboBox.Items.AddRange(SSGlobal.EncryptMethods.ToArray());
RemarkTextBox.Text = _server.Remark;
AddressTextBox.Text = _server.Hostname;
PortTextBox.Text = _server.Port.ToString();
PasswordTextBox.Text = _server.Password;
EncryptMethodComboBox.SelectedIndex = SSGlobal.EncryptMethods.IndexOf(_server.EncryptMethod);
PluginTextBox.Text = _server.Plugin;
PluginOptionsTextBox.Text = _server.PluginOption;
}
private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
Utils.Utils.DrawCenterComboBox(sender, e);
}
private void ControlButton_Click(object sender, EventArgs e)
{
if (!ushort.TryParse(PortTextBox.Text, out var port)) return;
_server.Remark = RemarkTextBox.Text;
_server.Type = "SS";
_server.Hostname = AddressTextBox.Text;
_server.Port = port;
_server.Password = PasswordTextBox.Text;
_server.EncryptMethod = EncryptMethodComboBox.Text;
_server.Plugin = PluginTextBox.Text;
_server.PluginOption = PluginOptionsTextBox.Text;
_server.Country = null;
if (Global.Settings.Server.IndexOf(_server) == -1)
Global.Settings.Server.Add(_server);
MessageBoxX.Show(i18N.Translate("Saved"));
Close();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,299 +0,0 @@
namespace Netch.ServerEx.ShadowsocksR.Form
{
partial class ShadowsocksRForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ShadowsocksRForm));
this.ConfigurationGroupBox = new System.Windows.Forms.GroupBox();
this.OBFSParamLabel = new System.Windows.Forms.Label();
this.OBFSOptionParamTextBox = new System.Windows.Forms.TextBox();
this.OBFSLabel = new System.Windows.Forms.Label();
this.OBFSComboBox = new System.Windows.Forms.ComboBox();
this.ProtocolParamLabel = new System.Windows.Forms.Label();
this.ProtocolParamTextBox = new System.Windows.Forms.TextBox();
this.ProtocolLabel = new System.Windows.Forms.Label();
this.ProtocolComboBox = new System.Windows.Forms.ComboBox();
this.EncryptMethodLabel = new System.Windows.Forms.Label();
this.EncryptMethodComboBox = new System.Windows.Forms.ComboBox();
this.PasswordTextBox = new System.Windows.Forms.TextBox();
this.PasswordLabel = new System.Windows.Forms.Label();
this.AddressLabel = new System.Windows.Forms.Label();
this.PortTextBox = new System.Windows.Forms.TextBox();
this.AddressTextBox = new System.Windows.Forms.TextBox();
this.RemarkTextBox = new System.Windows.Forms.TextBox();
this.RemarkLabel = new System.Windows.Forms.Label();
this.PortLabel = new System.Windows.Forms.Label();
this.ControlButton = new System.Windows.Forms.Button();
this.ConfigurationGroupBox.SuspendLayout();
this.SuspendLayout();
//
// ConfigurationGroupBox
//
this.ConfigurationGroupBox.Controls.Add(this.OBFSParamLabel);
this.ConfigurationGroupBox.Controls.Add(this.OBFSOptionParamTextBox);
this.ConfigurationGroupBox.Controls.Add(this.OBFSLabel);
this.ConfigurationGroupBox.Controls.Add(this.OBFSComboBox);
this.ConfigurationGroupBox.Controls.Add(this.ProtocolParamLabel);
this.ConfigurationGroupBox.Controls.Add(this.ProtocolParamTextBox);
this.ConfigurationGroupBox.Controls.Add(this.ProtocolLabel);
this.ConfigurationGroupBox.Controls.Add(this.ProtocolComboBox);
this.ConfigurationGroupBox.Controls.Add(this.EncryptMethodLabel);
this.ConfigurationGroupBox.Controls.Add(this.EncryptMethodComboBox);
this.ConfigurationGroupBox.Controls.Add(this.PasswordTextBox);
this.ConfigurationGroupBox.Controls.Add(this.PasswordLabel);
this.ConfigurationGroupBox.Controls.Add(this.AddressLabel);
this.ConfigurationGroupBox.Controls.Add(this.PortTextBox);
this.ConfigurationGroupBox.Controls.Add(this.AddressTextBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkTextBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkLabel);
this.ConfigurationGroupBox.Controls.Add(this.PortLabel);
this.ConfigurationGroupBox.Location = new System.Drawing.Point(12, 12);
this.ConfigurationGroupBox.Name = "ConfigurationGroupBox";
this.ConfigurationGroupBox.Size = new System.Drawing.Size(420, 258);
this.ConfigurationGroupBox.TabIndex = 0;
this.ConfigurationGroupBox.TabStop = false;
this.ConfigurationGroupBox.Text = "Configuration";
//
// OBFSParamLabel
//
this.OBFSParamLabel.AutoSize = true;
this.OBFSParamLabel.Location = new System.Drawing.Point(10, 230);
this.OBFSParamLabel.Name = "OBFSParamLabel";
this.OBFSParamLabel.Size = new System.Drawing.Size(80, 17);
this.OBFSParamLabel.TabIndex = 16;
this.OBFSParamLabel.Text = "OBFS Param";
//
// OBFSParamTextBox
//
this.OBFSOptionParamTextBox.Location = new System.Drawing.Point(120, 227);
this.OBFSOptionParamTextBox.Name = "OBFSParamTextBox";
this.OBFSOptionParamTextBox.Size = new System.Drawing.Size(294, 23);
this.OBFSOptionParamTextBox.TabIndex = 17;
this.OBFSOptionParamTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// OBFSLabel
//
this.OBFSLabel.AutoSize = true;
this.OBFSLabel.Location = new System.Drawing.Point(10, 200);
this.OBFSLabel.Name = "OBFSLabel";
this.OBFSLabel.Size = new System.Drawing.Size(39, 17);
this.OBFSLabel.TabIndex = 14;
this.OBFSLabel.Text = "OBFS";
//
// OBFSComboBox
//
this.OBFSComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.OBFSComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.OBFSComboBox.FormattingEnabled = true;
this.OBFSComboBox.Location = new System.Drawing.Point(120, 196);
this.OBFSComboBox.Name = "OBFSComboBox";
this.OBFSComboBox.Size = new System.Drawing.Size(294, 24);
this.OBFSComboBox.TabIndex = 15;
this.OBFSComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ComboBox_DrawItem);
//
// ProtocolParamLabel
//
this.ProtocolParamLabel.AutoSize = true;
this.ProtocolParamLabel.Location = new System.Drawing.Point(10, 170);
this.ProtocolParamLabel.Name = "ProtocolParamLabel";
this.ProtocolParamLabel.Size = new System.Drawing.Size(98, 17);
this.ProtocolParamLabel.TabIndex = 12;
this.ProtocolParamLabel.Text = "Protocol Param";
//
// ProtocolParamTextBox
//
this.ProtocolParamTextBox.Location = new System.Drawing.Point(120, 167);
this.ProtocolParamTextBox.Name = "ProtocolParamTextBox";
this.ProtocolParamTextBox.Size = new System.Drawing.Size(294, 23);
this.ProtocolParamTextBox.TabIndex = 13;
this.ProtocolParamTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// ProtocolLabel
//
this.ProtocolLabel.AutoSize = true;
this.ProtocolLabel.Location = new System.Drawing.Point(10, 140);
this.ProtocolLabel.Name = "ProtocolLabel";
this.ProtocolLabel.Size = new System.Drawing.Size(57, 17);
this.ProtocolLabel.TabIndex = 10;
this.ProtocolLabel.Text = "Protocol";
//
// ProtocolComboBox
//
this.ProtocolComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.ProtocolComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ProtocolComboBox.FormattingEnabled = true;
this.ProtocolComboBox.Location = new System.Drawing.Point(120, 136);
this.ProtocolComboBox.Name = "ProtocolComboBox";
this.ProtocolComboBox.Size = new System.Drawing.Size(294, 24);
this.ProtocolComboBox.TabIndex = 11;
this.ProtocolComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ComboBox_DrawItem);
//
// EncryptMethodLabel
//
this.EncryptMethodLabel.AutoSize = true;
this.EncryptMethodLabel.Location = new System.Drawing.Point(10, 110);
this.EncryptMethodLabel.Name = "EncryptMethodLabel";
this.EncryptMethodLabel.Size = new System.Drawing.Size(101, 17);
this.EncryptMethodLabel.TabIndex = 8;
this.EncryptMethodLabel.Text = "Encrypt Method";
//
// EncryptMethodComboBox
//
this.EncryptMethodComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.EncryptMethodComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.EncryptMethodComboBox.FormattingEnabled = true;
this.EncryptMethodComboBox.Location = new System.Drawing.Point(120, 106);
this.EncryptMethodComboBox.Name = "EncryptMethodComboBox";
this.EncryptMethodComboBox.Size = new System.Drawing.Size(294, 24);
this.EncryptMethodComboBox.TabIndex = 9;
this.EncryptMethodComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ComboBox_DrawItem);
//
// PasswordTextBox
//
this.PasswordTextBox.Location = new System.Drawing.Point(120, 77);
this.PasswordTextBox.Name = "PasswordTextBox";
this.PasswordTextBox.Size = new System.Drawing.Size(294, 23);
this.PasswordTextBox.TabIndex = 7;
this.PasswordTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// PasswordLabel
//
this.PasswordLabel.AutoSize = true;
this.PasswordLabel.Location = new System.Drawing.Point(10, 80);
this.PasswordLabel.Name = "PasswordLabel";
this.PasswordLabel.Size = new System.Drawing.Size(64, 17);
this.PasswordLabel.TabIndex = 6;
this.PasswordLabel.Text = "Password";
//
// AddressLabel
//
this.AddressLabel.AutoSize = true;
this.AddressLabel.Location = new System.Drawing.Point(10, 51);
this.AddressLabel.Name = "AddressLabel";
this.AddressLabel.Size = new System.Drawing.Size(56, 17);
this.AddressLabel.TabIndex = 2;
this.AddressLabel.Text = "Address";
//
// PortTextBox
//
this.PortTextBox.Location = new System.Drawing.Point(358, 48);
this.PortTextBox.Name = "PortTextBox";
this.PortTextBox.Size = new System.Drawing.Size(56, 23);
this.PortTextBox.TabIndex = 5;
this.PortTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// AddressTextBox
//
this.AddressTextBox.Location = new System.Drawing.Point(120, 48);
this.AddressTextBox.Name = "AddressTextBox";
this.AddressTextBox.Size = new System.Drawing.Size(232, 23);
this.AddressTextBox.TabIndex = 3;
this.AddressTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// RemarkTextBox
//
this.RemarkTextBox.Location = new System.Drawing.Point(120, 19);
this.RemarkTextBox.Name = "RemarkTextBox";
this.RemarkTextBox.Size = new System.Drawing.Size(294, 23);
this.RemarkTextBox.TabIndex = 1;
this.RemarkTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// RemarkLabel
//
this.RemarkLabel.AutoSize = true;
this.RemarkLabel.Location = new System.Drawing.Point(10, 22);
this.RemarkLabel.Name = "RemarkLabel";
this.RemarkLabel.Size = new System.Drawing.Size(53, 17);
this.RemarkLabel.TabIndex = 0;
this.RemarkLabel.Text = "Remark";
//
// PortLabel
//
this.PortLabel.AutoSize = true;
this.PortLabel.Location = new System.Drawing.Point(351, 51);
this.PortLabel.Name = "PortLabel";
this.PortLabel.Size = new System.Drawing.Size(11, 17);
this.PortLabel.TabIndex = 4;
this.PortLabel.Text = ":";
//
// ControlButton
//
this.ControlButton.Location = new System.Drawing.Point(357, 276);
this.ControlButton.Name = "ControlButton";
this.ControlButton.Size = new System.Drawing.Size(75, 23);
this.ControlButton.TabIndex = 1;
this.ControlButton.Text = "Save";
this.ControlButton.UseVisualStyleBackColor = true;
this.ControlButton.Click += new System.EventHandler(this.ControlButton_Click);
//
// ShadowsocksR
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(444, 310);
this.Controls.Add(this.ControlButton);
this.Controls.Add(this.ConfigurationGroupBox);
this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.MaximizeBox = false;
this.Name = "ShadowsocksRForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "ShadowsocksR";
this.Load += new System.EventHandler(this.ShadowsocksR_Load);
this.ConfigurationGroupBox.ResumeLayout(false);
this.ConfigurationGroupBox.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox ConfigurationGroupBox;
private System.Windows.Forms.Button ControlButton;
private System.Windows.Forms.Label RemarkLabel;
private System.Windows.Forms.TextBox RemarkTextBox;
private System.Windows.Forms.Label PortLabel;
private System.Windows.Forms.TextBox AddressTextBox;
private System.Windows.Forms.TextBox PortTextBox;
private System.Windows.Forms.Label AddressLabel;
private System.Windows.Forms.Label EncryptMethodLabel;
private System.Windows.Forms.ComboBox EncryptMethodComboBox;
private System.Windows.Forms.TextBox PasswordTextBox;
private System.Windows.Forms.Label PasswordLabel;
private System.Windows.Forms.Label ProtocolLabel;
private System.Windows.Forms.ComboBox ProtocolComboBox;
private System.Windows.Forms.TextBox ProtocolParamTextBox;
private System.Windows.Forms.Label ProtocolParamLabel;
private System.Windows.Forms.Label OBFSLabel;
private System.Windows.Forms.ComboBox OBFSComboBox;
private System.Windows.Forms.TextBox OBFSOptionParamTextBox;
private System.Windows.Forms.Label OBFSParamLabel;
}
}

View File

@@ -1,65 +0,0 @@
using System;
using System.Windows.Forms;
using Netch.Utils;
namespace Netch.ServerEx.ShadowsocksR.Form
{
public partial class ShadowsocksRForm : System.Windows.Forms.Form
{
private readonly ShadowsocksR _server;
public ShadowsocksRForm(Models.Server server = default)
{
InitializeComponent();
_server = (ShadowsocksR) (server ?? new ShadowsocksR());
}
private void ShadowsocksR_Load(object sender, EventArgs e)
{
i18N.TranslateForm(this);
EncryptMethodComboBox.Items.AddRange(SSRGlobal.EncryptMethods.ToArray());
ProtocolComboBox.Items.AddRange(SSRGlobal.Protocols.ToArray());
OBFSComboBox.Items.AddRange(SSRGlobal.OBFSs.ToArray());
RemarkTextBox.Text = _server.Remark;
AddressTextBox.Text = _server.Hostname;
PortTextBox.Text = _server.Port.ToString();
PasswordTextBox.Text = _server.Password;
EncryptMethodComboBox.SelectedIndex = SSRGlobal.EncryptMethods.IndexOf(_server.EncryptMethod);
ProtocolComboBox.SelectedIndex = SSRGlobal.Protocols.IndexOf(_server.Protocol);
ProtocolParamTextBox.Text = _server.ProtocolParam;
OBFSComboBox.SelectedIndex = SSRGlobal.OBFSs.IndexOf(_server.OBFS);
OBFSOptionParamTextBox.Text = _server.OBFSParam;
}
private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
Utils.Utils.DrawCenterComboBox(sender, e);
}
private void ControlButton_Click(object sender, EventArgs e)
{
if (!ushort.TryParse(PortTextBox.Text, out var port)) return;
_server.Remark = RemarkTextBox.Text;
_server.Type = "SSR";
_server.Hostname = AddressTextBox.Text;
_server.Port = port;
_server.Password = PasswordTextBox.Text;
_server.EncryptMethod = EncryptMethodComboBox.Text;
_server.Protocol = ProtocolComboBox.Text;
_server.ProtocolParam = ProtocolParamTextBox.Text;
_server.OBFS = OBFSComboBox.Text;
_server.OBFSParam = OBFSOptionParamTextBox.Text;
_server.Country = null;
if (Global.Settings.Server.IndexOf(_server) == -1)
Global.Settings.Server.Add(_server);
MessageBoxX.Show(i18N.Translate("Saved"));
Close();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,198 +0,0 @@
namespace Netch.ServerEx.Socks5.Form
{
partial class Socks5Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Socks5Form));
this.ConfigurationGroupBox = new System.Windows.Forms.GroupBox();
this.PasswordLabel = new System.Windows.Forms.Label();
this.UsernameTextBox = new System.Windows.Forms.TextBox();
this.PasswordTextBox = new System.Windows.Forms.TextBox();
this.UsernameLabel = new System.Windows.Forms.Label();
this.AddressLabel = new System.Windows.Forms.Label();
this.PortTextBox = new System.Windows.Forms.TextBox();
this.AddressTextBox = new System.Windows.Forms.TextBox();
this.RemarkTextBox = new System.Windows.Forms.TextBox();
this.RemarkLabel = new System.Windows.Forms.Label();
this.PortLabel = new System.Windows.Forms.Label();
this.ControlButton = new System.Windows.Forms.Button();
this.ConfigurationGroupBox.SuspendLayout();
this.SuspendLayout();
//
// ConfigurationGroupBox
//
this.ConfigurationGroupBox.Controls.Add(this.PasswordLabel);
this.ConfigurationGroupBox.Controls.Add(this.UsernameTextBox);
this.ConfigurationGroupBox.Controls.Add(this.PasswordTextBox);
this.ConfigurationGroupBox.Controls.Add(this.UsernameLabel);
this.ConfigurationGroupBox.Controls.Add(this.AddressLabel);
this.ConfigurationGroupBox.Controls.Add(this.PortTextBox);
this.ConfigurationGroupBox.Controls.Add(this.AddressTextBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkTextBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkLabel);
this.ConfigurationGroupBox.Controls.Add(this.PortLabel);
this.ConfigurationGroupBox.Location = new System.Drawing.Point(12, 12);
this.ConfigurationGroupBox.Name = "ConfigurationGroupBox";
this.ConfigurationGroupBox.Size = new System.Drawing.Size(420, 139);
this.ConfigurationGroupBox.TabIndex = 0;
this.ConfigurationGroupBox.TabStop = false;
this.ConfigurationGroupBox.Text = "Configuration";
//
// PasswordLabel
//
this.PasswordLabel.AutoSize = true;
this.PasswordLabel.Location = new System.Drawing.Point(10, 109);
this.PasswordLabel.Name = "PasswordLabel";
this.PasswordLabel.Size = new System.Drawing.Size(64, 17);
this.PasswordLabel.TabIndex = 8;
this.PasswordLabel.Text = "Password";
//
// UsernameTextBox
//
this.UsernameTextBox.Location = new System.Drawing.Point(120, 77);
this.UsernameTextBox.Name = "UsernameTextBox";
this.UsernameTextBox.Size = new System.Drawing.Size(294, 23);
this.UsernameTextBox.TabIndex = 7;
this.UsernameTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// PasswordTextBox
//
this.PasswordTextBox.Location = new System.Drawing.Point(120, 106);
this.PasswordTextBox.Name = "PasswordTextBox";
this.PasswordTextBox.Size = new System.Drawing.Size(294, 23);
this.PasswordTextBox.TabIndex = 9;
this.PasswordTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// UsernameLabel
//
this.UsernameLabel.AutoSize = true;
this.UsernameLabel.Location = new System.Drawing.Point(10, 80);
this.UsernameLabel.Name = "UsernameLabel";
this.UsernameLabel.Size = new System.Drawing.Size(67, 17);
this.UsernameLabel.TabIndex = 6;
this.UsernameLabel.Text = "Username";
//
// AddressLabel
//
this.AddressLabel.AutoSize = true;
this.AddressLabel.Location = new System.Drawing.Point(10, 51);
this.AddressLabel.Name = "AddressLabel";
this.AddressLabel.Size = new System.Drawing.Size(56, 17);
this.AddressLabel.TabIndex = 2;
this.AddressLabel.Text = "Address";
//
// PortTextBox
//
this.PortTextBox.Location = new System.Drawing.Point(358, 48);
this.PortTextBox.Name = "PortTextBox";
this.PortTextBox.Size = new System.Drawing.Size(56, 23);
this.PortTextBox.TabIndex = 5;
this.PortTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// AddressTextBox
//
this.AddressTextBox.Location = new System.Drawing.Point(120, 48);
this.AddressTextBox.Name = "AddressTextBox";
this.AddressTextBox.Size = new System.Drawing.Size(232, 23);
this.AddressTextBox.TabIndex = 3;
this.AddressTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// RemarkTextBox
//
this.RemarkTextBox.Location = new System.Drawing.Point(120, 19);
this.RemarkTextBox.Name = "RemarkTextBox";
this.RemarkTextBox.Size = new System.Drawing.Size(294, 23);
this.RemarkTextBox.TabIndex = 1;
this.RemarkTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// RemarkLabel
//
this.RemarkLabel.AutoSize = true;
this.RemarkLabel.Location = new System.Drawing.Point(10, 22);
this.RemarkLabel.Name = "RemarkLabel";
this.RemarkLabel.Size = new System.Drawing.Size(53, 17);
this.RemarkLabel.TabIndex = 0;
this.RemarkLabel.Text = "Remark";
//
// PortLabel
//
this.PortLabel.AutoSize = true;
this.PortLabel.Location = new System.Drawing.Point(351, 51);
this.PortLabel.Name = "PortLabel";
this.PortLabel.Size = new System.Drawing.Size(11, 17);
this.PortLabel.TabIndex = 4;
this.PortLabel.Text = ":";
//
// ControlButton
//
this.ControlButton.Location = new System.Drawing.Point(357, 157);
this.ControlButton.Name = "ControlButton";
this.ControlButton.Size = new System.Drawing.Size(75, 23);
this.ControlButton.TabIndex = 1;
this.ControlButton.Text = "Save";
this.ControlButton.UseVisualStyleBackColor = true;
this.ControlButton.Click += new System.EventHandler(this.ControlButton_Click);
//
// Socks5
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(444, 192);
this.Controls.Add(this.ControlButton);
this.Controls.Add(this.ConfigurationGroupBox);
this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.MaximizeBox = false;
this.Name = "Socks5Form";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Socks5";
this.Load += new System.EventHandler(this.Socks5_Load);
this.ConfigurationGroupBox.ResumeLayout(false);
this.ConfigurationGroupBox.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox ConfigurationGroupBox;
private System.Windows.Forms.Button ControlButton;
private System.Windows.Forms.Label RemarkLabel;
private System.Windows.Forms.TextBox RemarkTextBox;
private System.Windows.Forms.Label PortLabel;
private System.Windows.Forms.TextBox AddressTextBox;
private System.Windows.Forms.TextBox PortTextBox;
private System.Windows.Forms.Label AddressLabel;
private System.Windows.Forms.TextBox PasswordTextBox;
private System.Windows.Forms.Label UsernameLabel;
private System.Windows.Forms.Label PasswordLabel;
private System.Windows.Forms.TextBox UsernameTextBox;
}
}

View File

@@ -1,47 +0,0 @@
using System;
using Netch.Utils;
namespace Netch.ServerEx.Socks5.Form
{
public partial class Socks5Form : System.Windows.Forms.Form
{
private readonly Socks5 _server;
public Socks5Form(Models.Server server = default)
{
InitializeComponent();
_server = (Socks5) (server ?? new Socks5());
}
private void Socks5_Load(object sender, EventArgs e)
{
i18N.TranslateForm(this);
RemarkTextBox.Text = _server.Remark;
AddressTextBox.Text = _server.Hostname;
PortTextBox.Text = _server.Port.ToString();
UsernameTextBox.Text = _server.Username;
PasswordTextBox.Text = _server.Password;
}
private void ControlButton_Click(object sender, EventArgs e)
{
if (!ushort.TryParse(PortTextBox.Text, out var port)) return;
_server.Remark = RemarkTextBox.Text;
_server.Type = "Socks5";
_server.Hostname = AddressTextBox.Text;
_server.Port = port;
_server.Username = UsernameTextBox.Text;
_server.Password = PasswordTextBox.Text;
_server.Country = null;
if (Global.Settings.Server.IndexOf(_server) == -1)
Global.Settings.Server.Add(_server);
MessageBoxX.Show(i18N.Translate("Saved"));
Close();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,175 +0,0 @@
namespace Netch.ServerEx.Trojan.Form
{
partial class TrojanForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TrojanForm));
this.ConfigurationGroupBox = new System.Windows.Forms.GroupBox();
this.PasswordTextBox = new System.Windows.Forms.TextBox();
this.PasswordLabel = new System.Windows.Forms.Label();
this.AddressLabel = new System.Windows.Forms.Label();
this.PortTextBox = new System.Windows.Forms.TextBox();
this.AddressTextBox = new System.Windows.Forms.TextBox();
this.RemarkTextBox = new System.Windows.Forms.TextBox();
this.RemarkLabel = new System.Windows.Forms.Label();
this.PortLabel = new System.Windows.Forms.Label();
this.ControlButton = new System.Windows.Forms.Button();
this.ConfigurationGroupBox.SuspendLayout();
this.SuspendLayout();
//
// ConfigurationGroupBox
//
this.ConfigurationGroupBox.Controls.Add(this.PasswordTextBox);
this.ConfigurationGroupBox.Controls.Add(this.PasswordLabel);
this.ConfigurationGroupBox.Controls.Add(this.AddressLabel);
this.ConfigurationGroupBox.Controls.Add(this.PortTextBox);
this.ConfigurationGroupBox.Controls.Add(this.AddressTextBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkTextBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkLabel);
this.ConfigurationGroupBox.Controls.Add(this.PortLabel);
this.ConfigurationGroupBox.Location = new System.Drawing.Point(12, 12);
this.ConfigurationGroupBox.Name = "ConfigurationGroupBox";
this.ConfigurationGroupBox.Size = new System.Drawing.Size(420, 109);
this.ConfigurationGroupBox.TabIndex = 0;
this.ConfigurationGroupBox.TabStop = false;
this.ConfigurationGroupBox.Text = "Configuration";
//
// PasswordTextBox
//
this.PasswordTextBox.Location = new System.Drawing.Point(120, 77);
this.PasswordTextBox.Name = "PasswordTextBox";
this.PasswordTextBox.Size = new System.Drawing.Size(294, 23);
this.PasswordTextBox.TabIndex = 7;
this.PasswordTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// PasswordLabel
//
this.PasswordLabel.AutoSize = true;
this.PasswordLabel.Location = new System.Drawing.Point(10, 80);
this.PasswordLabel.Name = "PasswordLabel";
this.PasswordLabel.Size = new System.Drawing.Size(64, 17);
this.PasswordLabel.TabIndex = 6;
this.PasswordLabel.Text = "Password";
//
// AddressLabel
//
this.AddressLabel.AutoSize = true;
this.AddressLabel.Location = new System.Drawing.Point(10, 51);
this.AddressLabel.Name = "AddressLabel";
this.AddressLabel.Size = new System.Drawing.Size(56, 17);
this.AddressLabel.TabIndex = 2;
this.AddressLabel.Text = "Address";
//
// PortTextBox
//
this.PortTextBox.Location = new System.Drawing.Point(358, 48);
this.PortTextBox.Name = "PortTextBox";
this.PortTextBox.Size = new System.Drawing.Size(56, 23);
this.PortTextBox.TabIndex = 5;
this.PortTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// AddressTextBox
//
this.AddressTextBox.Location = new System.Drawing.Point(120, 48);
this.AddressTextBox.Name = "AddressTextBox";
this.AddressTextBox.Size = new System.Drawing.Size(232, 23);
this.AddressTextBox.TabIndex = 3;
this.AddressTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// RemarkTextBox
//
this.RemarkTextBox.Location = new System.Drawing.Point(120, 19);
this.RemarkTextBox.Name = "RemarkTextBox";
this.RemarkTextBox.Size = new System.Drawing.Size(294, 23);
this.RemarkTextBox.TabIndex = 1;
this.RemarkTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// RemarkLabel
//
this.RemarkLabel.AutoSize = true;
this.RemarkLabel.Location = new System.Drawing.Point(10, 22);
this.RemarkLabel.Name = "RemarkLabel";
this.RemarkLabel.Size = new System.Drawing.Size(53, 17);
this.RemarkLabel.TabIndex = 0;
this.RemarkLabel.Text = "Remark";
//
// PortLabel
//
this.PortLabel.AutoSize = true;
this.PortLabel.Location = new System.Drawing.Point(351, 51);
this.PortLabel.Name = "PortLabel";
this.PortLabel.Size = new System.Drawing.Size(11, 17);
this.PortLabel.TabIndex = 4;
this.PortLabel.Text = ":";
//
// ControlButton
//
this.ControlButton.Location = new System.Drawing.Point(357, 127);
this.ControlButton.Name = "ControlButton";
this.ControlButton.Size = new System.Drawing.Size(75, 23);
this.ControlButton.TabIndex = 1;
this.ControlButton.Text = "Save";
this.ControlButton.UseVisualStyleBackColor = true;
this.ControlButton.Click += new System.EventHandler(this.ControlButton_Click);
//
// Trojan
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(444, 161);
this.Controls.Add(this.ControlButton);
this.Controls.Add(this.ConfigurationGroupBox);
this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.MaximizeBox = false;
this.Name = "TrojanForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Trojan";
this.Load += new System.EventHandler(this.TrojanForm_Load);
this.ConfigurationGroupBox.ResumeLayout(false);
this.ConfigurationGroupBox.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox ConfigurationGroupBox;
private System.Windows.Forms.Button ControlButton;
private System.Windows.Forms.Label RemarkLabel;
private System.Windows.Forms.TextBox RemarkTextBox;
private System.Windows.Forms.Label PortLabel;
private System.Windows.Forms.TextBox AddressTextBox;
private System.Windows.Forms.TextBox PortTextBox;
private System.Windows.Forms.Label AddressLabel;
private System.Windows.Forms.TextBox PasswordTextBox;
private System.Windows.Forms.Label PasswordLabel;
}
}

View File

@@ -1,52 +0,0 @@
using System;
using System.Windows.Forms;
using Netch.Models;
using Netch.Utils;
namespace Netch.ServerEx.Trojan.Form
{
public partial class TrojanForm : System.Windows.Forms.Form
{
private readonly Trojan _server;
public TrojanForm(Server server = default)
{
InitializeComponent();
_server = (Trojan) (server ?? new Trojan());
}
private void TrojanForm_Load(object sender, EventArgs e)
{
i18N.TranslateForm(this);
RemarkTextBox.Text = _server.Remark;
AddressTextBox.Text = _server.Hostname;
PortTextBox.Text = _server.Port.ToString();
PasswordTextBox.Text = _server.Password;
}
private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
Utils.Utils.DrawCenterComboBox(sender, e);
}
private void ControlButton_Click(object sender, EventArgs e)
{
if (!ushort.TryParse(PortTextBox.Text, out var port)) return;
_server.Remark = RemarkTextBox.Text;
_server.Type = "Trojan";
_server.Hostname = AddressTextBox.Text;
_server.Port = port;
_server.Password = PasswordTextBox.Text;
_server.Country = null;
if (Global.Settings.Server.IndexOf(_server) == -1)
Global.Settings.Server.Add(_server);
MessageBoxX.Show(i18N.Translate("Saved"));
Close();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,426 +0,0 @@
namespace Netch.ServerEx.VMess.Form
{
partial class VMessForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VMessForm));
this.ConfigurationGroupBox = new System.Windows.Forms.GroupBox();
this.UseMuxCheckBox = new System.Windows.Forms.CheckBox();
this.TLSSecureCheckBox = new System.Windows.Forms.CheckBox();
this.QUICSecretLabel = new System.Windows.Forms.Label();
this.QUICSecurityLabel = new System.Windows.Forms.Label();
this.QUICSecretTextBox = new System.Windows.Forms.TextBox();
this.QUICSecurityComboBox = new System.Windows.Forms.ComboBox();
this.PathLabel = new System.Windows.Forms.Label();
this.PathTextBox = new System.Windows.Forms.TextBox();
this.HostLabel = new System.Windows.Forms.Label();
this.HostTextBox = new System.Windows.Forms.TextBox();
this.FakeTypeLabel = new System.Windows.Forms.Label();
this.FakeTypeComboBox = new System.Windows.Forms.ComboBox();
this.TransferProtocolLabel = new System.Windows.Forms.Label();
this.TransferProtocolComboBox = new System.Windows.Forms.ComboBox();
this.EncryptMethodLabel = new System.Windows.Forms.Label();
this.EncryptMethodComboBox = new System.Windows.Forms.ComboBox();
this.AlterIDLabel = new System.Windows.Forms.Label();
this.AlterIDTextBox = new System.Windows.Forms.TextBox();
this.UserIDLabel = new System.Windows.Forms.Label();
this.UserIDTextBox = new System.Windows.Forms.TextBox();
this.PortTextBox = new System.Windows.Forms.TextBox();
this.AddressTextBox = new System.Windows.Forms.TextBox();
this.AddressLabel = new System.Windows.Forms.Label();
this.RemarkTextBox = new System.Windows.Forms.TextBox();
this.RemarkLabel = new System.Windows.Forms.Label();
this.PortLabel = new System.Windows.Forms.Label();
this.ControlButton = new System.Windows.Forms.Button();
this.ConfigurationGroupBox.SuspendLayout();
this.SuspendLayout();
//
// ConfigurationGroupBox
//
this.ConfigurationGroupBox.Controls.Add(this.UseMuxCheckBox);
this.ConfigurationGroupBox.Controls.Add(this.TLSSecureCheckBox);
this.ConfigurationGroupBox.Controls.Add(this.QUICSecretLabel);
this.ConfigurationGroupBox.Controls.Add(this.QUICSecurityLabel);
this.ConfigurationGroupBox.Controls.Add(this.QUICSecretTextBox);
this.ConfigurationGroupBox.Controls.Add(this.QUICSecurityComboBox);
this.ConfigurationGroupBox.Controls.Add(this.PathLabel);
this.ConfigurationGroupBox.Controls.Add(this.PathTextBox);
this.ConfigurationGroupBox.Controls.Add(this.HostLabel);
this.ConfigurationGroupBox.Controls.Add(this.HostTextBox);
this.ConfigurationGroupBox.Controls.Add(this.FakeTypeLabel);
this.ConfigurationGroupBox.Controls.Add(this.FakeTypeComboBox);
this.ConfigurationGroupBox.Controls.Add(this.TransferProtocolLabel);
this.ConfigurationGroupBox.Controls.Add(this.TransferProtocolComboBox);
this.ConfigurationGroupBox.Controls.Add(this.EncryptMethodLabel);
this.ConfigurationGroupBox.Controls.Add(this.EncryptMethodComboBox);
this.ConfigurationGroupBox.Controls.Add(this.AlterIDLabel);
this.ConfigurationGroupBox.Controls.Add(this.AlterIDTextBox);
this.ConfigurationGroupBox.Controls.Add(this.UserIDLabel);
this.ConfigurationGroupBox.Controls.Add(this.UserIDTextBox);
this.ConfigurationGroupBox.Controls.Add(this.PortTextBox);
this.ConfigurationGroupBox.Controls.Add(this.AddressTextBox);
this.ConfigurationGroupBox.Controls.Add(this.AddressLabel);
this.ConfigurationGroupBox.Controls.Add(this.RemarkTextBox);
this.ConfigurationGroupBox.Controls.Add(this.RemarkLabel);
this.ConfigurationGroupBox.Controls.Add(this.PortLabel);
this.ConfigurationGroupBox.Location = new System.Drawing.Point(18, 18);
this.ConfigurationGroupBox.Margin = new System.Windows.Forms.Padding(4);
this.ConfigurationGroupBox.Name = "ConfigurationGroupBox";
this.ConfigurationGroupBox.Padding = new System.Windows.Forms.Padding(4);
this.ConfigurationGroupBox.Size = new System.Drawing.Size(630, 560);
this.ConfigurationGroupBox.TabIndex = 1;
this.ConfigurationGroupBox.TabStop = false;
this.ConfigurationGroupBox.Text = "Configuration";
//
// UseMuxCheckBox
//
this.UseMuxCheckBox.AutoSize = true;
this.UseMuxCheckBox.Location = new System.Drawing.Point(292, 519);
this.UseMuxCheckBox.Margin = new System.Windows.Forms.Padding(4);
this.UseMuxCheckBox.Name = "UseMuxCheckBox";
this.UseMuxCheckBox.Size = new System.Drawing.Size(110, 28);
this.UseMuxCheckBox.TabIndex = 25;
this.UseMuxCheckBox.Text = "Use Mux";
this.UseMuxCheckBox.UseVisualStyleBackColor = true;
//
// TLSSecureCheckBox
//
this.TLSSecureCheckBox.AutoSize = true;
this.TLSSecureCheckBox.Location = new System.Drawing.Point(453, 519);
this.TLSSecureCheckBox.Margin = new System.Windows.Forms.Padding(4);
this.TLSSecureCheckBox.Name = "TLSSecureCheckBox";
this.TLSSecureCheckBox.Size = new System.Drawing.Size(127, 28);
this.TLSSecureCheckBox.TabIndex = 24;
this.TLSSecureCheckBox.Text = "TLS Secure";
this.TLSSecureCheckBox.UseVisualStyleBackColor = true;
//
// QUICSecretLabel
//
this.QUICSecretLabel.AutoSize = true;
this.QUICSecretLabel.Location = new System.Drawing.Point(15, 480);
this.QUICSecretLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.QUICSecretLabel.Name = "QUICSecretLabel";
this.QUICSecretLabel.Size = new System.Drawing.Size(113, 24);
this.QUICSecretLabel.TabIndex = 22;
this.QUICSecretLabel.Text = "QUIC Secret";
//
// QUICSecurityLabel
//
this.QUICSecurityLabel.AutoSize = true;
this.QUICSecurityLabel.Location = new System.Drawing.Point(15, 435);
this.QUICSecurityLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.QUICSecurityLabel.Name = "QUICSecurityLabel";
this.QUICSecurityLabel.Size = new System.Drawing.Size(129, 24);
this.QUICSecurityLabel.TabIndex = 20;
this.QUICSecurityLabel.Text = "QUIC Security";
//
// QUICSecretTextBox
//
this.QUICSecretTextBox.Location = new System.Drawing.Point(180, 476);
this.QUICSecretTextBox.Margin = new System.Windows.Forms.Padding(4);
this.QUICSecretTextBox.Name = "QUICSecretTextBox";
this.QUICSecretTextBox.Size = new System.Drawing.Size(439, 31);
this.QUICSecretTextBox.TabIndex = 23;
this.QUICSecretTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// QUICSecurityComboBox
//
this.QUICSecurityComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.QUICSecurityComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.QUICSecurityComboBox.FormattingEnabled = true;
this.QUICSecurityComboBox.Location = new System.Drawing.Point(180, 429);
this.QUICSecurityComboBox.Margin = new System.Windows.Forms.Padding(4);
this.QUICSecurityComboBox.Name = "QUICSecurityComboBox";
this.QUICSecurityComboBox.Size = new System.Drawing.Size(439, 32);
this.QUICSecurityComboBox.TabIndex = 21;
this.QUICSecurityComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ComboBox_DrawItem);
//
// PathLabel
//
this.PathLabel.AutoSize = true;
this.PathLabel.Location = new System.Drawing.Point(15, 390);
this.PathLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.PathLabel.Name = "PathLabel";
this.PathLabel.Size = new System.Drawing.Size(49, 24);
this.PathLabel.TabIndex = 18;
this.PathLabel.Text = "Path";
//
// PathTextBox
//
this.PathTextBox.Location = new System.Drawing.Point(180, 386);
this.PathTextBox.Margin = new System.Windows.Forms.Padding(4);
this.PathTextBox.Name = "PathTextBox";
this.PathTextBox.Size = new System.Drawing.Size(439, 31);
this.PathTextBox.TabIndex = 19;
this.PathTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// HostLabel
//
this.HostLabel.AutoSize = true;
this.HostLabel.Location = new System.Drawing.Point(15, 346);
this.HostLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.HostLabel.Name = "HostLabel";
this.HostLabel.Size = new System.Drawing.Size(50, 24);
this.HostLabel.TabIndex = 16;
this.HostLabel.Text = "Host";
//
// HostTextBox
//
this.HostTextBox.Location = new System.Drawing.Point(180, 342);
this.HostTextBox.Margin = new System.Windows.Forms.Padding(4);
this.HostTextBox.Name = "HostTextBox";
this.HostTextBox.Size = new System.Drawing.Size(439, 31);
this.HostTextBox.TabIndex = 17;
this.HostTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// FakeTypeLabel
//
this.FakeTypeLabel.AutoSize = true;
this.FakeTypeLabel.Location = new System.Drawing.Point(15, 302);
this.FakeTypeLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.FakeTypeLabel.Name = "FakeTypeLabel";
this.FakeTypeLabel.Size = new System.Drawing.Size(97, 24);
this.FakeTypeLabel.TabIndex = 14;
this.FakeTypeLabel.Text = "Fake Type";
//
// FakeTypeComboBox
//
this.FakeTypeComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.FakeTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.FakeTypeComboBox.FormattingEnabled = true;
this.FakeTypeComboBox.Location = new System.Drawing.Point(180, 296);
this.FakeTypeComboBox.Margin = new System.Windows.Forms.Padding(4);
this.FakeTypeComboBox.Name = "FakeTypeComboBox";
this.FakeTypeComboBox.Size = new System.Drawing.Size(439, 32);
this.FakeTypeComboBox.TabIndex = 15;
this.FakeTypeComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ComboBox_DrawItem);
//
// TransferProtocolLabel
//
this.TransferProtocolLabel.AutoSize = true;
this.TransferProtocolLabel.Location = new System.Drawing.Point(15, 255);
this.TransferProtocolLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.TransferProtocolLabel.Name = "TransferProtocolLabel";
this.TransferProtocolLabel.Size = new System.Drawing.Size(156, 24);
this.TransferProtocolLabel.TabIndex = 12;
this.TransferProtocolLabel.Text = "Transfer Protocol";
//
// TransferProtocolComboBox
//
this.TransferProtocolComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.TransferProtocolComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.TransferProtocolComboBox.FormattingEnabled = true;
this.TransferProtocolComboBox.Location = new System.Drawing.Point(180, 249);
this.TransferProtocolComboBox.Margin = new System.Windows.Forms.Padding(4);
this.TransferProtocolComboBox.Name = "TransferProtocolComboBox";
this.TransferProtocolComboBox.Size = new System.Drawing.Size(439, 32);
this.TransferProtocolComboBox.TabIndex = 13;
this.TransferProtocolComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ComboBox_DrawItem);
//
// EncryptMethodLabel
//
this.EncryptMethodLabel.AutoSize = true;
this.EncryptMethodLabel.Location = new System.Drawing.Point(15, 208);
this.EncryptMethodLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.EncryptMethodLabel.Name = "EncryptMethodLabel";
this.EncryptMethodLabel.Size = new System.Drawing.Size(150, 24);
this.EncryptMethodLabel.TabIndex = 10;
this.EncryptMethodLabel.Text = "Encrypt Method";
//
// EncryptMethodComboBox
//
this.EncryptMethodComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.EncryptMethodComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.EncryptMethodComboBox.FormattingEnabled = true;
this.EncryptMethodComboBox.Location = new System.Drawing.Point(180, 202);
this.EncryptMethodComboBox.Margin = new System.Windows.Forms.Padding(4);
this.EncryptMethodComboBox.Name = "EncryptMethodComboBox";
this.EncryptMethodComboBox.Size = new System.Drawing.Size(439, 32);
this.EncryptMethodComboBox.TabIndex = 11;
this.EncryptMethodComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ComboBox_DrawItem);
//
// AlterIDLabel
//
this.AlterIDLabel.AutoSize = true;
this.AlterIDLabel.Location = new System.Drawing.Point(15, 164);
this.AlterIDLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.AlterIDLabel.Name = "AlterIDLabel";
this.AlterIDLabel.Size = new System.Drawing.Size(76, 24);
this.AlterIDLabel.TabIndex = 8;
this.AlterIDLabel.Text = "Alter ID";
//
// AlterIDTextBox
//
this.AlterIDTextBox.Location = new System.Drawing.Point(180, 159);
this.AlterIDTextBox.Margin = new System.Windows.Forms.Padding(4);
this.AlterIDTextBox.Name = "AlterIDTextBox";
this.AlterIDTextBox.Size = new System.Drawing.Size(79, 31);
this.AlterIDTextBox.TabIndex = 9;
this.AlterIDTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// UserIDLabel
//
this.UserIDLabel.AutoSize = true;
this.UserIDLabel.Location = new System.Drawing.Point(15, 120);
this.UserIDLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.UserIDLabel.Name = "UserIDLabel";
this.UserIDLabel.Size = new System.Drawing.Size(72, 24);
this.UserIDLabel.TabIndex = 6;
this.UserIDLabel.Text = "User ID";
//
// UserIDTextBox
//
this.UserIDTextBox.Location = new System.Drawing.Point(180, 116);
this.UserIDTextBox.Margin = new System.Windows.Forms.Padding(4);
this.UserIDTextBox.Name = "UserIDTextBox";
this.UserIDTextBox.Size = new System.Drawing.Size(439, 31);
this.UserIDTextBox.TabIndex = 7;
this.UserIDTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// PortTextBox
//
this.PortTextBox.Location = new System.Drawing.Point(540, 72);
this.PortTextBox.Margin = new System.Windows.Forms.Padding(4);
this.PortTextBox.Name = "PortTextBox";
this.PortTextBox.Size = new System.Drawing.Size(79, 31);
this.PortTextBox.TabIndex = 5;
this.PortTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// AddressTextBox
//
this.AddressTextBox.Location = new System.Drawing.Point(180, 72);
this.AddressTextBox.Margin = new System.Windows.Forms.Padding(4);
this.AddressTextBox.Name = "AddressTextBox";
this.AddressTextBox.Size = new System.Drawing.Size(349, 31);
this.AddressTextBox.TabIndex = 3;
this.AddressTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// AddressLabel
//
this.AddressLabel.AutoSize = true;
this.AddressLabel.Location = new System.Drawing.Point(15, 76);
this.AddressLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.AddressLabel.Name = "AddressLabel";
this.AddressLabel.Size = new System.Drawing.Size(80, 24);
this.AddressLabel.TabIndex = 2;
this.AddressLabel.Text = "Address";
//
// RemarkTextBox
//
this.RemarkTextBox.Location = new System.Drawing.Point(180, 28);
this.RemarkTextBox.Margin = new System.Windows.Forms.Padding(4);
this.RemarkTextBox.Name = "RemarkTextBox";
this.RemarkTextBox.Size = new System.Drawing.Size(439, 31);
this.RemarkTextBox.TabIndex = 1;
this.RemarkTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// RemarkLabel
//
this.RemarkLabel.AutoSize = true;
this.RemarkLabel.Location = new System.Drawing.Point(15, 33);
this.RemarkLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.RemarkLabel.Name = "RemarkLabel";
this.RemarkLabel.Size = new System.Drawing.Size(76, 24);
this.RemarkLabel.TabIndex = 0;
this.RemarkLabel.Text = "Remark";
//
// PortLabel
//
this.PortLabel.AutoSize = true;
this.PortLabel.Location = new System.Drawing.Point(530, 76);
this.PortLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.PortLabel.Name = "PortLabel";
this.PortLabel.Size = new System.Drawing.Size(14, 24);
this.PortLabel.TabIndex = 4;
this.PortLabel.Text = ":";
//
// ControlButton
//
this.ControlButton.Location = new System.Drawing.Point(536, 586);
this.ControlButton.Margin = new System.Windows.Forms.Padding(4);
this.ControlButton.Name = "ControlButton";
this.ControlButton.Size = new System.Drawing.Size(112, 34);
this.ControlButton.TabIndex = 2;
this.ControlButton.Text = "Save";
this.ControlButton.UseVisualStyleBackColor = true;
this.ControlButton.Click += new System.EventHandler(this.ControlButton_Click);
//
// VMess
//
this.AutoScaleDimensions = new System.Drawing.SizeF(144F, 144F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(666, 639);
this.Controls.Add(this.ControlButton);
this.Controls.Add(this.ConfigurationGroupBox);
this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6);
this.MaximizeBox = false;
this.Name = "VMessForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "VMess";
this.Load += new System.EventHandler(this.VMess_Load);
this.ConfigurationGroupBox.ResumeLayout(false);
this.ConfigurationGroupBox.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox ConfigurationGroupBox;
private System.Windows.Forms.TextBox PortTextBox;
private System.Windows.Forms.TextBox AddressTextBox;
private System.Windows.Forms.Label AddressLabel;
private System.Windows.Forms.TextBox RemarkTextBox;
private System.Windows.Forms.Label RemarkLabel;
private System.Windows.Forms.Label PortLabel;
private System.Windows.Forms.Label UserIDLabel;
private System.Windows.Forms.TextBox UserIDTextBox;
private System.Windows.Forms.Label AlterIDLabel;
private System.Windows.Forms.TextBox AlterIDTextBox;
private System.Windows.Forms.Label EncryptMethodLabel;
private System.Windows.Forms.ComboBox EncryptMethodComboBox;
private System.Windows.Forms.Label TransferProtocolLabel;
private System.Windows.Forms.ComboBox TransferProtocolComboBox;
private System.Windows.Forms.Label FakeTypeLabel;
private System.Windows.Forms.ComboBox FakeTypeComboBox;
private System.Windows.Forms.Label HostLabel;
private System.Windows.Forms.TextBox HostTextBox;
private System.Windows.Forms.Label PathLabel;
private System.Windows.Forms.TextBox PathTextBox;
private System.Windows.Forms.Label QUICSecurityLabel;
private System.Windows.Forms.TextBox QUICSecretTextBox;
private System.Windows.Forms.ComboBox QUICSecurityComboBox;
private System.Windows.Forms.Label QUICSecretLabel;
private System.Windows.Forms.CheckBox TLSSecureCheckBox;
private System.Windows.Forms.Button ControlButton;
private System.Windows.Forms.CheckBox UseMuxCheckBox;
}
}

View File

@@ -1,80 +0,0 @@
using System;
using System.Windows.Forms;
using Netch.Models;
using Netch.Utils;
namespace Netch.ServerEx.VMess.Form
{
public partial class VMessForm : System.Windows.Forms.Form
{
private static VMess _server;
public VMessForm(Server server = default)
{
InitializeComponent();
_server = (VMess) server ?? new VMess();
}
private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
Utils.Utils.DrawCenterComboBox(sender, e);
}
private void VMess_Load(object sender, EventArgs e)
{
i18N.TranslateForm(this);
EncryptMethodComboBox.Items.AddRange(VMessGlobal.EncryptMethods.ToArray());
TransferProtocolComboBox.Items.AddRange(VMessGlobal.TransferProtocols.ToArray());
FakeTypeComboBox.Items.AddRange(VMessGlobal.FakeTypes.ToArray());
QUICSecurityComboBox.Items.AddRange(VMessGlobal.QUIC.ToArray());
RemarkTextBox.Text = _server.Remark;
AddressTextBox.Text = _server.Hostname;
PortTextBox.Text = _server.Port.ToString();
UserIDTextBox.Text = _server.UserID;
AlterIDTextBox.Text = _server.AlterID.ToString();
EncryptMethodComboBox.SelectedIndex = VMessGlobal.EncryptMethods.IndexOf(_server.EncryptMethod);
TransferProtocolComboBox.SelectedIndex = VMessGlobal.TransferProtocols.IndexOf(_server.TransferProtocol);
FakeTypeComboBox.SelectedIndex = VMessGlobal.FakeTypes.IndexOf(_server.FakeType);
HostTextBox.Text = _server.Host;
PathTextBox.Text = _server.Path;
QUICSecurityComboBox.SelectedIndex = VMessGlobal.QUIC.IndexOf(_server.QUICSecure);
QUICSecretTextBox.Text = _server.QUICSecret;
TLSSecureCheckBox.Checked = _server.TLSSecure;
UseMuxCheckBox.Checked = _server.UseMux;
}
private void ControlButton_Click(object sender, EventArgs e)
{
if (!ushort.TryParse(PortTextBox.Text, out var port)) return;
if (!int.TryParse(AlterIDTextBox.Text, out var alterId)) return;
_server.Remark = RemarkTextBox.Text;
_server.Type = "VMess";
_server.Hostname = AddressTextBox.Text;
_server.Port = port;
_server.UserID = UserIDTextBox.Text;
_server.AlterID = alterId;
_server.EncryptMethod = EncryptMethodComboBox.Text;
_server.TransferProtocol = TransferProtocolComboBox.Text;
_server.FakeType = FakeTypeComboBox.Text;
_server.Host = HostTextBox.Text;
_server.Path = PathTextBox.Text;
_server.QUICSecure = QUICSecurityComboBox.Text;
_server.QUICSecret = QUICSecretTextBox.Text;
_server.TLSSecure = TLSSecureCheckBox.Checked;
_server.UseMux = UseMuxCheckBox.Checked;
_server.Country = null;
if (Global.Settings.Server.IndexOf(_server) == -1)
Global.Settings.Server.Add(_server);
MessageBoxX.Show(i18N.Translate("Saved"));
Close();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,206 +0,0 @@
using System.Collections.Generic;
namespace Netch.ServerEx.VMess.Models
{
public class VMessConfig
{
public class InboundSettings
{
public bool udp = true;
}
public class Inbounds
{
public string listen = "127.0.0.1";
public int port = 2801;
public string protocol = "socks";
public InboundSettings settings;
}
public class User
{
public string id;
public int alterId;
public string security;
}
public class VNext
{
public string address;
public int port;
public List<User> users;
}
public class WSHeaders
{
public string Host;
}
public class TCPRequestHeaders
{
public string Host;
//public string User_Agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36";
public string Accept_Encoding = "gzip, deflate";
public string Connection = "keep-alive";
public string Pragma = "no-cache";
}
public class TCPRequest
{
public string version = "1.1";
public string method = "GET";
public string path = "/";
public TCPRequestHeaders headers;
}
public class TCPHeaders
{
public string type;
public TCPRequest request;
}
public class WebSocketSettings
{
public bool connectionReuse = true;
public string path = "/";
public WSHeaders headers;
}
public class TCPSettings
{
public bool connectionReuse = true;
public TCPHeaders header;
}
public class QUICSettings
{
public string security;
public string key;
public TCPHeaders header;
}
public class KCPSettings
{
public int mtu = 1350;
public int tti = 50;
public int uplinkCapacity = 12;
public int downlinkCapacity = 100;
public bool congestion = false;
public int readBufferSize = 2;
public int writeBufferSize = 2;
public TCPHeaders header;
}
public class HTTPSettings
{
public string host;
public string path;
}
public class TLSSettings
{
public bool allowInsecure = true;
public string serverName;
}
public class OutboundSettings
{
public List<VNext> vnext;
}
public class OutboundMux
{
public bool enabled = false;
}
public class StreamSettings
{
public string network;
public string security;
public TCPSettings tcpSettings;
public WebSocketSettings wsSettings;
public KCPSettings kcpSettings;
public QUICSettings quicSettings;
public HTTPSettings httpSettings;
public TLSSettings tlsSettings;
}
public class Outbounds
{
public string tag = "proxy";
public string protocol = "vmess";
public OutboundSettings settings;
public StreamSettings streamSettings;
public OutboundMux mux;
}
public class RoutingRules
{
public string type = "field";
public List<string> port;
public string outboundTag;
public List<string> ip;
public List<string> domain;
}
public class Routing
{
public string domainStrategy = "IPIfNonMatch";
public List<RoutingRules> rules;
}
public class Config
{
public List<Inbounds> inbounds;
public List<Outbounds> outbounds;
public Routing routing;
}
}
}

View File

@@ -1,184 +0,0 @@
using System.Collections.Generic;
using System.IO;
using Netch.Models;
using Netch.ServerEx.VMess.Models;
using Newtonsoft.Json;
namespace Netch.ServerEx.VMess
{
public class VMessController : ServerController
{
public VMessController()
{
Name = "V2Ray";
MainFile = "v2ray.exe";
StartedKeywords.Add("started");
StoppedKeywords.AddRange(new[] {"config file not readable", "failed to"});
}
public override bool Start(Server s, Mode mode)
{
var server = (VMess) s;
File.WriteAllText("data\\last.json", JsonConvert.SerializeObject(new VMessConfig.Config()
{
inbounds = new List<VMessConfig.Inbounds>
{
new VMessConfig.Inbounds
{
settings = new VMessConfig.InboundSettings(),
port = Socks5LocalPort,
listen = LocalAddress
}
},
outbounds = new List<VMessConfig.Outbounds>
{
new VMessConfig.Outbounds
{
settings = new VMessConfig.OutboundSettings
{
vnext = new List<VMessConfig.VNext>
{
new VMessConfig.VNext
{
address = server.Hostname,
port = server.Port,
users = new List<VMessConfig.User>
{
new VMessConfig.User
{
id = server.UserID,
alterId = server.AlterID,
security = server.EncryptMethod
}
}
}
}
},
streamSettings = new VMessConfig.StreamSettings
{
network = server.TransferProtocol,
security = server.TLSSecure ? "tls" : string.Empty,
wsSettings = server.TransferProtocol == "ws"
? new VMessConfig.WebSocketSettings
{
path = server.Path == string.Empty ? "/" : server.Path,
headers = new VMessConfig.WSHeaders
{
Host = server.Host == string.Empty ? server.Hostname : server.Host
}
}
: null,
tcpSettings = server.FakeType == "http"
? new VMessConfig.TCPSettings
{
header = new VMessConfig.TCPHeaders
{
type = server.FakeType,
request = new VMessConfig.TCPRequest
{
path = server.Path == string.Empty ? "/" : server.Path,
headers = new VMessConfig.TCPRequestHeaders
{
Host = server.Host == string.Empty ? server.Hostname : server.Host
}
}
}
}
: null,
kcpSettings = server.TransferProtocol == "kcp"
? new VMessConfig.KCPSettings
{
header = new VMessConfig.TCPHeaders
{
type = server.FakeType
}
}
: null,
quicSettings = server.TransferProtocol == "quic"
? new VMessConfig.QUICSettings
{
security = server.QUICSecure,
key = server.QUICSecret,
header = new VMessConfig.TCPHeaders
{
type = server.FakeType
}
}
: null,
httpSettings = server.TransferProtocol == "h2"
? new VMessConfig.HTTPSettings
{
host = server.Host == "" ? server.Hostname : server.Host,
path = server.Path == "" ? "/" : server.Path
}
: null,
tlsSettings = new VMessConfig.TLSSettings
{
allowInsecure = true,
serverName = server.Host == "" ? server.Hostname : server.Host
}
},
mux = new VMessConfig.OutboundMux
{
enabled = server.UseMux
}
},
mode.Type == 0 || mode.Type == 1 || mode.Type == 2
? new VMessConfig.Outbounds
{
tag = "TUNTAP",
protocol = "freedom"
}
: new VMessConfig.Outbounds
{
tag = "direct",
protocol = "freedom"
}
},
routing = new VMessConfig.Routing
{
rules = new List<VMessConfig.RoutingRules>
{
mode.BypassChina
? new VMessConfig.RoutingRules
{
type = "field",
ip = new List<string>
{
"geoip:cn",
"geoip:private"
},
domain = new List<string>
{
"geosite:cn"
},
outboundTag = "direct"
}
: new VMessConfig.RoutingRules
{
type = "field",
ip = new List<string>
{
"geoip:private"
},
outboundTag = "direct"
}
}
}
}));
if (StartInstanceAuto("-config ..\\data\\last.json"))
{
if (File.Exists("data\\last.json")) File.Delete("data\\last.json");
return true;
}
return false;
}
public override void Stop()
{
StopInstance();
}
}
}

View File

@@ -0,0 +1,31 @@
using Netch.Forms;
namespace Netch.Servers.Shadowsocks.Form
{
public class ShadowsocksForm : ServerForm
{
protected override string TypeName { get; } = "Shadowsocks";
public ShadowsocksForm(Shadowsocks server = default)
{
server ??= new Shadowsocks();
Server = server;
CreateTextBox("Password", "Password",
s => true,
s => server.Password = s,
server.Password);
CreateComboBox("EncryptMethod", "Encrypt Method",
SSGlobal.EncryptMethods,
s => server.EncryptMethod = s,
server.EncryptMethod);
CreateTextBox("Plugin", "Plugin",
s => true,
s => server.Plugin = s,
server.Plugin);
CreateTextBox("PluginsOption", "Plugin Options",
s => true,
s => server.PluginOption = s,
server.PluginOption);
}
}
}

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
namespace Netch.ServerEx.Shadowsocks.Models.SSD
namespace Netch.Servers.Shadowsocks.Models.SSD
{
public class Main
{
@@ -12,7 +12,7 @@ namespace Netch.ServerEx.Shadowsocks.Models.SSD
/// <summary>
/// 端口
/// </summary>
public int port;
public ushort port;
/// <summary>
/// 加密方式

View File

@@ -1,4 +1,4 @@
namespace Netch.ServerEx.Shadowsocks.Models.SSD
namespace Netch.Servers.Shadowsocks.Models.SSD
{
public class SSDServer
{
@@ -10,7 +10,7 @@
/// <summary>
/// 端口
/// </summary>
public int port;
public ushort port;
/// <summary>
/// 加密方式

View File

@@ -1,9 +1,9 @@
namespace Netch.ServerEx.Shadowsocks.Models
namespace Netch.Servers.Shadowsocks.Models
{
public class ShadowsocksConfig
{
public string server { get; set; }
public int server_port { get; set; }
public ushort server_port { get; set; }
public string password { get; set; }
public string method { get; set; }
public string remarks { get; set; }

View File

@@ -1,32 +1,34 @@
using System.Runtime.InteropServices;
using System.Text;
using Netch.Controllers;
using Netch.Models;
using Netch.Utils;
namespace Netch.ServerEx.Shadowsocks
namespace Netch.Servers.Shadowsocks
{
public class SSController : ServerController
public class SSController : Guard, IServerController
{
public SSController()
{
Name = "Shadowsocks";
MainFile = "Shadowsocks.exe";
}
public override string Name { get; protected set; } = "Shadowsocks";
public override string MainFile { get; protected set; } = "Shadowsocks.exe";
public override bool Start(Server s, Mode mode)
{
bool DllFlag()
{
return Global.Settings.BootShadowsocksFromDLL && (mode.Type == 0 || mode.Type == 1 || mode.Type == 2);
}
public Server Server { get; set; }
public ushort? Socks5LocalPort { get; set; }
public string LocalAddress { get; set; }
private Mode _savedMode;
public bool DllFlag => Global.Settings.BootShadowsocksFromDLL && (_savedMode.Type == 0 || _savedMode.Type == 1 || _savedMode.Type == 2);
public bool Start(in Server s, in Mode mode)
{
_savedMode = mode;
Server = s;
var server = (Shadowsocks) s;
//从DLL启动Shaowsocks
if (DllFlag())
if (DllFlag)
{
State = State.Starting;
var client = Encoding.UTF8.GetBytes($"{LocalAddress}:{Socks5LocalPort}");
var remote = Encoding.UTF8.GetBytes($"{server.Hostname}:{server.Port}");
var client = Encoding.UTF8.GetBytes($"{this.LocalAddress()}:{this.Socks5LocalPort()}");
var remote = Encoding.UTF8.GetBytes($"{server.AutoResolveHostname()}:{server.Port}");
var passwd = Encoding.UTF8.GetBytes($"{server.Password}");
var method = Encoding.UTF8.GetBytes($"{server.EncryptMethod}");
if (!ShadowsocksDLL.Info(client, remote, passwd, method))
@@ -54,10 +56,10 @@ namespace Netch.ServerEx.Shadowsocks
var argument = new StringBuilder();
argument.Append(
$"-s {server.Hostname} " +
$"-s {server.AutoResolveHostname()} " +
$"-p {server.Port} " +
$"-b {LocalAddress} " +
$"-l {Socks5LocalPort} " +
$"-b {this.LocalAddress()} " +
$"-l {this.Socks5LocalPort()} " +
$"-m {server.EncryptMethod} " +
$"-k \"{server.Password}\" " +
"-u ");
@@ -78,6 +80,7 @@ namespace Netch.ServerEx.Shadowsocks
ShadowsocksDLL.Stop();
else
StopInstance();
_savedMode = null;
}

View File

@@ -3,24 +3,25 @@ using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Netch.Controllers;
using Netch.Models;
using Netch.ServerEx.Shadowsocks.Form;
using Netch.ServerEx.Shadowsocks.Models.SSD;
using Netch.Servers.Shadowsocks.Form;
using Netch.Servers.Shadowsocks.Models.SSD;
using Netch.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Netch.ServerEx.Shadowsocks
namespace Netch.Servers.Shadowsocks
{
public class SSUtil : IServerUtil
{
public ushort Priority { get; } = 1;
public string TypeName { get; } = "SS";
public string FullName { get; } = "Shadowsocks";
public string ShortName { get; } = "SS";
public string[] UriScheme { get; } = {"ss", "ssd"};
public string[] UriScheme { get; } = {"ss","ssd"};
public Server ParseJObject(JObject j)
public Server ParseJObject(in JObject j)
{
return j.ToObject<Shadowsocks>();
}
@@ -42,7 +43,7 @@ namespace Netch.ServerEx.Shadowsocks
return "ss://" + ShareLink.URLSafeBase64Encode($"{server.EncryptMethod}:{server.Password}@{server.Hostname}:{server.Port}") + "#" + HttpUtility.UrlEncode(server.Remark);
}
public ServerController GetController()
public IServerController GetController()
{
return new SSController();
}
@@ -139,7 +140,7 @@ namespace Netch.ServerEx.Shadowsocks
if (!match.Success) throw new FormatException();
data.Hostname = match.Groups["server"].Value;
data.Port = int.Parse(match.Groups["port"].Value);
data.Port = ushort.Parse(match.Groups["port"].Value);
var base64 = ShareLink.URLSafeBase64Decode(match.Groups["base64"].Value);
match = parser.Match(base64);
@@ -155,7 +156,7 @@ namespace Netch.ServerEx.Shadowsocks
if (!match.Success) throw new FormatException();
data.Hostname = match.Groups["server"].Value;
data.Port = int.Parse(match.Groups["port"].Value);
data.Port = ushort.Parse(match.Groups["port"].Value);
data.EncryptMethod = match.Groups["method"].Value;
data.Password = match.Groups["password"].Value;
}

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using Netch.Models;
namespace Netch.ServerEx.Shadowsocks
namespace Netch.Servers.Shadowsocks
{
public class Shadowsocks : Server
{

View File

@@ -0,0 +1,39 @@
using Netch.Forms;
namespace Netch.Servers.ShadowsocksR.Form
{
public class ShadowsocksRForm : ServerForm
{
protected override string TypeName { get; } = "ShadowsocksR";
public ShadowsocksRForm(ShadowsocksR server = default)
{
server ??= new ShadowsocksR();
Server = server;
CreateTextBox("Password", "Password",
s => true,
s => server.Password = s,
server.Password);
CreateComboBox("EncryptMethod", "Encrypt Method",
SSRGlobal.EncryptMethods,
s => server.EncryptMethod = s,
server.EncryptMethod);
CreateComboBox("Protocol", "Protocol",
SSRGlobal.Protocols,
s => server.Protocol = s,
server.Protocol);
CreateTextBox("ProtocolParam", "Protocol Param",
s => true,
s => server.ProtocolParam = s,
server.ProtocolParam);
CreateComboBox("OBFS", "OBFS",
SSRGlobal.OBFSs,
s => server.OBFS = s,
server.OBFS);
CreateTextBox("OBFSParam", "OBFS Param",
s => true,
s => server.OBFSParam = s,
server.OBFSParam);
}
}
}

View File

@@ -1,25 +1,29 @@
using System.Text;
using Netch.Controllers;
using Netch.Models;
using Netch.Utils;
namespace Netch.ServerEx.ShadowsocksR
namespace Netch.Servers.ShadowsocksR
{
public class SSRController : ServerController
public class SSRController : Guard, IServerController
{
public SSRController()
{
Name = "ShadowsocksR";
MainFile = "ShadowsocksR.exe";
}
public override string MainFile { get; protected set; } = "ShadowsocksR.exe";
public override string Name { get; protected set; } = "ShadowsocksR";
public override bool Start(Server s, Mode mode)
public Server Server { get; set; }
public ushort? Socks5LocalPort { get; set; }
public string LocalAddress { get; set; }
public bool Start(in Server s, in Mode mode)
{
Server = s;
var server = (ShadowsocksR) s;
#region Argument
var argument = new StringBuilder();
argument.Append($"-s {server.Hostname} -p {server.Port} -k \"{server.Password}\" -m {server.EncryptMethod} -t 120");
argument.Append($"-s {server.AutoResolveHostname()} -p {server.Port} -k \"{server.Password}\" -m {server.EncryptMethod} -t 120");
if (!string.IsNullOrEmpty(server.Protocol))
{
argument.Append($" -O {server.Protocol}");
@@ -32,7 +36,7 @@ namespace Netch.ServerEx.ShadowsocksR
if (!string.IsNullOrEmpty(server.OBFSParam)) argument.Append($" -g \"{server.OBFSParam}\"");
}
argument.Append($" -b {LocalAddress} -l {Socks5LocalPort} -u");
argument.Append($" -b {this.LocalAddress()} -l {this.Socks5LocalPort()} -u");
if (mode.BypassChina) argument.Append(" --acl default.acl");
#endregion

View File

@@ -1,22 +1,23 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Netch.Controllers;
using Netch.Models;
using Netch.ServerEx.ShadowsocksR.Form;
using Netch.Servers.ShadowsocksR.Form;
using Netch.Utils;
using Newtonsoft.Json.Linq;
namespace Netch.ServerEx.ShadowsocksR
namespace Netch.Servers.ShadowsocksR
{
public class SSRUtil : IServerUtil
{
public ushort Priority { get; } = 1;
public string TypeName { get; } = "SSR";
public string FullName { get; } = "ShadowsocksR";
public string ShortName { get; } = "SR";
public string[] UriScheme { get; } = {"ssr"};
public Server ParseJObject(JObject j)
public Server ParseJObject(in JObject j)
{
return j.ToObject<ShadowsocksR>();
}
@@ -24,7 +25,7 @@ namespace Netch.ServerEx.ShadowsocksR
public void Edit(Server s)
{
new ShadowsocksRForm(s).ShowDialog();
new ShadowsocksRForm((ShadowsocksR) s).ShowDialog();
}
public void Create()
@@ -42,7 +43,7 @@ namespace Netch.ServerEx.ShadowsocksR
return "ssr://" + ShareLink.URLSafeBase64Encode($"{server.Hostname}:{server.Port}:{server.Protocol}:{server.EncryptMethod}:{server.OBFS}:{ShareLink.URLSafeBase64Encode(server.Password)}{paraStr}");
}
public ServerController GetController()
public IServerController GetController()
{
return new SSRController();
}

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using Netch.Models;
namespace Netch.ServerEx.ShadowsocksR
namespace Netch.Servers.ShadowsocksR
{
public class ShadowsocksR : Server
{

View File

@@ -0,0 +1,23 @@
using Netch.Forms;
namespace Netch.Servers.Socks5.Form
{
public class Socks5Form : ServerForm
{
protected override string TypeName { get; } = "Socks5";
public Socks5Form(Socks5 server = default)
{
server ??= new Socks5();
Server = server;
CreateTextBox("Username", "Username",
s => true,
s => server.Username = s,
server.Username);
CreateTextBox("Password", "Password",
s => true,
s => server.Password = s,
server.Password);
}
}
}

View File

@@ -0,0 +1,42 @@
using System.IO;
using Netch.Controllers;
using Netch.Models;
using Netch.Servers.VMess.Utils;
namespace Netch.Servers.Socks5
{
public class S5Controller : Guard, IServerController
{
public override string Name { get; protected set; } = "Socks5";
public override string MainFile { get; protected set; } = "v2ray.exe";
public bool Start(in Server s, in Mode mode)
{
Server = s;
var server = (Socks5) s;
if (server.Auth() && !mode.SupportSocks5Auth)
{
File.WriteAllText("data\\last.json", V2rayConfigUtils.GenerateClientConfig(s, mode));
if (StartInstanceAuto("-config ..\\data\\last.json"))
{
return true;
}
return false;
}
return true;
}
public override void Stop()
{
if (Instance != null)
StopInstance();
}
public Server Server { get; set; }
public ushort? Socks5LocalPort { get; set; }
public string LocalAddress { get; set; }
}
}

View File

@@ -1,27 +1,28 @@
using System.Collections.Generic;
using System.Linq;
using Netch.Controllers;
using Netch.Models;
using Netch.ServerEx.Socks5.Form;
using Netch.Servers.Socks5.Form;
using Newtonsoft.Json.Linq;
namespace Netch.ServerEx.Socks5
namespace Netch.Servers.Socks5
{
public class S5Util : IServerUtil
{
public ushort Priority { get; } = 0;
public string TypeName { get; } = "Socks5";
public string FullName { get; } = "Socks5";
public string ShortName { get; } = "S5";
public string[] UriScheme { get; } = { };
public Server ParseJObject(JObject j)
public Server ParseJObject(in JObject j)
{
return j.ToObject<Socks5>();
}
public void Edit(Server s)
{
new Socks5Form(s).ShowDialog();
new Socks5Form((Socks5) s).ShowDialog();
}
public void Create()
@@ -29,15 +30,18 @@ namespace Netch.ServerEx.Socks5
new Socks5Form().ShowDialog();
}
public string GetShareLink(Server server)
public string GetShareLink(Server s)
{
var server = (Socks5) s;
// https://t.me/socks?server=1.1.1.1&port=443
return $"https://t.me/socks?server={server.Hostname}&port={server.Port}";
return $"https://t.me/socks?server={server.Hostname}&port={server.Port}" +
$"{(!string.IsNullOrWhiteSpace(server.Username) ? $"&user={server.Username}" : "")}" +
$"{(server.Auth() ? $"&user={server.Password}" : "")}";
}
public ServerController GetController()
public IServerController GetController()
{
return null;
return new S5Controller();
}
public IEnumerable<Server> ParseUri(string text)
@@ -57,7 +61,7 @@ namespace Netch.ServerEx.Socks5
var data = new Socks5
{
Hostname = dict["server"],
Port = int.Parse(dict["port"])
Port = ushort.Parse(dict["port"])
};
if (dict.ContainsKey("user") && !string.IsNullOrWhiteSpace(dict["user"]))

View File

@@ -1,6 +1,6 @@
using Netch.Models;
namespace Netch.ServerEx.Socks5
namespace Netch.Servers.Socks5
{
public class Socks5 : Server
{
@@ -18,5 +18,7 @@ namespace Netch.ServerEx.Socks5
{
Type = "Socks5";
}
public bool Auth() => !string.IsNullOrWhiteSpace(Username) && !string.IsNullOrWhiteSpace(Password);
}
}

View File

@@ -0,0 +1,23 @@
using Netch.Forms;
namespace Netch.Servers.Trojan.Form
{
public class TrojanForm : ServerForm
{
protected override string TypeName { get; } = "Trojan";
public TrojanForm(Trojan server = default)
{
server ??= new Trojan();
Server = server;
CreateTextBox("Password", "Password",
s => true,
s => server.Password = s,
server.Password);
CreateTextBox("Host", "Host",
s => true,
s => server.Host = s,
server.Host);
}
}
}

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
namespace Netch.ServerEx.Trojan.Models
namespace Netch.Servers.Trojan.Models
{
public class TrojanConfig
{

View File

@@ -1,6 +1,6 @@
using Netch.Models;
namespace Netch.ServerEx.Trojan
namespace Netch.Servers.Trojan
{
public class Trojan : Server
{

View File

@@ -1,29 +1,37 @@
using System.Collections.Generic;
using System.IO;
using Netch.Controllers;
using Netch.Models;
using Netch.ServerEx.Trojan.Models;
using Netch.Servers.Trojan.Models;
using Netch.Utils;
using Newtonsoft.Json;
namespace Netch.ServerEx.Trojan
namespace Netch.Servers.Trojan
{
public class TrojanController : ServerController
public class TrojanController : Guard, IServerController
{
public TrojanController()
{
Name = "Trojan";
MainFile = "Trojan.exe";
StartedKeywords.Add("started");
StoppedKeywords.Add("exiting");
}
public override bool Start(Server s, Mode mode)
public override string MainFile { get; protected set; } = "Trojan.exe";
public override string Name { get; protected set; } = "Trojan";
public Server Server { get; set; }
public ushort? Socks5LocalPort { get; set; }
public string LocalAddress { get; set; }
public bool Start(in Server s, in Mode mode)
{
Server = s;
var server = (Trojan) s;
File.WriteAllText("data\\last.json", JsonConvert.SerializeObject(new TrojanConfig
{
local_addr = LocalAddress,
local_port = Socks5LocalPort,
remote_addr = server.Hostname,
local_addr = this.LocalAddress(),
local_port = this.Socks5LocalPort(),
remote_addr = server.AutoResolveHostname(),
remote_port = server.Port,
password = new List<string>
{

View File

@@ -2,28 +2,29 @@ using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using Netch.Controllers;
using Netch.Models;
using Netch.ServerEx.Trojan.Form;
using Netch.Servers.Trojan.Form;
using Newtonsoft.Json.Linq;
namespace Netch.ServerEx.Trojan
namespace Netch.Servers.Trojan
{
public class TrojanUtil : IServerUtil
{
public ushort Priority { get; } = 2;
public ushort Priority { get; } = 3;
public string TypeName { get; } = "Trojan";
public string FullName { get; } = "Trojan";
public string ShortName { get; } = "TR";
public string[] UriScheme { get; } = {"trojan"};
public Server ParseJObject(JObject j)
public Server ParseJObject(in JObject j)
{
return j.ToObject<Trojan>();
}
public void Edit(Server s)
{
new TrojanForm(s).ShowDialog();
new TrojanForm((Trojan) s).ShowDialog();
}
public void Create()
@@ -31,13 +32,13 @@ namespace Netch.ServerEx.Trojan
new TrojanForm().ShowDialog();
}
public string GetShareLink(Server server)
public string GetShareLink(Server s)
{
// TODO
return "";
var server = (Trojan) s;
return $"trojan://{HttpUtility.UrlEncode(server.Password)}@{server.Hostname}:{server.Port}#{server.Remark}";
}
public ServerController GetController()
public IServerController GetController()
{
return new TrojanController();
}
@@ -84,7 +85,7 @@ namespace Netch.ServerEx.Trojan
data.Password = match.Groups["psk"].Value;
data.Hostname = match.Groups["server"].Value;
data.Port = int.Parse(match.Groups["port"].Value);
data.Port = ushort.Parse(match.Groups["port"].Value);
return new[] {data};
}

View File

@@ -0,0 +1,46 @@
using System.Collections.Generic;
using Netch.Models;
using Netch.Servers.VMess;
namespace Netch.Servers.VLESS
{
public class VLESS : VMess.VMess
{
public VLESS()
{
Type = "VLESS";
}
/// <summary>
/// 加密方式
/// </summary>
public new string EncryptMethod { get; set; } = "none";
/// <summary>
/// 传输协议
/// </summary>
public new string TransferProtocol { get; set; } = VLESSGlobal.TransferProtocols[0];
/// <summary>
/// 伪装类型
/// </summary>
public new string FakeType { get; set; } = VLESSGlobal.FakeTypes[0];
/// <summary>
///
/// </summary>
public string Flow { get; set; }
}
public class VLESSGlobal
{
public static List<string> TransferProtocols => VMessGlobal.TransferProtocols;
public static readonly List<string> FakeTypes = new List<string>
{
"none",
"http"
};
}
}

View File

@@ -0,0 +1,30 @@
using System.IO;
using Netch.Controllers;
using Netch.Models;
using Netch.Servers.VMess.Utils;
namespace Netch.Servers.VLESS
{
public class VLESSController : Guard, IServerController
{
public override string Name { get; protected set; } = "VLESS";
public override string MainFile { get; protected set; } = "v2ray.exe";
public Server Server { get; set; }
public ushort? Socks5LocalPort { get; set; }
public string LocalAddress { get; set; }
public bool Start(in Server s,in Mode mode)
{
Server = s;
File.WriteAllText("data\\last.json", V2rayConfigUtils.GenerateClientConfig(s, mode));
return StartInstanceAuto("-config ..\\data\\last.json");
}
public override void Stop()
{
StopInstance();
}
}
}

View File

@@ -0,0 +1,60 @@
using System.Collections.Generic;
using Netch.Forms;
namespace Netch.Servers.VLESS.VLESSForm
{
class VLESSForm : ServerForm
{
protected override string TypeName { get; } = "VLESS";
public VLESSForm(VLESS server = default)
{
server ??= new VLESS();
Server = server;
CreateTextBox("UUID", "UUID",
s => true,
s => server.UserID = s,
server.UserID);
CreateTextBox("EncryptMethod", "Encrypt Method",
s => true,
s => server.EncryptMethod = !string.IsNullOrWhiteSpace(s) ? s : "none",
server.EncryptMethod);
CreateTextBox("Flow", "Flow",
s => true,
s => server.Flow = s,
server.Flow);
CreateComboBox("TransferProtocol", "Transfer Protocol",
VLESSGlobal.TransferProtocols,
s => server.TransferProtocol = s,
server.TransferProtocol);
CreateComboBox("FakeType", "Fake Type",
VLESSGlobal.FakeTypes,
s => server.FakeType = s,
server.FakeType);
CreateTextBox("Host", "Host",
s => true,
s => server.Host = s,
server.Host);
CreateTextBox("Path", "Path",
s => true,
s => server.Path = s,
server.Path);
CreateComboBox("TLSSecure", "TLS Secure",
new List<string> {"", "true", "false"},
s =>
{
server.TLSSecure = s switch
{
"" => null,
"true" => true,
"false" => false,
_ => null
};
},
server.TLSSecure?.ToString() ?? string.Empty);
CreateCheckBox("UseMux", "Use Mux",
b => server.UseMux = b,
server.UseMux);
}
}
}

View File

@@ -0,0 +1,53 @@
using System.Collections.Generic;
using Netch.Controllers;
using Netch.Models;
using Newtonsoft.Json.Linq;
namespace Netch.Servers.VLESS
{
public class VLESSUtil : IServerUtil
{
public ushort Priority { get; } = 2;
public string TypeName { get; } = "VLESS";
public string FullName { get; } = "VLESS";
public string ShortName { get; } = "VL";
public string[] UriScheme { get; } = { };
public Server ParseJObject(in JObject j)
{
return j.ToObject<VLESS>();
}
public void Edit(Server s)
{
new VLESSForm.VLESSForm((VLESS) s).ShowDialog();
}
public void Create()
{
new VLESSForm.VLESSForm().ShowDialog();
}
public string GetShareLink(Server server)
{
// TODO
return "";
}
public IServerController GetController()
{
return new VLESSController();
}
public IEnumerable<Server> ParseUri(string text)
{
throw new System.NotImplementedException();
}
public bool CheckServer(Server s)
{
// TODO
return true;
}
}
}

View File

@@ -0,0 +1,69 @@
using System.Collections.Generic;
using Netch.Forms;
namespace Netch.Servers.VMess.Form
{
public class VMessForm : ServerForm
{
protected override string TypeName { get; } = "VMess";
public VMessForm(VMess server = default)
{
server ??= new VMess();
Server = server;
CreateTextBox("UserId", "User ID",
s => true,
s => server.UserID = s,
server.UserID);
CreateTextBox("AlterId", "Alter ID",
s => int.TryParse(s, out _),
s => server.AlterID = int.Parse(s),
server.AlterID.ToString(),
76);
CreateComboBox("EncryptMethod", "Encrypt Method",
VMessGlobal.EncryptMethods,
s => server.EncryptMethod = s,
server.EncryptMethod);
CreateComboBox("TransferProtocol", "Transfer Protocol",
VMessGlobal.TransferProtocols,
s => server.TransferProtocol = s,
server.TransferProtocol);
CreateComboBox("FakeType", "Fake Type",
VMessGlobal.FakeTypes,
s => server.FakeType = s,
server.FakeType);
CreateTextBox("Host", "Host",
s => true,
s => server.Host = s,
server.Host);
CreateTextBox("Path", "Path",
s => true,
s => server.Path = s,
server.Path);
CreateComboBox("QUICSecurity", "QUIC Security",
VMessGlobal.QUIC,
s => server.QUIC = s,
server.QUIC);
CreateTextBox("QUICSecret", "QUIC Secret",
s => true,
s => server.QUICSecret = s,
server.QUICSecret);
CreateComboBox("TLSSecure", "TLS Secure",
new List<string> {"", "true", "false"},
s =>
{
server.TLSSecure = s switch
{
"" => null,
"true" => true,
"false" => false,
_ => null
};
},
server.TLSSecure?.ToString() ?? string.Empty);
CreateCheckBox("UseMux", "Use Mux",
s => server.UseMux = s,
server.UseMux);
}
}
}

View File

@@ -0,0 +1,287 @@
using System.Collections.Generic;
namespace Netch.Servers.VMess.Models
{
public class V2rayConfig
{
public List<Inbounds> inbounds { get; set; }
public List<Outbounds> outbounds { get; set; }
public Routing routing { get; set; }
}
public class Inbounds
{
public string tag { get; set; }
public ushort port { get; set; }
public string listen { get; set; }
public string protocol { get; set; }
public Sniffing sniffing { get; set; }
public Inboundsettings settings { get; set; }
public StreamSettings streamSettings { get; set; }
}
public class Inboundsettings
{
public string auth { get; set; }
public bool udp { get; set; }
public string ip { get; set; }
public string address { get; set; }
public List<UsersItem> clients { get; set; }
public string decryption { get; set; }
}
public class UsersItem
{
public string id { get; set; }
public int alterId { get; set; }
public string email { get; set; }
public string security { get; set; }
public string encryption { get; set; }
public string flow { get; set; }
}
public class Sniffing
{
public bool enabled { get; set; }
public List<string> destOverride { get; set; }
}
public class Outbounds
{
public string tag { get; set; }
public string protocol { get; set; }
public Outboundsettings settings { get; set; }
public StreamSettings streamSettings { get; set; }
public Mux mux { get; set; }
}
public class Outboundsettings
{
public List<VnextItem> vnext { get; set; }
public List<ServersItem> servers { get; set; }
public Response response { get; set; }
}
public class VnextItem
{
public string address { get; set; }
public ushort port { get; set; }
public List<UsersItem> users { get; set; }
}
public class ServersItem
{
public string email { get; set; }
public string address { get; set; }
public string method { get; set; }
public bool ota { get; set; }
public string password { get; set; }
public ushort port { get; set; }
public int level { get; set; }
public List<SocksUsersItem> users { get; set; }
}
public class SocksUsersItem
{
public string user { get; set; }
public string pass { get; set; }
public int level { get; set; }
}
public class Mux
{
public bool enabled { get; set; }
public int concurrency { get; set; }
}
public class Response
{
public string type { get; set; }
}
public class Dns
{
public List<string> servers { get; set; }
}
public class RulesItem
{
public string type { get; set; }
public string port { get; set; }
public List<string> inboundTag { get; set; }
public string outboundTag { get; set; }
public List<string> ip { get; set; }
public List<string> domain { get; set; }
}
public class Routing
{
public string domainStrategy { get; set; }
public List<RulesItem> rules { get; set; }
}
public class StreamSettings
{
public string network { get; set; }
public string security { get; set; }
public TlsSettings tlsSettings { get; set; }
public TcpSettings tcpSettings { get; set; }
public KcpSettings kcpSettings { get; set; }
public WsSettings wsSettings { get; set; }
public HttpSettings httpSettings { get; set; }
public QuicSettings quicSettings { get; set; }
public TlsSettings xtlsSettings { get; set; }
}
public class TlsSettings
{
public bool allowInsecure { get; set; }
public string serverName { get; set; }
}
public class TcpSettings
{
public bool connectionReuse { get; set; }
public Header header { get; set; }
}
public class Header
{
public string type { get; set; }
public TCPRequest request { get; set; }
public object response { get; set; }
}
public class TCPRequest
{
public string version = "1.1";
public string method = "GET";
public string path = "/";
public TCPRequestHeaders headers;
}
public class TCPRequestHeaders
{
public string Host;
//public string User_Agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36";
public string Accept_Encoding = "gzip, deflate";
public string Connection = "keep-alive";
public string Pragma = "no-cache";
}
public class KcpSettings
{
public int mtu { get; set; }
public int tti { get; set; }
public int uplinkCapacity { get; set; }
public int downlinkCapacity { get; set; }
public bool congestion { get; set; }
public int readBufferSize { get; set; }
public int writeBufferSize { get; set; }
public Header header { get; set; }
public string seed { get; set; }
}
public class WsSettings
{
public bool connectionReuse { get; set; }
public string path { get; set; }
public Headers headers { get; set; }
}
public class Headers
{
public string Host { get; set; }
}
public class HttpSettings
{
public string path { get; set; }
public List<string> host { get; set; }
}
public class QuicSettings
{
public string security { get; set; }
public string key { get; set; }
public Header header { get; set; }
}
}

View File

@@ -1,76 +1,63 @@
namespace Netch.ServerEx.VMess.Models
namespace Netch.Servers.VMess.Models
{
/// <summary>
/// 使用 v2rayN 定义的 VMess 链接格式
/// </summary>
public class VMessJObject
public class V2rayNSharing
{
/// <summary>
/// Mux Class
/// </summary>
public class Mux
{
public object enabled;
}
/// <summary>
/// 链接版本
/// </summary>
public string v;
public string v = string.Empty;
/// <summary>
/// 备注
/// </summary>
public string ps;
public string ps = string.Empty;
/// <summary>
/// 地址
/// </summary>
public string add;
public string add = string.Empty;
/// <summary>
/// 端口
/// </summary>
public int port;
public string port = string.Empty;
/// <summary>
/// 用户 ID
/// </summary>
public string id;
public string id = string.Empty;
/// <summary>
/// 额外 ID
/// </summary>
public int aid = 0;
public string aid = string.Empty;
/// <summary>
/// 传输协议
/// </summary>
public string net;
public string net = string.Empty;
/// <summary>
/// 伪装类型
/// </summary>
public string type;
public string type = string.Empty;
/// <summary>
/// 伪装域名HTTPWS
/// </summary>
public string host;
public string host = string.Empty;
/// <summary>
/// 伪装路径
/// </summary>
public string path;
public string path = string.Empty;
/// <summary>
/// 是否使用 TLS
/// </summary>
public string tls;
/// <summary>
/// Mux 多路复用
/// </summary>
public Mux mux;
public string tls = string.Empty;
}
}

View File

@@ -0,0 +1,374 @@
using System.Collections.Generic;
using Netch.Models;
using Netch.Servers.VMess.Models;
using Newtonsoft.Json;
using V2rayConfig = Netch.Servers.VMess.Models.V2rayConfig;
namespace Netch.Servers.VMess.Utils
{
public static class V2rayConfigUtils
{
public static string GenerateClientConfig(Server server, Mode mode)
{
try
{
var v2rayConfig = new V2rayConfig();
inbound(server, ref v2rayConfig);
routing(server, mode, ref v2rayConfig);
outbound(server, ref v2rayConfig);
return JsonConvert.SerializeObject(v2rayConfig);
}
catch
{
return "";
}
}
private static void inbound(Server server, ref V2rayConfig v2rayConfig)
{
try
{
var inbound = new Inbounds
{
port = Global.Settings.Socks5LocalPort,
protocol = "socks",
listen = Global.Settings.LocalAddress,
settings = new Inboundsettings
{
udp = true
}
};
v2rayConfig.inbounds = new List<Inbounds>
{
inbound
};
}
catch
{
// ignored
}
}
private static void routing(Server server, Mode mode, ref V2rayConfig v2rayConfig)
{
try
{
RulesItem rulesItem;
if (mode.BypassChina)
{
rulesItem = new RulesItem
{
type = "field",
ip = new List<string>
{
"geoip:cn",
"geoip:private"
},
domain = new List<string>
{
"geosite:cn"
},
outboundTag = "direct"
};
}
else
{
rulesItem = new RulesItem
{
type = "field",
ip = new List<string>
{
"geoip:private"
},
outboundTag = "direct"
};
}
v2rayConfig.routing = new Routing
{
rules = new List<RulesItem>
{
rulesItem
}
};
}
catch
{
// ignored
}
}
private static void outbound(Server server, ref V2rayConfig v2rayConfig)
{
try
{
var outbound = new Outbounds
{
settings = new Outboundsettings(),
mux = new Mux(),
streamSettings = new StreamSettings
{
network = "tcp"
}
};
switch (server)
{
case Socks5.Socks5 socks5:
{
var serversItem = new ServersItem
{
users = new List<SocksUsersItem>()
};
outbound.settings.servers = new List<ServersItem>
{
serversItem
};
serversItem.address = server.AutoResolveHostname();
serversItem.port = server.Port;
serversItem.method = null;
serversItem.password = null;
if (socks5.Auth())
{
var socksUsersItem = new SocksUsersItem
{
user = socks5.Username,
pass = socks5.Password,
level = 1
};
serversItem.users.Add(socksUsersItem);
}
outbound.mux.enabled = false;
outbound.mux.concurrency = -1;
outbound.protocol = "socks";
break;
}
case VLESS.VLESS vless:
{
var vnextItem = new VnextItem
{
users = new List<UsersItem>()
};
outbound.settings.vnext = new List<VnextItem>
{
vnextItem
};
vnextItem.address = server.AutoResolveHostname();
vnextItem.port = server.Port;
var usersItem = new UsersItem();
vnextItem.users.Add(usersItem);
usersItem.id = vless.UserID;
usersItem.alterId = 0;
usersItem.flow = string.Empty;
usersItem.encryption = vless.EncryptMethod;
outbound.mux.enabled = vless.UseMux;
outbound.mux.concurrency = vless.UseMux ? 8 : -1;
var streamSettings = outbound.streamSettings;
boundStreamSettings(vless, ref streamSettings);
if (vless.TransferProtocol == "xtls")
{
usersItem.flow = string.IsNullOrEmpty(vless.Flow) ? "xtls-rprx-origin" : vless.Flow;
outbound.mux.enabled = false;
outbound.mux.concurrency = -1;
}
outbound.protocol = "vless";
outbound.settings.servers = null;
break;
}
case VMess vmess:
{
var vnextItem = new VnextItem
{
users = new List<UsersItem>()
};
outbound.settings.vnext = new List<VnextItem>
{
vnextItem
};
vnextItem.address = server.AutoResolveHostname();
vnextItem.port = server.Port;
var usersItem = new UsersItem();
vnextItem.users.Add(usersItem);
usersItem.id = vmess.UserID;
usersItem.alterId = vmess.AlterID;
usersItem.security = vmess.EncryptMethod;
outbound.mux.enabled = vmess.UseMux;
outbound.mux.concurrency = vmess.UseMux ? 8 : -1;
var streamSettings = outbound.streamSettings;
boundStreamSettings(vmess, ref streamSettings);
outbound.protocol = "vmess";
break;
}
}
v2rayConfig.outbounds = new List<Outbounds> {outbound};
}
catch
{
// ignored
}
}
private static void boundStreamSettings(VMess server, ref StreamSettings streamSettings)
{
try
{
streamSettings.network = server.TransferProtocol;
var host = server.Host;
if (server.TLSSecure ?? Global.Settings.V2RayConfig.AllowInsecure)
{
streamSettings.security = "tls";
var tlsSettings = new TlsSettings
{
allowInsecure = true
};
if (!string.IsNullOrWhiteSpace(host))
{
tlsSettings.serverName = host;
}
streamSettings.tlsSettings = tlsSettings;
}
else
{
streamSettings.security = "";
}
switch (server.TransferProtocol)
{
case "kcp":
var kcpSettings = new KcpSettings
{
mtu = Global.Settings.V2RayConfig.KcpConfig.mtu,
tti = Global.Settings.V2RayConfig.KcpConfig.tti,
uplinkCapacity = Global.Settings.V2RayConfig.KcpConfig.uplinkCapacity,
downlinkCapacity = Global.Settings.V2RayConfig.KcpConfig.downlinkCapacity,
congestion = Global.Settings.V2RayConfig.KcpConfig.congestion,
readBufferSize = Global.Settings.V2RayConfig.KcpConfig.readBufferSize,
writeBufferSize = Global.Settings.V2RayConfig.KcpConfig.writeBufferSize,
header = new Header
{
type = server.FakeType
},
seed = !string.IsNullOrWhiteSpace(server.Path) ? server.Path : null
};
streamSettings.kcpSettings = kcpSettings;
break;
case "ws":
var path = server.Path;
var wsSettings = new WsSettings
{
connectionReuse = true,
headers = !string.IsNullOrWhiteSpace(host)
? new Headers
{
Host = host
}
: null,
path = !string.IsNullOrWhiteSpace(path) ? path : null
};
streamSettings.wsSettings = wsSettings;
break;
case "h2":
var httpSettings = new HttpSettings
{
host = new List<string>
{
string.IsNullOrWhiteSpace(server.Host) ? server.Hostname : server.Host
},
path = server.Path
};
streamSettings.httpSettings = httpSettings;
break;
case "quic":
var quicSettings = new QuicSettings
{
security = host,
key = server.Path,
header = new Header
{
type = server.FakeType
}
};
if (server.TLSSecure ?? Global.Settings.V2RayConfig.AllowInsecure)
{
streamSettings.tlsSettings.serverName = server.Hostname;
}
streamSettings.quicSettings = quicSettings;
break;
case "xtls":
streamSettings.security = server.TransferProtocol;
var xtlsSettings = new TlsSettings
{
allowInsecure = true
};
if (!string.IsNullOrWhiteSpace(host))
{
xtlsSettings.serverName = host;
}
streamSettings.xtlsSettings = xtlsSettings;
break;
default:
if (server.FakeType == "http")
{
var tcpSettings = new TcpSettings
{
connectionReuse = true,
header = new Header
{
type = server.FakeType,
request = new TCPRequest
{
path = string.IsNullOrWhiteSpace(server.Path) ? "/" : server.Path,
headers = new TCPRequestHeaders
{
Host = string.IsNullOrWhiteSpace(server.Host) ? server.Hostname : server.Host
}
}
}
};
streamSettings.tcpSettings = tcpSettings;
}
break;
}
}
catch
{
// ignored
}
}
}
}

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using Netch.Models;
namespace Netch.ServerEx.VMess
namespace Netch.Servers.VMess
{
public class VMess : Server
{
@@ -64,7 +64,7 @@ namespace Netch.ServerEx.VMess
/// <summary>
/// TLS 底层传输安全
/// </summary>
public bool TLSSecure { get; set; } = false;
public bool? TLSSecure { get; set; }
/// <summary>
/// Mux 多路复用

View File

@@ -0,0 +1,35 @@
using System.IO;
using Netch.Controllers;
using Netch.Models;
using Netch.Servers.VMess.Utils;
namespace Netch.Servers.VMess
{
public class VMessController : Guard, IServerController
{
public VMessController()
{
StartedKeywords.Add("started");
StoppedKeywords.AddRange(new[] {"config file not readable", "failed to"});
}
public override string Name { get; protected set; } = "V2Ray";
public override string MainFile { get; protected set; } = "v2ray.exe";
public Server Server { get; set; }
public ushort? Socks5LocalPort { get; set; }
public string LocalAddress { get; set; }
public bool Start(in Server s,in Mode mode)
{
Server = s;
File.WriteAllText("data\\last.json", V2rayConfigUtils.GenerateClientConfig(s, mode));
return StartInstanceAuto("-config ..\\data\\last.json");
}
public override void Stop()
{
StopInstance();
}
}
}

View File

@@ -1,28 +1,31 @@
using System;
using System.Collections.Generic;
using Netch.Controllers;
using Netch.Models;
using Netch.ServerEx.VMess.Form;
using Netch.ServerEx.VMess.Models;
using Netch.Servers.VMess.Form;
using Netch.Servers.VMess.Models;
using Netch.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Netch.ServerEx.VMess
namespace Netch.Servers.VMess
{
public class VMessUtil : IServerUtil
{
public ushort Priority { get; } = 2;
public ushort Priority { get; } = 3;
public string TypeName { get; } = "VMess";
public string FullName { get; } = "VMess";
public string ShortName { get; } = "V2";
public string[] UriScheme { get; } = {"vmess"};
public Server ParseJObject(JObject j)
public Server ParseJObject(in JObject j)
{
return j.ToObject<VMess>();
}
public void Edit(Server s)
{
new VMessForm(s).ShowDialog();
new VMessForm((VMess) s).ShowDialog();
}
public void Create()
@@ -46,12 +49,12 @@ namespace Netch.ServerEx.VMess
type = server.FakeType,
host = server.Host,
path = server.Path,
tls = server.TLSSecure ? "tls" : ""
tls = server.TLSSecure ?? Global.Settings.V2RayConfig.AllowInsecure ? "tls" : ""
});
return "vmess://" + ShareLink.URLSafeBase64Encode(vmessJson);
}
public ServerController GetController()
public IServerController GetController()
{
return new VMessController();
}
@@ -61,26 +64,25 @@ namespace Netch.ServerEx.VMess
var data = new VMess();
text = text.Substring(8);
var vmess = JsonConvert.DeserializeObject<VMessJObject>(ShareLink.URLSafeBase64Decode(text));
V2rayNSharing vmess;
try
{
vmess = JsonConvert.DeserializeObject<V2rayNSharing>(ShareLink.URLSafeBase64Decode(text));
}
catch (Exception e)
{
Logging.Warning(e.ToString());
return null;
}
data.Remark = vmess.ps;
data.Hostname = vmess.add;
data.Port = vmess.port;
data.Port = ushort.Parse(vmess.port);
data.UserID = vmess.id;
data.AlterID = vmess.aid;
data.AlterID = int.Parse(vmess.aid);
data.TransferProtocol = vmess.net;
data.FakeType = vmess.type;
if (vmess.v == null || vmess.v == "1")
{
var info = vmess.host.Split(';');
if (info.Length == 2)
{
vmess.host = info[0];
vmess.path = info[1];
}
}
if (data.TransferProtocol == "quic")
{
if (VMessGlobal.QUIC.Contains(vmess.host))
@@ -96,28 +98,8 @@ namespace Netch.ServerEx.VMess
}
data.TLSSecure = vmess.tls == "tls";
if (vmess.mux == null)
{
data.UseMux = false;
}
else
{
if (vmess.mux.enabled is bool enabled)
{
data.UseMux = enabled;
}
else if (vmess.mux.enabled is string muxEnabled)
{
data.UseMux = muxEnabled == "true"; // 针对使用字符串当作布尔值的情况
}
else
{
data.UseMux = false;
}
}
data.EncryptMethod = "auto"; // V2Ray 加密方式不包括在链接中,主动添加一个
return CheckServer(data) ? new[] {data} : null;
}

View File

@@ -7,6 +7,7 @@ using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Session;
using Netch.Controllers;
using Netch.Models;
using Netch.Servers.Shadowsocks;
namespace Netch.Utils
{
@@ -52,7 +53,7 @@ namespace Netch.Utils
/// <summary>
/// 根据程序名统计流量
/// </summary>
public static void NetTraffic(Server server, Mode mode)
public static void NetTraffic(in Server server, in Mode mode)
{
if (!Global.Flags.IsWindows10Upper)
return;
@@ -66,18 +67,29 @@ namespace Netch.Utils
{
instances.Add(((HTTPController) MainController.ModeController).pPrivoxyController.Instance);
}
else if (server.Type.Equals("SS") && Global.Settings.BootShadowsocksFromDLL &&
(mode.Type == 0 || mode.Type == 1 || mode.Type == 2))
{
instances.Add(Process.GetCurrentProcess());
}
else if (MainController.ServerController != null)
{
instances.Add(MainController.ServerController.Instance);
switch (MainController.ServerController)
{
case SSController ssController when ssController.DllFlag:
instances.Add(Process.GetCurrentProcess());
break;
case Guard instanceController:
instances.Add(instanceController.Instance);
break;
}
}
else if (MainController.ModeController != null)
{
instances.Add(MainController.ModeController.Instance);
switch (MainController.ModeController)
{
case NFController _:
instances.Add(Process.GetCurrentProcess());
break;
case Guard instanceController:
instances.Add(instanceController.Instance);
break;
}
}
var processList = instances.Select(instance => instance.Id).ToList();

View File

@@ -32,7 +32,7 @@ namespace Netch.Utils
foreach (JObject server in settingJObject["Server"])
{
var serverResult = Servers.ParseJObject(server);
var serverResult = ServerHelper.ParseJObject(server);
if (serverResult != null)
Global.Settings.Server.Add(serverResult);
}

View File

@@ -49,6 +49,8 @@ namespace Netch.Utils
private static RegistryKey AdapterRegistry(bool write = false)
{
if (Global.Outbound.Adapter == null)
Utils.SearchOutboundAdapter();
return Registry.LocalMachine.OpenSubKey(
$@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{Global.Outbound.Adapter.Id}", write);
}

View File

@@ -5,7 +5,7 @@ using NetFwTypeLib;
namespace Netch.Utils
{
public class Firewall
public static class Firewall
{
private static readonly string[] ProgramPath =
{

View File

@@ -1,34 +1,52 @@
using System;
using System.Linq;
using System.Management;
using Netch.Utils;
using Netch.Controllers;
using Netch.Models.WinFW;
using NETCONLib;
using WinFW;
namespace Netch.Controllers
namespace Netch.Utils
{
public class ICSController
public static class ICSHelper
{
public static bool Enabled
public static bool? Enabled
{
get
{
TUNTAPController.SearchTapAdapter();
AutoSearchTapAdapter();
if (Global.TUNTAP.Adapter == null)
return null;
foreach (NetworkConnection connection in new NetworkConnectionCollection())
{
if (connection.DeviceName == Global.TUNTAP.Adapter.Description)
try
{
return connection.SharingEnabled;
if (connection.DeviceName == Global.TUNTAP.Adapter?.Description)
{
return connection.SharingEnabled;
}
}
catch (Exception e)
{
Logging.Warning(e.ToString());
}
}
return false;
return null;
}
}
private static void AutoSearchTapAdapter()
{
if (Global.TUNTAP.Adapter == null)
TUNTAPController.SearchTapAdapter();
}
public static bool Enable()
{
Utils.Utils.SearchOutboundAdapter();
TUNTAPController.SearchTapAdapter();
Utils.SearchOutboundAdapter(false);
AutoSearchTapAdapter();
if (Global.TUNTAP.Adapter == null || Global.Outbound.Adapter == null)
{
@@ -41,10 +59,7 @@ namespace Netch.Controllers
#region Save Outbound IP Config
var wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
var moc = wmi.GetInstances();
var dhcpEnabled = true;
bool dhcpEnabled;
string[] ipAddress = null;
string[] subnetMask = null;
string[] gateway = null;
@@ -101,19 +116,19 @@ namespace Netch.Controllers
else
{
//Set static IP and subnet mask
var newIP = outboundWmi.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = ipAddress;
newIP["SubnetMask"] = subnetMask;
outboundWmi.InvokeMethod("EnableStatic", newIP, null);
var ip = outboundWmi.GetMethodParameters("EnableStatic");
ip["IPAddress"] = ipAddress;
ip["SubnetMask"] = subnetMask;
outboundWmi.InvokeMethod("EnableStatic", ip, null);
//Set default gateway
var newGateway = outboundWmi.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = gateway;
newGateway["GatewayCostMetric"] = gatewayMetric;
outboundWmi.InvokeMethod("SetGateways", newGateway, null);
//Set dns servers
var newDNS = outboundWmi.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = dns;
outboundWmi.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
var newDns = outboundWmi.GetMethodParameters("SetDNSServerSearchOrder");
newDns["DNSServerSearchOrder"] = dns;
outboundWmi.InvokeMethod("SetDNSServerSearchOrder", newDns, null);
}
#endregion
@@ -141,8 +156,17 @@ namespace Netch.Controllers
{
foreach (NetworkConnection connection in new NetworkConnectionCollection())
{
if (connection.SharingEnabled)
connection.DisableSharing();
try
{
if (connection.SharingEnabled)
{
connection.DisableSharing();
}
}
catch (Exception e)
{
Logging.Warning(e.ToString());
}
}
CleanupWMISharingEntries();
@@ -153,25 +177,27 @@ namespace Netch.Controllers
var scope = new ManagementScope("root\\Microsoft\\HomeNet");
scope.Connect();
var options = new PutOptions();
options.Type = PutType.UpdateOnly;
var query = new ObjectQuery("SELECT * FROM HNet_ConnectionProperties");
var srchr = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject entry in srchr.Get())
var searchResults = new ManagementObjectSearcher(scope, new ObjectQuery("SELECT * FROM HNet_ConnectionProperties"));
foreach (var o in searchResults.Get())
{
var entry = (ManagementObject) o;
if ((bool) entry["IsIcsPrivate"])
entry["IsIcsPrivate"] = false;
if ((bool) entry["IsIcsPublic"])
entry["IsIcsPublic"] = false;
entry.Put(options);
entry.Put(new PutOptions
{
Type = PutType.UpdateOnly
});
}
}
public static ManagementObject GetManagementObjectByDeviceNameOrDefault(string deviceName)
private static ManagementObject GetManagementObjectByDeviceNameOrDefault(string deviceName)
{
foreach (ManagementObject mo in new ManagementClass("Win32_NetworkAdapterConfiguration").GetInstances())
foreach (var o in new ManagementClass("Win32_NetworkAdapterConfiguration").GetInstances())
{
var mo = (ManagementObject) o;
if (((string) mo["Caption"]).EndsWith(deviceName))
{
return mo;

View File

@@ -2,11 +2,13 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Netch.Controllers;
using Netch.Forms;
using Netch.Models;
namespace Netch.Utils
{
public static class Modes
public static class ModeHelper
{
private const string MODE_DIR = "mode";
@@ -60,22 +62,21 @@ namespace Netch.Utils
for (var i = 0; i < content.Length; i++)
{
var text = content[i];
var text = content[i].Trim();
if (i == 0)
{
var splited = text.Substring(text.IndexOf('#') + 1).Split(',').Select(s => s.Trim()).ToArray();
try
{
string tmp;
if ((tmp = splited.ElementAtOrDefault(0)) != null)
mode.Remark = i18N.Translate(tmp);
var splited = text.Substring(text.IndexOf('#') + 1).Split(',').Select(s => s.Trim()).ToArray();
tmp = splited.ElementAtOrDefault(1);
mode.Type = tmp != null ? int.Parse(tmp) : 0;
mode.Remark = splited[0];
if ((tmp = splited.ElementAtOrDefault(2)) != null)
mode.BypassChina = int.Parse(tmp) == 1;
var result = int.TryParse(splited.ElementAtOrDefault(1), out var type);
mode.Type = result ? type : 0;
var result1 = int.TryParse(splited.ElementAtOrDefault(2), out var bypassChina);
mode.BypassChina = result1 && bypassChina == 1;
}
catch
{
@@ -84,8 +85,7 @@ namespace Netch.Utils
}
else
{
if (!text.StartsWith("#") && !string.IsNullOrWhiteSpace(text))
mode.Rule.Add(text.Trim());
mode.Rule.Add(text);
}
}
@@ -134,5 +134,40 @@ namespace Netch.Utils
Global.Modes.Remove(mode);
Global.MainForm.InitMode();
}
public static IModeController GetModeControllerByType(int type, out ushort? port, out string portName, out PortType portType)
{
IModeController modeController;
port = null;
portName = string.Empty;
portType = PortType.Both;
switch (type)
{
case 0:
modeController = new NFController();
port = Global.Settings.RedirectorTCPPort;
portName = "Redirector TCP";
break;
case 1:
case 2:
modeController = new TUNTAPController();
break;
case 3:
case 5:
modeController = new HTTPController();
port = Global.Settings.HTTPLocalPort;
portName = "HTTP";
MainForm.StatusPortInfoText.HttpPort = (ushort) port;
break;
case 4:
modeController = null;
break;
default:
Logging.Error("未知模式类型");
throw new StartFailedException();
}
return modeController;
}
}
}

View File

@@ -5,7 +5,7 @@ using System.Text;
namespace Netch.Utils
{
public class OnlyInstance
public static class OnlyInstance
{
public enum Commands
{

View File

@@ -8,8 +8,8 @@ namespace Netch.Utils
{
public static class PortHelper
{
private static readonly List<int[]> TCPExcludedRanges = new List<int[]>();
private static readonly List<int[]> UDPExcludedRanges = new List<int[]>();
private static readonly List<ushort[]> TCPExcludedRanges = new List<ushort[]>();
private static readonly List<ushort[]> UDPExcludedRanges = new List<ushort[]>();
static PortHelper()
{
@@ -24,7 +24,7 @@ namespace Netch.Utils
}
}
private static void GetExcludedPortRange(PortType portType, ref List<int[]> targetList)
private static void GetExcludedPortRange(PortType portType, ref List<ushort[]> targetList)
{
var lines = new List<string>();
var process = new Process
@@ -63,9 +63,9 @@ namespace Netch.Utils
var value = line.Trim().Split(' ').Where(s => s != string.Empty);
var port = 0;
ushort port = 0;
var _ = (from s1 in value
where int.TryParse(s1, out port)
where ushort.TryParse(s1, out port)
select port).ToArray();
targetList.Add(_);
@@ -80,7 +80,7 @@ namespace Netch.Utils
/// <param name="type">端口类型</param>
/// <returns>是否是保留端口</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private static bool IsPortExcluded(int port, PortType type)
private static bool IsPortExcluded(ushort port, PortType type)
{
return type switch
{
@@ -97,7 +97,7 @@ namespace Netch.Utils
/// <param name="port">端口</param>
/// <param name="type">检查端口类型</param>
/// <returns>是否被占用</returns>
public static bool PortInUse(int port, PortType type = PortType.Both)
public static bool PortInUse(ushort port, PortType type = PortType.Both)
{
var netInfo = IPGlobalProperties.GetIPGlobalProperties();
var isTcpUsed = type != PortType.UDP &&
@@ -111,11 +111,12 @@ namespace Netch.Utils
return isPortExcluded && (isTcpUsed || isUdpUsed);
}
public static int GetAvailablePort()
public static ushort GetAvailablePort()
{
for (var i = 0; i < 55535; i++)
var random = new Random();
for (ushort i = 0; i < 55535; i++)
{
var p = new Random().Next(10000, 65535);
var p = (ushort) random.Next(10000, 65535);
if (!PortInUse(p))
{
return p;
@@ -128,7 +129,7 @@ namespace Netch.Utils
/// <summary>
/// 记录Netch使用的端口
/// </summary>
public static readonly List<int> UsingPorts = new List<int>();
public static readonly List<ushort> UsingPorts = new List<ushort>();
}
/// <summary>

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