Compare commits

...

154 Commits
1.6.5 ... 1.7.3

Author SHA1 Message Date
ChsBuffer
8e83359e39 Bump version to 1.7.3 2021-01-26 21:57:24 +08:00
ChsBuffer
d2b6d182ff Remove Delay Test "Test done" Notification 2021-01-26 21:51:47 +08:00
ChsBuffer
019044c275 Refactor:
Move NatTest to MainForm
  Move call NetTraffic() NatTest() to ControlButton_Click()
2021-01-26 21:50:33 +08:00
ChsBuffer
df48eb3067 Disable Update Servers with proxy when started 2021-01-26 21:43:33 +08:00
ChsBuffer
6bfcae453f Fix #498 , again 2021-01-26 21:36:23 +08:00
ChsBuffer
7d55af2101 Fix speed test caused lost status port info 2021-01-26 00:59:46 +08:00
ChsBuffer
9172ede7c2 Refactor DrawItem 2021-01-18 05:51:38 +08:00
ChsBuffer
fb8aa548ac Cut: Exclude Server.Delay property from serialization. 2021-01-18 04:11:10 +08:00
ChsBuffer
46643a3f5e Fix: Detection Tick be enabled by MainForm.State even disabled by value 0 2021-01-18 04:06:28 +08:00
ChsBuffer
99752d7a44 Refactor Check settings change
Refactor Check Detection Tick value
Fix sometimes Detection Tick not update
2021-01-18 01:01:07 +08:00
ChsBuffer
004b84ceda Fix #498 2021-01-16 22:40:05 +08:00
ChsBuffer
d15206b803 Bump version to 1.7.2 2021-01-15 19:57:28 +08:00
ChsBuffer
754753300d Refactor Test All Server Delay Tick 2021-01-15 19:53:44 +08:00
ChsBuffer
aa021aaf79 Fix Build 2021-01-15 19:43:09 +08:00
ChsBuffer
c50ca563b2 Improve Force Exit 2021-01-15 19:42:49 +08:00
ChsBuffer
a1fdf7ead2 Update SettingForm 2021-01-15 18:09:36 +08:00
ChsBuffer
c9da7197ba Refactor: Merge MainForm 2021-01-15 16:24:59 +08:00
ChsBuffer
5ff26e97b4 trim 2021-01-14 20:13:15 +08:00
ChsBuffer
06049cb06f Refactor Servers Test Delay Interval 2021-01-14 19:52:23 +08:00
ChsBuffer
8cf765de92 Feat: Update Download Progress 2021-01-14 16:28:14 +08:00
ChsBuffer
2b53a7ca9e Refactor UpdateChecker.cs 2021-01-14 15:54:17 +08:00
ChsBuffer
c7c0a2a698 Update README 2021-01-13 21:16:53 +08:00
ChsBuffer
1d072214ee Refactor Check Port 2021-01-13 20:22:15 +08:00
AmazingDM
135ff642bd Update NF driver to 1.6.0.2 2021-01-13 09:53:52 +08:00
Connection Refused
4c274a1888 Update zh-CN 2021-01-13 02:23:11 +08:00
ChsBuffer
59cfc071cc [Break] Rename UpdateSubscribeatWhenOpened to UpdateServersWhenOpened 2021-01-12 19:13:14 +08:00
ChsBuffer
8cf32e5d37 Feat: MainForm.UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem,
"Update server at startup" uses proxy based on the last update servers operation
2021-01-12 19:02:27 +08:00
ChsBuffer
7a1e5b58b9 SubscribeForm: Refactor 2021-01-12 18:28:38 +08:00
ChsBuffer
651fbb6ff9 SubscribeForm: Fix Enable Checked Event, Organize code 2021-01-12 17:46:52 +08:00
ChsBuffer
45bf31e9f3 Fix SubscribeForm Edit 2021-01-12 17:02:57 +08:00
AmazingDM
f7c9ab4028 Update NTT to 3.4 2021-01-11 17:10:19 +08:00
AmazingDM
717dc55055 Delete subscribeForm alert 2021-01-11 11:54:25 +08:00
ChsBuffer
a0c4dd3192 Replace NetchCore with RouteHelper 2021-01-10 20:58:49 +08:00
AmazingDM
325ad430fe Bump version to 1.7.1 2021-01-09 02:33:00 +00:00
ChsBuffer
4b374d3898 Disable Update PAC when started 2021-01-07 11:01:23 +08:00
ChsBuffer
b6afeab187 trim 2021-01-07 10:54:50 +08:00
ChsBuffer
6e499c3948 Update Option items Notification 2021-01-07 10:52:58 +08:00
ChsBuffer
5bfcbab543 Comment ExitToolStripMenuIten_Click Handler 2021-01-05 18:10:10 +08:00
ChsBuffer
fe69c5a67b Refactor show Bandwidth 2021-01-05 17:55:08 +08:00
ChsBuffer
1c974d295b Revert "️"
This reverts commit a544bd1a26.
2021-01-05 17:54:00 +08:00
AmazingDM
a544bd1a26 2021-01-05 17:37:14 +08:00
AmazingDM
3bfe03b99b 更新添加模式窗口汉化,优化代码 2021-01-05 17:21:36 +08:00
AmazingDM
1fa18ce787 Merge branch 'master' of https://github.com/NetchX/Netch 2021-01-05 17:12:50 +08:00
AmazingDM
f7ad2baa52 Optimized code 2021-01-05 17:11:11 +08:00
AmazingDM
447a25457b Update Advanced_Usage.zh-CN.md 2021-01-05 16:44:46 +08:00
AmazingDM
3a8351e6e4 Update README.md 2021-01-05 16:39:54 +08:00
AmazingDM
eb30300b24 Update README.zh-CN.md 2021-01-05 16:39:50 +08:00
AmazingDM
0b8373a21e Update README.md 2021-01-05 16:34:37 +08:00
AmazingDM
8a551b715e 订阅链接启用状态默认为true 2021-01-05 13:01:16 +08:00
AmazingDM
34814fe7f5 订阅窗口可右键删除订阅节点
新增订阅链接勾选项(订阅启用状态)
更新订阅窗口汉化
2021-01-05 11:55:04 +08:00
AmazingDM
528abe3fdd Socks5无验证时不显示流量统计
更新PAC
2021-01-04 18:45:01 +08:00
AmazingDM
a10410dafd Update ck-client to v2.5.2 https://github.com/cbeuw/Cloak/releases/tag/v2.5.2 2021-01-04 15:22:46 +08:00
AmazingDM
2ca98a94d5 rename UninstallTap method 2021-01-04 15:09:01 +08:00
AmazingDM
ac2e5e943e Update mode 2021-01-04 14:05:15 +08:00
AmazingDM
0957514e05 Bump version to 1.7.0 2021-01-04 14:01:20 +08:00
AmazingDM
35b9f168ff 添加测速方式(TCPing&ICMPing)切换设置选项 2021-01-04 13:59:19 +08:00
AmazingDM
ce15e9468e 不代理TCP流量设置
调整设置界面UI
2021-01-04 13:23:58 +08:00
AmazingDM
4c8508a838 Merge remote-tracking branch 'chsbuffer/fixJob' 2021-01-04 12:45:19 +08:00
ChsBuffer
f931adb005 Fix TrojanController ignores sni (host) value
closes #478, #487
2020-12-31 15:04:53 +08:00
Connection Refused
d4f829d4bd Merge pull request #486 from SekiBetu/dev
set mux to false by default
2020-12-30 09:26:44 +08:00
SekiBetu
51d4ba0fdb set mux to false by default 2020-12-30 06:37:02 +08:00
AmazingDM
ca0870889a 更新NTT,优化部分代码 2020-12-28 15:21:43 +08:00
ChsBuffer
ac3e39e9cd Update AioDNS 2020-12-25 22:44:44 +08:00
ChsBuffer
84765ab96d Delay Add Job 2020-12-25 17:12:03 +08:00
AmazingDM
a18851af15 Update binaries 2020-12-25 13:48:40 +08:00
AmazingDM
42366abcca Update README.md Quote 2020-12-25 13:43:33 +08:00
AmazingDM
cec8358922 PAC 2020-12-25 11:28:38 +08:00
AmazingDM
db8e964351 Update translations 2020-12-25 09:43:48 +08:00
AmazingDM
ad3053298a PAC替换ACL
sysproxy.dll 替换为 nuget WindowsProxy
2020-12-24 22:57:52 +08:00
ChsBuffer
669ca4902f Fix: set encoding only when RedireStd enabled 2020-12-24 16:14:41 +08:00
ChsBuffer
272bf61b0f Remove RedirecStandInput (Fix SS plugin start error) 2020-12-24 15:59:51 +08:00
ChsBuffer
0051e7bb50 Feat ICMPing 2020-12-24 13:32:06 +08:00
ChsBuffer
aa5faa9af6 bump version to 1.6.9 2020-12-22 22:21:23 +08:00
ChsBuffer
a92d1c8244 Update translations 2020-12-22 22:21:09 +08:00
ChsBuffer
6bdcc7ce04 Fix GenerateV2RayConfig 2020-12-22 20:59:29 +08:00
ChsBuffer
b5c7ca4c1a Refactor NFController SetServer 2020-12-22 16:59:32 +08:00
ChsBuffer
7c318a9e49 Remove hardcoded TLS1.3 2020-12-21 11:49:08 +08:00
ChsBuffer
f9724f77c2 Fix mode 1,2 did not ignore BypassChina 2020-12-20 17:34:45 +08:00
ChsBuffer
5d8bbe3518 Bump version to 1.6.8 2020-12-20 16:26:08 +08:00
ChsBuffer
e9f0a5b2f8 Update modes 2020-12-20 16:24:27 +08:00
ChsBuffer
9d086336ea Refactor Mode Load 2020-12-19 18:31:25 +08:00
ChsBuffer
b31bedbc82 Update .editorconfig 2020-12-18 19:33:57 +08:00
ChsBuffer
7f15042c03 Update UpdateChecker 2020-12-18 19:33:57 +08:00
Connection Refused
2c4728f13c Merge pull request #464 from AceDroidX/master
Add NoProxyForUdp
2020-12-18 18:54:34 +08:00
AceDroidX
a2f5c9ab27 Add NoProxyForUdp 2020-12-18 18:14:47 +08:00
ChsBuffer
583bf31c92 Fix #462 2020-12-17 12:39:40 +08:00
ChsBuffer
0275b7718f Update binaries 2020-12-16 23:03:03 +08:00
ChsBuffer
0a226fab22 Fix PictureBox High-DPI scale 2020-12-16 16:57:41 +08:00
ChsBuffer
77680e2c02 Fix attach console 2020-12-16 16:27:40 +08:00
ChsBuffer
2afc5ff21a remove connectionReuse 2020-12-16 12:01:16 +08:00
ChsBuffer
4f4882d7f7 update MainController.StartMode 2020-12-16 11:58:12 +08:00
ChsBuffer
41fdf94a16 remove connectionReuse 2020-12-16 10:50:05 +08:00
ChsBuffer
a3e8826105 feat: Add Redirector SS Setting 2020-12-16 10:25:57 +08:00
ChsBuffer
b7bcb46c78 refactor: NTTController, save NTT log to logging\NTT.log 2020-12-15 21:32:16 +08:00
ChsBuffer
5e27b6a1eb refactor: Remove TUNTAPController savedMode savedServer 2020-12-15 21:08:22 +08:00
ChsBuffer
a5903f5f57 Remove IServerController.Server 2020-12-15 21:07:09 +08:00
ChsBuffer
39eb1b4eef refactor: mode handle supported server 2020-12-15 18:23:40 +08:00
ChsBuffer
23bcac0d5d fix: Shadowsocks.HasPlugin typo 2020-12-15 18:23:19 +08:00
ChsBuffer
38480776f0 Revert "update LangVersion to 9"
This reverts commit e77a40966c.
2020-12-15 17:58:39 +08:00
ChsBuffer
bcccb80ece feat: Redirector Shadowsocks (no plugin) support 2020-12-15 17:31:21 +08:00
ChsBuffer
513d0b01a7 refactor: mode match 2020-12-15 17:12:15 +08:00
ChsBuffer
a3d309113c fix: force using ss-libev if using plugin 2020-12-15 17:11:25 +08:00
ChsBuffer
e77a40966c update LangVersion to 9 2020-12-15 17:05:40 +08:00
ChsBuffer
670cb06e4a fix: auto change server type to ss 2020-12-15 16:29:44 +08:00
AmazingDM
59b4ba578b Update UA 2020-12-09 12:00:51 +08:00
ChsBuffer
5ed25de9ee fix: hardcode tls SecurityProtocol tls1.2 and tls 1.3 2020-12-07 17:50:08 +08:00
ChsBuffer
464abef28a Deprecated: VMess.TLSSecure 2020-12-04 00:02:28 +08:00
ChsBuffer
79a7273af2 feat: Proess Mode Start and Edit Rule check 2020-11-30 17:45:00 +08:00
Connection Refused
7d44821e57 Update README.zh-CN.md 2020-11-30 03:20:29 +08:00
Connection Refused
ca3502a284 Update README.md 2020-11-30 03:19:57 +08:00
Connection Refused
415fc5fa8f Update README.md 2020-11-30 03:19:17 +08:00
ChsBuffer
cfd458ffbd feat: keep server remark empty 2020-11-29 17:49:42 +08:00
ChsBuffer
3be5f10ed8 feat: ProcessMode Bypass Rule keyword 2020-11-29 17:25:47 +08:00
ChsBuffer
41479275da feat: DNS port check before start AioDNS 2020-11-29 17:25:06 +08:00
ChsBuffer
639fcf9575 fix: let SettingForm skip saving DNS value when UseCustomDNS is not enabled 2020-11-29 16:10:23 +08:00
AmazingDM
1eebb61d04 bump version to 1.6.7 2020-11-24 17:52:48 +08:00
AmazingDM
a2a66675c2 Update v2ray 4.33.0 2020-11-24 17:50:04 +08:00
ChsBuffer
850393ab71 refactor: TestFakeDNS 2020-11-15 00:38:29 +08:00
ChsBuffer
ea0dd3cd4a fix: Test project 2020-11-14 23:19:21 +08:00
ChsBuffer
c2afc1b014 fix: load config check if Server node is null 2020-11-14 19:52:44 +08:00
Bruce Wayne
7b9d9a6d57 Update CI 2020-11-14 16:51:18 +08:00
Bruce Wayne
860482402a More accurate TCPing 2020-11-14 16:51:13 +08:00
Bruce Wayne
a58f7c7b98 Use Safehandle job api
No handle leak
2020-11-14 16:51:08 +08:00
Bruce Wayne
6afc5e5e4d Update Nuget packages 2020-11-14 16:08:49 +08:00
ChsBuffer
98a5e91dd2 fix: Visual Studio warn solution contains incorrect configurations mappings 2020-11-11 23:27:27 +08:00
ChsBuffer
9581a41007 refactor: SettingForm AutoScaleMode,Disable Maximize SettingForm 2020-11-11 23:24:51 +08:00
ChsBuffer
d85b478868 doc: update bug report issue template 2020-11-10 23:44:08 +08:00
ChsBuffer
628dd6963a refactor: upgrade NetchLib.csproj to new format 2020-11-10 23:26:05 +08:00
ChsBuffer
5ae6f73062 fix: Netch GSF V2Ray TLSSecure 2020-11-05 23:59:39 +08:00
ChsBuffer
50b07ebabb refactor: GenerateClientConfig 2020-11-05 23:12:45 +08:00
ChsBuffer
21f2f8da5e refactor: extract Netch.Utils.Subscription 2020-11-05 16:13:30 +08:00
ChsBuffer
cfc070b1ef fix: clear DNS Cache wont clean system dns cache 2020-11-05 15:41:05 +08:00
ChsBuffer
a4f024df69 refactor: clean temp config file when exit 2020-11-05 15:04:54 +08:00
ChsBuffer
6754268714 feat: setting saving ignore null value 2020-11-05 14:31:45 +08:00
ChsBuffer
642cd57b71 fix: V2ray ServerForm Use Mux value 2020-11-05 14:31:37 +08:00
ChsBuffer
39ea679298 fix: VMess GetShareLink 2020-11-04 21:52:40 +08:00
ChsBuffer
1091486877 feat: #431 2020-11-04 21:50:18 +08:00
ChsBuffer
d805a4fccd bump version to 1.6.6 2020-10-31 22:18:40 +08:00
ChsBuffer
902f78b563 fix: SSDLL flag
fix: let Trojan don't use AutoresolveHostname setting
2020-10-29 16:30:21 +08:00
ChsBuffer
159fbdd58d feat: ServerForm set the color of the control to red If the value is wrong 2020-10-29 14:56:26 +08:00
ChsBuffer
0c5464f833 refactor: extract RegisterNetchStartupItem() method 2020-10-29 14:47:45 +08:00
ChsBuffer
b019362f5f refactor: Check STUN Server setting 2020-10-29 14:46:39 +08:00
ChsBuffer
241371c6f7 feat: SettingForm set the color of the control to red If the value is wrong 2020-10-29 14:14:50 +08:00
ChsBuffer
9b3f5f456f refactor: Bandwidth.NetTraffic 2020-10-29 13:44:30 +08:00
ChsBuffer
c04b8f6ffd refactor: Check NF driver version 2020-10-29 13:27:33 +08:00
ChsBuffer
9d6b6d15d7 refactor: set StatusPortInfoText.ShareLan 2020-10-29 12:07:12 +08:00
ChsBuffer
39081c0a6f refactor: StatusPortInfoText.Value 2020-10-28 01:43:33 +08:00
ChsBuffer
812fab6322 fix: ModifiedDNS Setting init Enabled state 2020-10-27 18:42:41 +08:00
ChsBuffer
bfadb181c4 fix: SettingForm TUNTAPDNS value init
fix: show starting tun2socks after setup route table
fix: a typo
2020-10-27 12:14:10 +08:00
ChsBuffer
52ac05ee17 feat: add ChildProcessTracker 2020-10-26 17:36:50 +08:00
ChsBuffer
c774122fdb fix: Disable update ACL after startup 2020-10-26 16:58:45 +08:00
ChsBuffer
8e223faa71 fix: v2ray will proxy multicast address causing loop 2020-10-25 21:35:07 +08:00
ChsBuffer
7b0f0f35cc fix: SettingForm load RedriectorTCP value wrong
fix: Start Profile ModeComboBox.Text and ProfileNameText.Text wrong
2020-10-25 21:01:21 +08:00
ChsBuffer
89ce721d4c fix: language setting not saved 2020-10-25 00:24:40 +08:00
81 changed files with 3847 additions and 3074 deletions

View File

@@ -1,9 +1,60 @@
root = true
# http://editorconfig.org/
# top-most EditorConfig file
root = true
# all files
[*]
indent_style = space
indent_size = 4
indent_size = 4
tab_width = 4
# Microsoft .NET properties
csharp_new_line_before_members_in_object_initializers = false
csharp_preferred_modifier_order = public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion
csharp_style_var_elsewhere = true:suggestion
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
dotnet_style_qualification_for_event = false:suggestion
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion
# ReSharper properties
resharper_blank_lines_after_block_statements = 0
resharper_csharp_blank_lines_around_field = 0
resharper_csharp_blank_lines_around_invocable = 0
resharper_csharp_blank_lines_around_type = 0
resharper_csharp_int_align_comments = true
resharper_csharp_keep_blank_lines_in_declarations = 1
resharper_csharp_max_line_length = 368
resharper_csharp_wrap_lines = false
resharper_place_expr_accessor_on_single_line = true
resharper_place_expr_method_on_single_line = true
resharper_place_field_attribute_on_same_line = false
resharper_place_simple_embedded_statement_on_same_line = false
resharper_place_simple_initializer_on_single_line = false
resharper_use_indent_from_vs = false
resharper_wrap_array_initializer_style = chop_if_long
resharper_wrap_object_and_collection_initializer_style = chop_always
# ReSharper inspection severities
resharper_arrange_redundant_parentheses_highlighting = hint
resharper_arrange_this_qualifier_highlighting = hint
resharper_arrange_type_member_modifiers_highlighting = hint
resharper_arrange_type_modifiers_highlighting = hint
resharper_built_in_type_reference_style_for_member_access_highlighting = hint
resharper_built_in_type_reference_style_highlighting = hint
resharper_redundant_base_qualifier_highlighting = warning
resharper_suggest_var_or_type_built_in_types_highlighting = hint
resharper_suggest_var_or_type_elsewhere_highlighting = hint
resharper_suggest_var_or_type_simple_types_highlighting = hint
resharper_web_config_module_not_resolved_highlighting = warning
resharper_web_config_type_not_resolved_highlighting = warning
resharper_web_config_wrong_module_highlighting = warning

View File

@@ -2,15 +2,13 @@
name: 'Bug report'
about: 'Create a report to help us improve'
title: ''
labels: 'Status: Review Needed'
labels: '需要核实'
assignees: ''
---
**Make sure you have read the readme, searched and read the issues related to yours. Otherwise it will be considered as a duplicate which will be closed immediately.**
**All issues about `bin/Redirector.exe` should be discussed at [issue #152](https://github.com/NetchX/Netch/issues/152).**
**Describe the bug**
A clear and concise description of what the bug is.

View File

@@ -2,15 +2,13 @@
name: '错误报告'
about: '创建错误报告以帮助我们改进'
title: ''
labels: 'Status: Review Needed'
labels: '需要核实'
assignees: ''
---
**确保你已经看过 readme也搜索并阅读过和你遇到的情况相关的问题。否则会被认为是重复的并被立刻关闭。**
**所有关于 `bin/Redirector.exe` 的问题,请在 [issue #152](https://github.com/NetchX/Netch/issues/152) 中讨论**
**错误描述**
对错误的清晰简洁描述

View File

@@ -14,26 +14,32 @@ jobs:
submodules: true
- name: Build Solution
shell: pwsh
run: .\BUILD.ps1
- name: Upload Artifact
continue-on-error: true
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
uses: actions/upload-artifact@v2
with:
name: Netch
path: Netch\bin\x64\Release
- name: Package
if: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') }}
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\
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
- name: Release
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
if: startsWith(github.ref, 'refs/tags/')
if: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') }}
with:
name: ${{ env.GITHUB_TAG_NAME }}
prerelease: true
@@ -49,23 +55,4 @@ jobs:
## 校验和
| 文件名 | SHA256 |
| :- | :- |
| Netch.7z | ${{ env.Netch_SHA256 }} |
# Deploy:
# needs: [build]
# runs-on: ubuntu-latest
# steps:
# - name: Download Artifacts
# uses: actions/download-artifact@v1
# with:
# name: Netch
# - name: Pushes to another repository
# uses: peaceiris/actions-gh-pages@v3
# with:
# personal_token: ${{ secrets.ACCESS_TOKEN }}
# publish_branch: repo
# publish_dir: ./Netch
# external_repository: ${{ github.repository_owner }}/NetchReleases
# user_name: 'github-actions[bot]'
# user_email: 'github-actions[bot]@users.noreply.github.com'
| Netch.7z | ${{ env.Netch_SHA256 }} |

View File

@@ -5,11 +5,11 @@ VisualStudioVersion = 16.0.29009.5
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Netch", "Netch\Netch.csproj", "{4B041B91-5790-4571-8C58-C63FFE4BC9F8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetchLib", "NetchLib\NetchLib.csproj", "{A8715AF4-ACC6-43F9-9381-4294C5360623}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetchLib", "NetchLib\NetchLib.csproj", "{A8715AF4-ACC6-43F9-9381-4294C5360623}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetchUpdater", "NetchUpdater\NetchUpdater.csproj", "{828318A8-9B90-4A5F-BD6B-E632CC9D8933}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "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}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test", "Test\Test.csproj", "{53397641-35CA-4336-8E22-2CE12EF476AC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -29,10 +29,9 @@ 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
{53397641-35CA-4336-8E22-2CE12EF476AC}.Debug|x64.ActiveCfg = Debug|x64
{53397641-35CA-4336-8E22-2CE12EF476AC}.Debug|x64.Build.0 = Debug|x64
{53397641-35CA-4336-8E22-2CE12EF476AC}.Release|x64.ActiveCfg = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -6,7 +6,6 @@ namespace Netch.Controllers
{
public class DNSController : IController
{
public string Name { get; } = "DNS Service";
/// <summary>
@@ -15,13 +14,14 @@ namespace Netch.Controllers
/// <returns></returns>
public bool Start()
{
if (!aiodns_dial(Encoding.UTF8.GetBytes(Path.GetFullPath(Global.Settings.AioDNS.RulePath)),
Encoding.UTF8.GetBytes($"{Global.Settings.AioDNS.ChinaDNS}:53"),
Encoding.UTF8.GetBytes($"{Global.Settings.AioDNS.OtherDNS}:53"))
)
return false;
return
aiodns_init();
aiodns_dial((int) NameList.TYPE_REST, null);
aiodns_dial((int) NameList.TYPE_ADDR, Encoding.UTF8.GetBytes($"{Global.Settings.LocalAddress}:53"));
aiodns_dial((int) NameList.TYPE_LIST, Encoding.UTF8.GetBytes(Path.GetFullPath(Global.Settings.AioDNS.RulePath)));
aiodns_dial((int) NameList.TYPE_CDNS, Encoding.UTF8.GetBytes($"{Global.Settings.AioDNS.ChinaDNS}:53"));
aiodns_dial((int) NameList.TYPE_ODNS, Encoding.UTF8.GetBytes($"{Global.Settings.AioDNS.OtherDNS}:53"));
aiodns_dial((int) NameList.TYPE_METH, Encoding.UTF8.GetBytes(Global.Settings.AioDNS.Protocol));
return aiodns_init();
}
public void Stop()
@@ -32,7 +32,7 @@ namespace Netch.Controllers
#region NativeMethods
[DllImport("aiodns.bin", CallingConvention = CallingConvention.Cdecl)]
public static extern bool aiodns_dial(byte[] chinacon, byte[] chinadns, byte[] otherdns);
public static extern bool aiodns_dial(int name, byte[] value);
[DllImport("aiodns.bin", CallingConvention = CallingConvention.Cdecl)]
public static extern bool aiodns_init();
@@ -40,6 +40,16 @@ namespace Netch.Controllers
[DllImport("aiodns.bin", CallingConvention = CallingConvention.Cdecl)]
public static extern void aiodns_free();
enum NameList : int
{
TYPE_REST,
TYPE_ADDR,
TYPE_LIST,
TYPE_CDNS,
TYPE_ODNS,
TYPE_METH
}
#endregion
}
}

View File

@@ -56,7 +56,7 @@ namespace Netch.Controllers
/// 程序输出的编码,
/// 调用于基类的 <see cref="OnOutputDataReceived"/>
/// </summary>
protected string InstanceOutputEncoding { get; set; } = "gbk";
protected Encoding InstanceOutputEncoding { get; set; } = Encoding.GetEncoding("gbk");
/// <summary>
/// 停止进程
@@ -93,10 +93,11 @@ namespace Netch.Controllers
WorkingDirectory = $"{Global.NetchDir}\\bin",
Arguments = argument,
CreateNoWindow = true,
RedirectStandardError = RedirectStd,
RedirectStandardInput = RedirectStd,
RedirectStandardOutput = RedirectStd,
UseShellExecute = !RedirectStd,
RedirectStandardOutput = RedirectStd,
StandardOutputEncoding = RedirectStd ? InstanceOutputEncoding : null,
RedirectStandardError = RedirectStd,
StandardErrorEncoding = RedirectStd ? InstanceOutputEncoding : null,
WindowStyle = ProcessWindowStyle.Hidden
}
};
@@ -192,15 +193,13 @@ namespace Netch.Controllers
if (e.Data == null)
return;
var info = Encoding.GetEncoding(InstanceOutputEncoding).GetBytes(e.Data);
var str = Encoding.UTF8.GetString(info);
Write(str);
Write(e.Data);
// 检查启动
if (State == State.Starting)
{
if (StartedKeywords.Any(s => str.Contains(s)))
if (StartedKeywords.Any(s => e.Data.Contains(s)))
State = State.Started;
else if (StoppedKeywords.Any(s => str.Contains(s)))
else if (StoppedKeywords.Any(s => e.Data.Contains(s)))
State = State.Stopped;
}
}

View File

@@ -1,11 +1,15 @@
using System;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsProxy;
using Microsoft.Win32;
using Netch.Forms;
using Netch.Models;
using Netch.Servers.Socks5;
using Netch.Servers.Trojan;
using Netch.Utils;
using Netch.Utils.HttpProxyHandler;
namespace Netch.Controllers
{
@@ -13,7 +17,7 @@ namespace Netch.Controllers
{
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.*";
public PrivoxyController pPrivoxyController = new PrivoxyController();
public PrivoxyController pPrivoxyController = new();
private string prevBypass, prevHTTP, prevPAC;
private bool prevEnabled;
@@ -31,9 +35,26 @@ namespace Netch.Controllers
try
{
pPrivoxyController.Start(MainController.ServerController.Server, mode);
if (pPrivoxyController.Start(MainController.Server, mode))
Global.Job.AddProcess(pPrivoxyController.Instance);
if (mode.Type == 3) NativeMethods.SetGlobal($"127.0.0.1:{Global.Settings.HTTPLocalPort}", IEProxyExceptions);
if (mode.Type == 3)
{
if (MainController.Server is Socks5 or Trojan && mode.BypassChina)
{
//启动PAC服务器
PACServerHandle.InitPACServer("127.0.0.1");
}
else
{
using var service = new ProxyService
{
Server = $"127.0.0.1:{Global.Settings.HTTPLocalPort}",
Bypass = IEProxyExceptions
};
service.Global();
}
}
}
catch (Exception e)
{
@@ -46,6 +67,48 @@ namespace Netch.Controllers
return true;
}
/// <summary>
/// 停止
/// </summary>
public void Stop()
{
var tasks = new[]
{
Task.Run(pPrivoxyController.Stop),
Task.Run(() =>
{
using var service = new ProxyService();
try
{
PACServerHandle.Stop();
if (prevEnabled)
{
if (prevHTTP != "")
{
service.Server = prevHTTP;
service.Bypass = prevBypass;
service.Global();
}
if (prevPAC != "")
{
service.AutoConfigUrl = prevPAC;
service.Pac();
}
}
else
{
service.Direct();
}
}
catch (Exception e)
{
Logging.Error($"{Name} 控制器出错:\n" + e);
}
})
};
Task.WaitAll(tasks);
}
private void RecordPrevious()
{
try
@@ -74,29 +137,5 @@ namespace Netch.Controllers
prevPAC = prevHTTP = prevBypass = "";
}
}
/// <summary>
/// 停止
/// </summary>
public void Stop()
{
var tasks = new[]
{
Task.Factory.StartNew(pPrivoxyController.Stop),
Task.Factory.StartNew(() =>
{
if (prevEnabled)
{
if (prevHTTP != "")
NativeMethods.SetGlobal(prevHTTP, prevBypass);
if (prevPAC != "")
NativeMethods.SetURL(prevPAC);
}
else
NativeMethods.SetDIRECT();
})
};
Task.WaitAll(tasks);
}
}
}

View File

@@ -4,8 +4,6 @@ namespace Netch.Controllers
{
public interface IServerController : IController
{
public Server Server { get; set; }
public ushort? Socks5LocalPort { get; set; }
public string LocalAddress { get; set; }

View File

@@ -1,7 +1,9 @@
using System;
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Netch.Forms;
using Netch.Models;
using Netch.Servers.Socks5;
using Netch.Utils;
@@ -12,19 +14,37 @@ namespace Netch.Controllers
{
public static class MainController
{
public static Mode Mode;
/// TCP or Both Server
public static Server Server;
private static Server _udpServer;
public static readonly NTTController NTTController = new();
private static IServerController _serverController;
private static IServerController _udpServerController;
public static IServerController ServerController
{
get => _serverController;
private set => _serverController = value;
}
public static IServerController UdpServerController
{
get => _udpServerController ?? _serverController;
set => _udpServerController = value;
}
public static Server UdpServer
{
get => _udpServer ?? Server;
set => _udpServer = value;
}
public static IModeController ModeController { get; private set; }
public static bool NttTested;
private static readonly NTTController NTTController = new NTTController();
private static IServerController _serverController;
/// <summary>
/// 启动
/// </summary>
@@ -34,11 +54,11 @@ namespace Netch.Controllers
public static async Task<bool> Start(Server server, Mode mode)
{
Logging.Info($"启动主控制器: {server.Type} [{mode.Type}]{mode.Remark}");
Server = server;
Mode = mode;
if (server is Socks5 && mode.Type == 4)
{
return false;
}
// 刷新DNS缓存
NativeMethods.FlushDNSResolverCache();
@@ -64,18 +84,16 @@ namespace Netch.Controllers
try
{
if (!await Task.Run(() => StartServer(server, mode, ref _serverController)))
if (!ModeHelper.SkipServerController(server, mode))
{
throw new StartFailedException();
if (!await Task.Run(() => StartServer(server, mode, ref _serverController)))
throw new StartFailedException();
StatusPortInfoText.UpdateShareLan();
}
if (!await StartMode(server, mode))
{
if (!await StartMode(mode))
throw new StartFailedException();
}
if (mode.TestNatRequired)
NatTest();
return true;
}
@@ -88,7 +106,6 @@ namespace Netch.Controllers
MessageBoxX.Show(e.Message + "\n\n" + i18N.Translate("Missing File or runtime components"), owner: Global.MainForm);
break;
case StartFailedException _:
case PortInUseException _:
break;
default:
Logging.Error($"主控制器未处理异常: {e}");
@@ -113,17 +130,31 @@ namespace Netch.Controllers
controller = ServerHelper.GetUtilByTypeName(server.Type).GetController();
if (controller is Guard instanceController)
{
Utils.Utils.KillProcessByName(instanceController.MainFile);
}
PortCheckAndShowMessageBox(controller.Socks5LocalPort(), "Socks5");
if (!PortCheckAndShowMessageBox(controller.Socks5LocalPort(), "Socks5"))
return false;
Global.MainForm.StatusText(i18N.TranslateFormat("Starting {0}", controller.Name));
if (controller.Start(in server, mode))
{
UsingPorts.Add(StatusPortInfoText.Socks5Port = controller.Socks5LocalPort());
StatusPortInfoText.ShareLan = controller.LocalAddress == "0.0.0.0";
if (controller is Guard guard)
if (guard.Instance != null)
Task.Run(() =>
{
Thread.Sleep(1000);
Global.Job.AddProcess(guard.Instance);
});
if (server is Socks5 socks5)
{
if (socks5.Auth())
StatusPortInfoText.Socks5Port = controller.Socks5LocalPort();
}
else
{
StatusPortInfoText.Socks5Port = controller.Socks5LocalPort();
}
return true;
}
@@ -131,22 +162,28 @@ namespace Netch.Controllers
return false;
}
private static async Task<bool> StartMode(Server server, Mode mode)
private static async Task<bool> StartMode(Mode mode)
{
ModeController = ModeHelper.GetModeControllerByType(mode.Type, out var port, out var portName, out var portType);
if (ModeController == null)
return true;
if (port != null)
if (!PortCheckAndShowMessageBox((ushort) port, portName, portType))
return false;
Global.MainForm.StatusText(i18N.TranslateFormat("Starting {0}", ModeController.Name));
if (await Task.Run(() => ModeController.Start(mode)))
{
PortCheckAndShowMessageBox((ushort) port, portName, portType);
UsingPorts.Add((ushort) port);
if (ModeController is Guard guard)
if (guard.Instance != null)
Global.Job.AddProcess(guard.Instance);
return true;
}
if (ModeController != null)
{
Global.MainForm.StatusText(i18N.TranslateFormat("Starting {0}", ModeController.Name));
return await Task.Run(() => ModeController.Start(mode));
}
return true;
return false;
}
/// <summary>
@@ -154,7 +191,6 @@ namespace Netch.Controllers
/// </summary>
public static async Task Stop()
{
UsingPorts.Clear();
StatusPortInfoText.Reset();
_ = Task.Run(() => NTTController.Stop());
@@ -162,53 +198,34 @@ namespace Netch.Controllers
var tasks = new[]
{
Task.Run(() => ServerController?.Stop()),
Task.Run(() => ModeController?.Stop()),
Task.Run(() => ModeController?.Stop())
};
await Task.WhenAll(tasks);
ModeController = null;
ServerController = null;
}
/// <summary>
/// 检查端口是否被占用,
/// 检查端口是否被占用,
/// 被占用则弹窗提示, 确认后抛出异常
/// </summary>
/// <param name="port">检查的端口</param>
/// <param name="portName">端口用途名称</param>
/// <param name="portType"></param>
/// <exception cref="PortInUseException"></exception>
private static void PortCheckAndShowMessageBox(ushort port, string portName, PortType portType = PortType.Both)
public static bool PortCheckAndShowMessageBox(ushort port, string portName, PortType portType = PortType.Both)
{
if (PortInUse(port, portType))
try
{
CheckPort(port, portType);
return true;
}
catch (PortInUseException)
{
MessageBoxX.Show(i18N.TranslateFormat("The {0} port is in use.", $"{portName} ({port})"));
throw new PortInUseException();
return false;
}
}
/// <summary>
/// 测试 NAT
/// </summary>
public static void NatTest()
{
NttTested = false;
Task.Run(() =>
catch (PortReservedException)
{
Global.MainForm.NatTypeStatusText(i18N.Translate("Starting NatTester"));
// Thread.Sleep(1000);
var (result, localEnd, publicEnd) = NTTController.Start();
if (!string.IsNullOrEmpty(publicEnd))
{
var country = Utils.Utils.GetCityCode(publicEnd);
Global.MainForm.NatTypeStatusText(result, country);
}
else
Global.MainForm.NatTypeStatusText(result ?? "Error");
NttTested = true;
});
MessageBoxX.Show(i18N.TranslateFormat("The {0} port is reserved by system.", $"{portName} ({port})"));
return false;
}
}
}

View File

@@ -7,6 +7,7 @@ using System.ServiceProcess;
using System.Threading.Tasks;
using Netch.Forms;
using Netch.Models;
using Netch.Servers.Shadowsocks;
using Netch.Servers.Socks5;
using Netch.Utils;
using nfapinet;
@@ -15,14 +16,12 @@ namespace Netch.Controllers
{
public class NFController : IModeController
{
private static readonly ServiceController NFService = new ServiceController("netfilter2");
private static readonly ServiceController NFService = new("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;
@@ -47,35 +46,54 @@ namespace Netch.Controllers
BinDriver = "bin\\" + fileName;
}
public string Name { get; } = "Redirector";
public bool Start(in Mode mode)
{
var binFileVersion = Utils.Utils.GetFileVersion(BinDriver);
var systemFileVersion = Utils.Utils.GetFileVersion(SystemDriver);
if (!CheckDriver())
return false;
Logging.Info("内置驱动版本: " + binFileVersion);
Logging.Info("系统驱动版本: " + systemFileVersion);
if (!systemFileVersion.Equals(binFileVersion))
{
if (File.Exists(SystemDriver))
{
Logging.Info("更新驱动");
UninstallDriver();
}
if (!InstallDriver())
return false;
}
#region aio_dial
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());
SetServer(MainController.ServerController, PortType.Both);
if (Global.Settings.ProcessNoProxyForUdp && Global.Settings.ProcessNoProxyForTcp) MessageBoxX.Show("");
//UDP
if (Global.Settings.ProcessNoProxyForUdp)
{
aio_dial((int) NameList.TYPE_FILTERUDP, "false");
SetServer(PortType.TCP);
}
else
{
aio_dial((int) NameList.TYPE_FILTERUDP, "true");
SetServer(PortType.Both);
}
//TCP
if (Global.Settings.ProcessNoProxyForTcp)
{
aio_dial((int) NameList.TYPE_FILTERTCP, "false");
SetServer(PortType.UDP);
}
else
{
aio_dial((int) NameList.TYPE_FILTERTCP, "true");
SetServer(PortType.Both);
}
if (!CheckRule(mode.FullRule, out var list))
{
MessageBoxX.Show($"\"{string.Join("", list.Select(s => s + "\n"))}\" does not conform to C++ regular expression syntax");
return false;
}
SetName(mode);
#endregion
if (Global.Settings.ModifySystemDNS)
{
// 备份并替换系统 DNS
@@ -88,46 +106,6 @@ namespace Netch.Controllers
return aio_init();
}
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(() =>
@@ -140,27 +118,181 @@ namespace Netch.Controllers
aio_free();
}
/// <summary>
/// </summary>
/// <param name="rules"></param>
/// <param name="incompatibleRule"></param>
/// <returns>No Problem true</returns>
public static bool CheckRule(IEnumerable<string> rules, out IEnumerable<string> incompatibleRule)
{
incompatibleRule = rules.Where(r => !CheckCppRegex(r, false));
aio_dial((int) NameList.TYPE_CLRNAME, "");
return !incompatibleRule.Any();
}
/// <summary>
/// </summary>
/// <param name="r"></param>
/// <param name="clear"></param>
/// <returns>No Problem true</returns>
public static bool CheckCppRegex(string r, bool clear = true)
{
try
{
if (r.StartsWith("!"))
return aio_dial((int) NameList.TYPE_ADDNAME, r.Substring(1));
return aio_dial((int) NameList.TYPE_ADDNAME, r);
}
finally
{
if (clear)
aio_dial((int) NameList.TYPE_CLRNAME, "");
}
}
private static bool CheckDriver()
{
var binFileVersion = Utils.Utils.GetFileVersion(BinDriver);
var systemFileVersion = Utils.Utils.GetFileVersion(SystemDriver);
Logging.Info("内置驱动版本: " + binFileVersion);
Logging.Info("系统驱动版本: " + systemFileVersion);
if (!File.Exists(BinDriver))
{
Logging.Warning("内置驱动不存在");
if (File.Exists(SystemDriver))
{
Logging.Warning("使用系统驱动");
return true;
}
Logging.Error("未安装驱动");
return false;
}
if (!File.Exists(SystemDriver))
return InstallDriver();
var updateFlag = false;
if (Version.TryParse(binFileVersion, out var binResult) && Version.TryParse(systemFileVersion, out var systemResult))
{
if (binResult.CompareTo(systemResult) > 0)
{
// Bin greater than Installed
updateFlag = true;
}
else
{
// Installed greater than Bin
if (systemResult.Major != binResult.Major)
// API breaking changes
updateFlag = true;
}
}
else
{
if (!systemFileVersion.Equals(binFileVersion))
updateFlag = true;
}
if (!updateFlag) return true;
Logging.Info("更新驱动");
UninstallDriver();
return InstallDriver();
}
private void SetServer(in PortType portType)
{
if (portType == PortType.Both)
{
SetServer(PortType.TCP);
SetServer(PortType.UDP);
return;
}
int offset;
Server server;
IServerController controller;
if (portType == PortType.UDP)
{
offset = UdpNameListOffset;
server = MainController.UdpServer;
controller = MainController.UdpServerController;
}
else
{
offset = 0;
server = MainController.Server;
controller = MainController.ServerController;
}
if (server is Socks5 socks5)
{
aio_dial((int) NameList.TYPE_TCPTYPE + offset, "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);
aio_dial((int) NameList.TYPE_TCPMETH + offset, string.Empty);
}
else if (server is Shadowsocks shadowsocks && !shadowsocks.HasPlugin() && Global.Settings.RedirectorSS)
{
aio_dial((int) NameList.TYPE_TCPTYPE + offset, "Shadowsocks");
aio_dial((int) NameList.TYPE_TCPHOST + offset, $"{shadowsocks.AutoResolveHostname()}:{shadowsocks.Port}");
aio_dial((int) NameList.TYPE_TCPMETH + offset, shadowsocks.EncryptMethod ?? string.Empty);
aio_dial((int) NameList.TYPE_TCPPASS + offset, shadowsocks.Password ?? string.Empty);
}
else
{
aio_dial((int) NameList.TYPE_TCPTYPE + offset, "Socks5");
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)
{
if (rule.StartsWith("!"))
{
aio_dial((int) NameList.TYPE_BYPNAME, rule.Substring(1));
continue;
}
aio_dial((int) NameList.TYPE_ADDNAME, rule);
}
aio_dial((int) NameList.TYPE_ADDNAME, @"NTT\.exe");
}
#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);
private static extern bool aio_dial(int name, [MarshalAs(UnmanagedType.LPWStr)] string value);
[DllImport("Redirector.bin", CallingConvention = CallingConvention.Cdecl)]
public static extern bool aio_init();
private static extern bool aio_init();
[DllImport("Redirector.bin", CallingConvention = CallingConvention.Cdecl)]
public static extern bool aio_free();
private static extern bool aio_free();
[DllImport("Redirector.bin", CallingConvention = CallingConvention.Cdecl)]
public static extern ulong aio_getUP();
private static extern ulong aio_getUP();
[DllImport("Redirector.bin", CallingConvention = CallingConvention.Cdecl)]
public static extern ulong aio_getDL();
private static extern ulong aio_getDL();
public enum NameList : int
public enum NameList
{
TYPE_FILTERLOOPBACK,
TYPE_FILTERTCP,
@@ -224,7 +356,6 @@ namespace Netch.Controllers
/// <returns>是否成功卸载</returns>
public static bool UninstallDriver()
{
Global.MainForm.StatusText(i18N.TranslateFormat("Uninstalling {0}", "NF Service"));
Logging.Info("卸载 NF 驱动");
try
{

View File

@@ -1,5 +1,5 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Netch.Utils;
@@ -7,10 +7,6 @@ namespace Netch.Controllers
{
public class NTTController : Guard, IController
{
private string _localEnd;
private string _publicEnd;
private string _result;
private string _bindingTest;
public override string Name { get; protected set; } = "NTT";
public override string MainFile { get; protected set; } = "NTT.exe";
@@ -20,7 +16,10 @@ namespace Netch.Controllers
/// <returns></returns>
public (string, string, string) Start()
{
_result = _localEnd = _publicEnd = null;
string localEnd=null;
string publicEnd=null;
string result =null;
string bindingTest=null;
try
{
@@ -28,12 +27,50 @@ namespace Netch.Controllers
Instance.OutputDataReceived += OnOutputDataReceived;
Instance.ErrorDataReceived += OnOutputDataReceived;
Instance.Start();
Instance.BeginOutputReadLine();
Instance.BeginErrorReadLine();
Instance.WaitForExit();
if (_bindingTest == "Fail")
_result = "UdpBlocked";
return (_result, _localEnd, _publicEnd);
var output = Instance.StandardOutput.ReadToEnd();
try
{
File.WriteAllText(Path.Combine(Global.NetchDir, $"logging\\{Name}.log"), output);
}
catch (Exception e)
{
Logging.Warning($"写入 {Name} 日志错误:\n" + e.Message);
}
foreach (var line in output.Split('\n'))
{
var str = line.Split(':').Select(s => s.Trim()).ToArray();
if (str.Length < 2)
continue;
var key = str[0];
var value = str[1];
switch (key)
{
case "Other address is":
case "Nat mapping behavior":
case "Nat filtering behavior":
break;
case "Binding test":
bindingTest = value;
break;
case "Local address":
localEnd = value;
break;
case "Mapped address":
publicEnd = value;
break;
case "result":
result = value;
break;
default:
result = str.Last();
break;
}
}
if (bindingTest == "Fail")
result = "UdpBlocked";
return (result, localEnd, publicEnd);
}
catch (Exception e)
{
@@ -51,41 +88,6 @@ namespace Netch.Controllers
}
}
private new void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (string.IsNullOrEmpty(e.Data)) return;
Logging.Info($"[NTT] {e.Data}");
var str = e.Data.Split(':').Select(s => s.Trim()).ToArray();
if (str.Length < 2)
return;
var key = str[0];
var value = str[1];
switch (key)
{
case "Other address is":
case "Nat mapping behavior":
case "Nat filtering behavior":
break;
case "Binding test":
_bindingTest = value;
break;
case "Local address":
_localEnd = value;
break;
case "Mapped address":
_publicEnd = value;
break;
case "result":
_result = value;
break;
default:
_result = str.Last();
break;
}
}
public override void Stop()
{
StopInstance();

View File

@@ -1,14 +1,12 @@
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;
@@ -17,9 +15,9 @@ namespace Netch.Controllers
{
public class TUNTAPController : Guard, IModeController
{
private Mode _savedMode = new Mode();
private Server _savedServer = new Server();
private readonly List<string> _directIPs = new();
private readonly List<string> _proxyIPs = new();
/// <summary>
/// 服务器 IP 地址
/// </summary>
@@ -28,30 +26,26 @@ namespace Netch.Controllers
/// <summary>
/// 本地 DNS 服务控制器
/// </summary>
public DNSController DNSController = new DNSController();
public DNSController DNSController = new();
public TUNTAPController()
{
StartedKeywords.Add("Running");
StoppedKeywords.AddRange(new[] {"failed", "invalid vconfig file"});
}
public override string MainFile { get; protected set; } = "tun2socks.exe";
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;
var server = MainController.Server;
// 查询服务器 IP 地址
_serverAddresses = DNS.Lookup(_savedServer.Hostname);
_serverAddresses = DNS.Lookup(server.Hostname);
// 查找出口适配器
if (!Utils.Utils.SearchOutboundAdapter())
{
return false;
}
// 查找并安装 TAP 适配器
if (!SearchTapAdapter())
@@ -66,7 +60,9 @@ namespace Netch.Controllers
}
SetupRouteTable();
SetupRouteTable(mode);
Global.MainForm.StatusText(i18N.TranslateFormat("Starting {0}", Name));
string dns;
if (Global.Settings.TUNTAP.UseCustomDNS)
@@ -83,13 +79,21 @@ namespace Netch.Controllers
}
else
{
var _ = DNSController.Start();
if (!MainController.PortCheckAndShowMessageBox(53, "DNS"))
return false;
if (!DNSController.Start())
{
Logging.Error("AioDNS 启动失败");
return false;
}
dns = "127.0.0.1";
}
var argument = new StringBuilder();
if (_savedServer is Socks5 socks5 && !socks5.Auth())
argument.Append($"-proxyServer {_serverAddresses}:{_savedServer.Port} ");
if (server is Socks5 socks5 && !socks5.Auth())
argument.Append($"-proxyServer {server.AutoResolveHostname()}:{server.Port} ");
else
argument.Append($"-proxyServer 127.0.0.1:{Global.Settings.Socks5LocalPort} ");
@@ -109,88 +113,80 @@ namespace Netch.Controllers
{
var tasks = new[]
{
Task.Factory.StartNew(StopInstance),
Task.Factory.StartNew(ClearRouteTable),
Task.Factory.StartNew(DNSController.Stop)
Task.Run(StopInstance),
Task.Run(ClearRouteTable),
Task.Run(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()
private void SetupRouteTable(Mode mode)
{
Global.MainForm.StatusText(i18N.Translate("SetupBypass"));
Logging.Info("设置路由规则");
#region Rule IPs
if (_savedMode.Type == 1)
switch (mode.Type)
{
// 代理规则
Logging.Info("代理 → 规则 IP");
RouteAction(Action.Create, _savedMode.FullRule, RouteType.TUNTAP);
case 1:
// 代理规则
Logging.Info("代理 → 规则 IP");
RouteAction(Action.Create, mode.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 类型测试域名解析失败,将不会被添加到代理列表");
}
}
//处理 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)
if (Global.Settings.TUNTAP.ProxyDNS)
{
RouteAction(Action.Create,
Global.Settings.TUNTAP.DNS.Select(ip => $"{ip}/32"),
RouteType.TUNTAP);
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
{
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
}
);
break;
case 2:
// 绕过规则
Logging.Info("绕行 → 规则 IP");
RouteAction(Action.Create, _savedMode.FullRule, RouteType.Outbound);
// 将 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, mode.FullRule, RouteType.Outbound);
break;
}
#endregion
@@ -202,7 +198,7 @@ namespace Netch.Controllers
Logging.Info("绕行 → 全局绕过 IP");
RouteAction(Action.Create, Global.Settings.BypassIPs, RouteType.Outbound);
if (_savedMode.Type == 2)
if (mode.Type == 2)
{
// 绕过规则
Logging.Info("代理 → 全局");
@@ -226,33 +222,11 @@ namespace Netch.Controllers
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");
return Instance.StandardError.ReadToEnd().Contains("-fakeDns");
}
catch
{
@@ -313,26 +287,11 @@ namespace Netch.Controllers
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)
@@ -393,11 +352,22 @@ namespace Netch.Controllers
}
if (!result)
{
Logging.Warning($"Failed to {action} Route on {routeType} Adapter: {ipNetwork} metric {metric}");
}
return result;
}
private enum RouteType
{
Outbound,
TUNTAP
}
private enum Action
{
Create,
Delete
}
}
}

View File

@@ -1,13 +1,17 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Netch.Models.GitHubRelease;
using Netch.Utils;
using Newtonsoft.Json;
namespace Netch.Controllers
{
public class UpdateChecker
public static class UpdateChecker
{
public const string Owner = @"NetchX";
public const string Repo = @"Netch";
@@ -15,20 +19,20 @@ namespace Netch.Controllers
public const string Name = @"Netch";
public const string Copyright = @"Copyright © 2019 - 2020";
public const string AssemblyVersion = @"1.6.5";
public const string AssemblyVersion = @"1.7.3";
private const string Suffix = @"";
public static readonly string Version = $"{AssemblyVersion}{(string.IsNullOrEmpty(Suffix) ? "" : $"-{Suffix}")}";
public string LatestVersionNumber;
public string LatestVersionUrl;
public string LatestVersionDownloadUrl;
public static string LatestVersionNumber;
public static string LatestVersionUrl;
public static Release LatestRelease;
public event EventHandler NewVersionFound;
public event EventHandler NewVersionFoundFailed;
public event EventHandler NewVersionNotFound;
public static event EventHandler NewVersionFound;
public static event EventHandler NewVersionFoundFailed;
public static event EventHandler NewVersionNotFound;
public async void Check(bool isPreRelease)
public static async void Check(bool isPreRelease)
{
try
{
@@ -38,20 +42,19 @@ namespace Netch.Controllers
var json = await WebUtil.DownloadStringAsync(WebUtil.CreateRequest(url));
var releases = JsonConvert.DeserializeObject<List<Release>>(json);
var latestRelease = VersionUtil.GetLatestRelease(releases, isPreRelease);
LatestVersionNumber = latestRelease.tag_name;
LatestVersionUrl = latestRelease.html_url;
LatestVersionDownloadUrl = latestRelease.assets[0].browser_download_url;
Logging.Info($"Github 最新发布版本: {latestRelease.tag_name}");
if (VersionUtil.CompareVersion(latestRelease.tag_name, Version) > 0)
LatestRelease = VersionUtil.GetLatestRelease(releases, isPreRelease);
LatestVersionNumber = LatestRelease.tag_name;
LatestVersionUrl = LatestRelease.html_url;
Logging.Info($"Github 最新发布版本: {LatestRelease.tag_name}");
if (VersionUtil.CompareVersion(LatestRelease.tag_name, Version) > 0)
{
Logging.Info("发现新版本");
NewVersionFound?.Invoke(this, new EventArgs());
NewVersionFound?.Invoke(null, new EventArgs());
}
else
{
Logging.Info("目前是最新版本");
NewVersionNotFound?.Invoke(this, new EventArgs());
NewVersionNotFound?.Invoke(null, new EventArgs());
}
}
catch (Exception e)
@@ -59,12 +62,67 @@ namespace Netch.Controllers
if (e is WebException)
Logging.Warning($"获取新版本失败: {e.Message}");
else
{
Logging.Warning(e.ToString());
NewVersionFoundFailed?.Invoke(null, new EventArgs());
}
}
public static async Task UpdateNetch(DownloadProgressChangedEventHandler onDownloadProgressChanged)
{
using WebClient client = new();
var latestVersionDownloadUrl = LatestRelease.assets[0].browser_download_url;
var tagPage = await client.DownloadStringTaskAsync(LatestVersionUrl);
var match = Regex.Match(tagPage, @"<td .*>(?<sha256>.*)</td>", RegexOptions.Singleline);
// TODO Replace with regex get basename and sha256
var fileName = Path.GetFileName(new Uri(latestVersionDownloadUrl).LocalPath);
fileName = fileName.Insert(fileName.LastIndexOf('.'), LatestVersionNumber);
var fileFullPath = Path.Combine(Global.NetchDir, "data", fileName);
var sha256 = match.Groups["sha256"].Value;
if (File.Exists(fileFullPath))
{
if (Utils.Utils.SHA256CheckSum(fileFullPath) == sha256)
{
RunUpdater();
return;
}
NewVersionFoundFailed?.Invoke(this, new EventArgs());
File.Delete(fileFullPath);
}
try
{
client.DownloadProgressChanged += onDownloadProgressChanged;
await client.DownloadFileTaskAsync(new Uri(latestVersionDownloadUrl), fileFullPath);
client.DownloadProgressChanged -= onDownloadProgressChanged;
}
catch (Exception e)
{
throw new Exception(i18N.Translate("Download Update Failed", ": ") + e.Message);
}
if (Utils.Utils.SHA256CheckSum(fileFullPath) != sha256)
throw new Exception(i18N.Translate("The downloaded file has the wrong hash"));
RunUpdater();
void RunUpdater()
{
// if debugging process stopped, debugger will kill child processes!!!!
// 调试进程结束,调试器将会杀死子进程
// uncomment if(!Debugger.isAttach) block in NetchUpdater Project's main() method and attach to NetchUpdater process to debug
// 在 NetchUpdater 项目的 main() 方法中取消注释 if!Debugger.isAttach并附加到 NetchUpdater 进程进行调试
Process.Start(new ProcessStartInfo
{
FileName = Path.Combine(Global.NetchDir, "NetchUpdater.exe"),
Arguments =
$"{Global.Settings.UDPSocketPort} \"{fileFullPath}\" \"{Global.NetchDir}\""
});
}
}
}
}
}

View File

@@ -1,127 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Netch.Controllers;
using Netch.Models;
using Netch.Utils;
namespace Netch.Forms
{
public partial class Dummy
{
}
partial class MainForm
{
private bool _isFirstCloseWindow = true;
private async void ControlFun()
{
Configuration.Save();
if (State == State.Waiting || State == State.Stopped)
{
// 服务器、模式 需选择
if (!(ServerComboBox.SelectedItem is Server server))
{
MessageBoxX.Show(i18N.Translate("Please select a server first"));
return;
}
if (!(ModeComboBox.SelectedItem is Models.Mode mode))
{
MessageBoxX.Show(i18N.Translate("Please select a mode first"));
return;
}
// 清除模式搜索框文本选择
ModeComboBox.Select(0, 0);
State = State.Starting;
if (await MainController.Start(server, mode))
{
State = State.Started;
_ = Task.Run(() => { Bandwidth.NetTraffic(server, mode); });
// 如果勾选启动后最小化
if (Global.Settings.MinimizeWhenStarted)
{
WindowState = FormWindowState.Minimized;
if (_isFirstCloseWindow)
{
// 显示提示语
NotifyTip(i18N.Translate("Netch is now minimized to the notification bar, double click this icon to restore."));
_isFirstCloseWindow = false;
}
Hide();
}
if (Global.Settings.StartedTcping)
{
// 自动检测延迟
_ = Task.Run(() =>
{
while (State == State.Started)
{
server.Test();
// 重绘 ServerComboBox
ServerComboBox.Invalidate();
Thread.Sleep(Global.Settings.StartedTcping_Interval * 1000);
}
});
}
}
else
{
State = State.Stopped;
StatusText(i18N.Translate("Start failed"));
}
}
else
{
// 停止
State = State.Stopping;
await MainController.Stop();
State = State.Stopped;
_ = Task.Run(TestServer);
}
}
public void OnBandwidthUpdated(ulong download)
{
if (InvokeRequired)
{
BeginInvoke(new Action<ulong>(OnBandwidthUpdated), download);
return;
}
try
{
UsedBandwidthLabel.Text = $"{i18N.Translate("Used", ": ")}{Bandwidth.Compute(download)}";
//UploadSpeedLabel.Text = $"↑: {Utils.Bandwidth.Compute(upload - LastUploadBandwidth)}/s";
DownloadSpeedLabel.Text = $"↑↓: {Bandwidth.Compute(download - LastDownloadBandwidth)}/s";
//LastUploadBandwidth = upload;
LastDownloadBandwidth = download;
Refresh();
}
catch
{
// ignored
}
}
/// <summary>
/// 上一次上传的流量
/// </summary>
public ulong LastUploadBandwidth;
/// <summary>
/// 上一次下载的流量
/// </summary>
public ulong LastDownloadBandwidth;
}
}

View File

@@ -39,6 +39,7 @@
this.SubscribeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ManageSubscribeLinksToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.UpdateServersFromSubscribeLinksToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.OptionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.OpenDirectoryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.CleanDNSCacheToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
@@ -87,6 +88,7 @@
this.ProfileTable = new System.Windows.Forms.TableLayoutPanel();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.ButtomControlContainerControl = new System.Windows.Forms.ContainerControl();
this.updatePACToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MenuStrip.SuspendLayout();
this.ConfigurationGroupBox.SuspendLayout();
this.configLayoutPanel.SuspendLayout();
@@ -169,7 +171,8 @@
//
this.SubscribeToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ManageSubscribeLinksToolStripMenuItem,
this.UpdateServersFromSubscribeLinksToolStripMenuItem});
this.UpdateServersFromSubscribeLinksToolStripMenuItem,
this.UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem});
this.SubscribeToolStripMenuItem.Margin = new System.Windows.Forms.Padding(0, 0, 0, 1);
this.SubscribeToolStripMenuItem.Name = "SubscribeToolStripMenuItem";
this.SubscribeToolStripMenuItem.Size = new System.Drawing.Size(77, 21);
@@ -189,6 +192,13 @@
this.UpdateServersFromSubscribeLinksToolStripMenuItem.Text = "Update Servers From Subscribe Links";
this.UpdateServersFromSubscribeLinksToolStripMenuItem.Click += new System.EventHandler(this.UpdateServersFromSubscribeLinksToolStripMenuItem_Click);
//
// UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem
//
this.UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem.Name = "UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem";
this.UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem.Size = new System.Drawing.Size(294, 22);
this.UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem.Text = "Update Servers From Subscribe Links With Proxy";
this.UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem.Click += new System.EventHandler(this.UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem_Click);
//
// OptionsToolStripMenuItem
//
this.OptionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
@@ -196,6 +206,7 @@
this.CleanDNSCacheToolStripMenuItem,
this.UpdateACLToolStripMenuItem,
this.updateACLWithProxyToolStripMenuItem,
this.updatePACToolStripMenuItem,
this.UninstallServiceToolStripMenuItem,
this.UninstallTapDriverToolStripMenuItem});
this.OptionsToolStripMenuItem.Margin = new System.Windows.Forms.Padding(0, 0, 0, 1);
@@ -243,7 +254,7 @@
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);
this.UninstallTapDriverToolStripMenuItem.Click += new System.EventHandler(this.UninstallTapDriverToolStripMenuItem_Click);
//
// HelpToolStripMenuItem
//
@@ -441,6 +452,7 @@
this.EditServerPictureBox.Location = new System.Drawing.Point(3, 3);
this.EditServerPictureBox.Name = "EditServerPictureBox";
this.EditServerPictureBox.Size = new System.Drawing.Size(16, 16);
this.EditServerPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.EditServerPictureBox.TabIndex = 7;
this.EditServerPictureBox.TabStop = false;
this.EditServerPictureBox.Click += new System.EventHandler(this.EditServerPictureBox_Click);
@@ -452,6 +464,7 @@
this.CopyLinkPictureBox.Location = new System.Drawing.Point(72, 3);
this.CopyLinkPictureBox.Name = "CopyLinkPictureBox";
this.CopyLinkPictureBox.Size = new System.Drawing.Size(18, 18);
this.CopyLinkPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.CopyLinkPictureBox.TabIndex = 14;
this.CopyLinkPictureBox.TabStop = false;
this.CopyLinkPictureBox.Click += new System.EventHandler(this.CopyLinkPictureBox_Click);
@@ -463,6 +476,7 @@
this.DeleteServerPictureBox.Location = new System.Drawing.Point(26, 3);
this.DeleteServerPictureBox.Name = "DeleteServerPictureBox";
this.DeleteServerPictureBox.Size = new System.Drawing.Size(16, 16);
this.DeleteServerPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.DeleteServerPictureBox.TabIndex = 8;
this.DeleteServerPictureBox.TabStop = false;
this.DeleteServerPictureBox.Click += new System.EventHandler(this.DeleteServerPictureBox_Click);
@@ -474,6 +488,7 @@
this.SpeedPictureBox.Location = new System.Drawing.Point(49, 3);
this.SpeedPictureBox.Name = "SpeedPictureBox";
this.SpeedPictureBox.Size = new System.Drawing.Size(16, 16);
this.SpeedPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.SpeedPictureBox.TabIndex = 9;
this.SpeedPictureBox.TabStop = false;
this.SpeedPictureBox.Click += new System.EventHandler(this.SpeedPictureBox_Click);
@@ -501,6 +516,7 @@
this.EditModePictureBox.Location = new System.Drawing.Point(3, 3);
this.EditModePictureBox.Name = "EditModePictureBox";
this.EditModePictureBox.Size = new System.Drawing.Size(16, 16);
this.EditModePictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.EditModePictureBox.TabIndex = 12;
this.EditModePictureBox.TabStop = false;
this.EditModePictureBox.Click += new System.EventHandler(this.EditModePictureBox_Click);
@@ -512,6 +528,7 @@
this.DeleteModePictureBox.Location = new System.Drawing.Point(26, 3);
this.DeleteModePictureBox.Name = "DeleteModePictureBox";
this.DeleteModePictureBox.Size = new System.Drawing.Size(16, 16);
this.DeleteModePictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.DeleteModePictureBox.TabIndex = 13;
this.DeleteModePictureBox.TabStop = false;
this.DeleteModePictureBox.Click += new System.EventHandler(this.DeleteModePictureBox_Click);
@@ -691,6 +708,13 @@
this.ButtomControlContainerControl.TabStop = false;
this.ButtomControlContainerControl.Text = "groupBox1";
//
// updatePACToolStripMenuItem
//
this.updatePACToolStripMenuItem.Name = "updatePACToolStripMenuItem";
this.updatePACToolStripMenuItem.Size = new System.Drawing.Size(220, 22);
this.updatePACToolStripMenuItem.Text = "Update PAC";
this.updatePACToolStripMenuItem.Click += new System.EventHandler(this.updatePACToolStripMenuItem_Click);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
@@ -785,6 +809,7 @@
private System.Windows.Forms.ToolStripMenuItem UpdateACLToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem updateACLWithProxyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem UpdateServersFromSubscribeLinksToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem UpdateServersFromSubscribeLinksWithProxyToolStripMenuItem;
private System.Windows.Forms.ToolStripStatusLabel UploadSpeedLabel;
private System.Windows.Forms.ToolStripStatusLabel UsedBandwidthLabel;
private System.Windows.Forms.ToolStripLabel NewVersionLabel;
@@ -797,5 +822,6 @@
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.ContainerControl ButtomControlContainerControl;
private System.Windows.Forms.ToolStripMenuItem updatePACToolStripMenuItem;
}
}

View File

@@ -1,378 +0,0 @@
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.Forms.Mode;
using Netch.Models;
using Netch.Utils;
namespace Netch.Forms
{
partial class Dummy
{
}
partial class MainForm
{
#region MenuStrip
#region
private void ImportServersFromClipboardToolStripMenuItem_Click(object sender, EventArgs e)
{
var texts = Clipboard.GetText();
if (!string.IsNullOrWhiteSpace(texts))
{
var servers = ShareLink.ParseText(texts);
Global.Settings.Server.AddRange(servers);
NotifyTip(i18N.TranslateFormat("Import {0} server(s) form Clipboard", servers.Count));
InitServer();
Configuration.Save();
}
}
private void AddServerToolStripMenuItem_Click(object sender, EventArgs e)
{
var s = ((ToolStripMenuItem) sender).Text;
var start = s.IndexOf("[", StringComparison.Ordinal) + 1;
var end = s.IndexOf("]", start, StringComparison.Ordinal);
var result = s.Substring(start, end - start);
Hide();
ServerHelper.GetUtilByFullName(result).Create();
InitServer();
Configuration.Save();
Show();
}
#endregion
#region
private void CreateProcessModeToolStripButton_Click(object sender, EventArgs e)
{
Hide();
new Process().ShowDialog();
Show();
}
private void ReloadModesToolStripMenuItem_Click(object sender, EventArgs e)
{
Enabled = false;
try
{
ModeHelper.Load();
InitMode();
NotifyTip(i18N.Translate("Modes have been reload"));
}
catch (Exception)
{
// ignored
}
finally
{
Enabled = true;
}
}
#endregion
#region
private void ManageSubscribeLinksToolStripMenuItem_Click(object sender, EventArgs e)
{
Hide();
new SubscribeForm().ShowDialog();
InitServer();
Show();
}
private async void UpdateServersFromSubscribeLinksToolStripMenuItem_Click(object sender, EventArgs e)
{
await UpdateServersFromSubscribe();
}
private readonly object _serverLock = new object();
public async Task UpdateServersFromSubscribe()
{
void DisableItems(bool v)
{
MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ProfileGroupBox.Enabled = ControlButton.Enabled = v;
}
if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1)
Global.Settings.UseProxyToUpdateSubscription = false;
if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1)
{
MessageBoxX.Show(i18N.Translate("Please select a server first"));
return;
}
if (Global.Settings.SubscribeLink.Count <= 0)
{
MessageBoxX.Show(i18N.Translate("No subscription link"));
return;
}
StatusText(i18N.Translate("Starting update subscription"));
DisableItems(false);
try
{
if (Global.Settings.UseProxyToUpdateSubscription)
{
var mode = new Models.Mode
{
Remark = "ProxyUpdate",
Type = 5
};
await MainController.Start(ServerComboBox.SelectedItem as Server, mode);
}
await Task.WhenAll(Global.Settings.SubscribeLink.Select(async item => await Task.Run(() =>
{
try
{
var request = WebUtil.CreateRequest(item.Link);
if (!string.IsNullOrEmpty(item.UserAgent)) request.UserAgent = item.UserAgent;
if (Global.Settings.UseProxyToUpdateSubscription)
request.Proxy = new WebProxy($"http://127.0.0.1:{Global.Settings.HTTPLocalPort}");
List<Server> servers;
var result = WebUtil.DownloadString(request, out var rep);
if (rep.StatusCode == HttpStatusCode.OK)
{
servers = ShareLink.ParseText(result);
}
else
{
throw new Exception($"{item.Remark} Response Status Code: {rep.StatusCode}");
}
foreach (var server in servers)
{
server.Group = item.Remark;
}
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());
InitServer();
Configuration.Save();
StatusText(i18N.Translate("Subscription updated"));
}
catch (Exception)
{
// ignored
}
finally
{
if (Global.Settings.UseProxyToUpdateSubscription)
{
await MainController.Stop();
}
DisableItems(true);
}
}
#endregion
#region
private void CheckForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
{
Task.Run(() =>
{
void OnNewVersionNotFound(object o, EventArgs args)
{
_updater.NewVersionNotFound -= OnNewVersionNotFound;
NotifyTip(i18N.Translate("Already latest version"));
}
void OnNewVersionFoundFailed(object o, EventArgs args)
{
_updater.NewVersionFoundFailed -= OnNewVersionFoundFailed;
NotifyTip(i18N.Translate("New version found failed"), info: false);
}
_updater.NewVersionNotFound += OnNewVersionNotFound;
_updater.NewVersionFoundFailed += OnNewVersionFoundFailed;
CheckUpdate();
});
}
private void OpenDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
Utils.Utils.Open(".\\");
}
private async void CleanDNSCacheToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
await Task.Run(() => DNS.Cache.Clear());
StatusText(i18N.Translate("DNS cache cleanup succeeded"));
}
catch (Exception)
{
// ignored
}
}
private void updateACLWithProxyToolStripMenuItem_Click(object sender, EventArgs e)
{
UpdateACL(true);
}
private void updateACLToolStripMenuItem_Click(object sender, EventArgs e)
{
UpdateACL(false);
}
private async void UpdateACL(bool useProxy)
{
void DisableItems(bool v)
{
UpdateACLToolStripMenuItem.Enabled = updateACLWithProxyToolStripMenuItem.Enabled = v;
}
if (useProxy && ServerComboBox.SelectedIndex == -1)
{
MessageBoxX.Show(i18N.Translate("Please select a server first"));
return;
}
DisableItems(false);
NotifyTip(i18N.Translate("Updating in the background"));
try
{
if (useProxy)
{
var mode = new Models.Mode
{
Remark = "ProxyUpdate",
Type = 5
};
State = State.Starting;
await MainController.Start(ServerComboBox.SelectedItem as Server, mode);
}
var req = WebUtil.CreateRequest(Global.Settings.ACL);
if (useProxy)
req.Proxy = new WebProxy($"http://127.0.0.1:{Global.Settings.HTTPLocalPort}");
await WebUtil.DownloadFileAsync(req, Path.Combine(Global.NetchDir, "bin\\default.acl"));
NotifyTip(i18N.Translate("ACL updated successfully"));
}
catch (Exception e)
{
NotifyTip(i18N.Translate("ACL update failed") + "\n" + e.Message, info: false);
Logging.Error("更新 ACL 失败!" + e);
}
finally
{
if (useProxy)
{
await MainController.Stop();
State = State.Stopped;
}
DisableItems(true);
}
}
private async void UninstallServiceToolStripMenuItem_Click(object sender, EventArgs e)
{
Enabled = false;
StatusText(i18N.TranslateFormat("Uninstalling {0}", "NF Service"));
try
{
await Task.Run(() =>
{
if (NFController.UninstallDriver())
{
StatusText(i18N.TranslateFormat("{0} has been uninstalled", "NF Service"));
}
});
}
finally
{
Enabled = true;
}
}
private async void reinstallTapDriverToolStripMenuItem_Click(object sender, EventArgs e)
{
StatusText(i18N.TranslateFormat("Uninstalling {0}", "TUN/TAP driver"));
Enabled = false;
try
{
await Task.Run(TUNTAP.deltapall);
StatusText(i18N.TranslateFormat("{0} has been uninstalled", "TUN/TAP driver"));
}
catch (Exception exception)
{
Logging.Error($"卸载 TUN/TAP 适配器失败: {exception}");
}
finally
{
State = State.Waiting;
Enabled = true;
}
}
#endregion
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Exit(true);
}
private void VersionLabel_Click(object sender, EventArgs e)
{
Utils.Utils.Open($"https://github.com/{UpdateChecker.Owner}/{UpdateChecker.Repo}/releases");
}
private void AboutToolStripButton_Click(object sender, EventArgs e)
{
Hide();
new AboutForm().ShowDialog();
Show();
}
private void fAQToolStripMenuItem_Click(object sender, EventArgs e)
{
Utils.Utils.Open($"https://netch.org/#/docs/zh-CN/faq");
}
#endregion
}
}

View File

@@ -1,104 +0,0 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Netch.Controllers;
using Netch.Utils;
namespace Netch.Forms
{
/// <summary lang="en">
/// this class is used to disable Designer <para />
/// </summary>
/// <summary lang="zh">
/// 此类用于禁用设计器
/// </summary>
[DesignerCategory("")]
public partial class Dummy
{
}
partial class MainForm
{
private readonly UpdateChecker _updater = new UpdateChecker();
private void CheckUpdate()
{
_updater.NewVersionFound += (o, args) =>
{
NotifyTip($"{i18N.Translate(@"New version available", ": ")}{_updater.LatestVersionNumber}");
NewVersionLabel.Visible = true;
};
_updater.Check(Global.Settings.CheckBetaUpdate);
}
private async void NewVersionLabel_Click(object sender, EventArgs e)
{
if (!_updater.LatestVersionDownloadUrl.Contains("Netch"))
{
Utils.Utils.Open(_updater.LatestVersionUrl);
return;
}
if (MessageBoxX.Show(i18N.Translate("Download and install now?"), confirm: true) != DialogResult.OK)
return;
NotifyTip(i18N.Translate("Start downloading new version"));
var tagPage = await WebUtil.DownloadStringAsync(WebUtil.CreateRequest(_updater.LatestVersionUrl));
var match = Regex.Match(tagPage, @"<td .*>(?<sha256>.*)</td>", RegexOptions.Singleline);
// TODO Replace with regex get basename and sha256
var fileName = Path.GetFileName(new Uri(_updater.LatestVersionDownloadUrl).LocalPath);
fileName = fileName.Insert(fileName.LastIndexOf('.'), _updater.LatestVersionNumber);
var fileFullPath = Path.Combine(Global.NetchDir, "data", fileName);
var sha256 = match.Groups["sha256"].Value;
try
{
if (File.Exists(fileFullPath))
{
if (Utils.Utils.SHA256CheckSum(fileFullPath) == sha256)
{
RunUpdater();
return;
}
File.Delete(fileFullPath);
}
// TODO Replace "New Version Found" to Progress bar
await WebUtil.DownloadFileAsync(WebUtil.CreateRequest(_updater.LatestVersionDownloadUrl), fileFullPath);
if (Utils.Utils.SHA256CheckSum(fileFullPath) != sha256)
{
MessageBoxX.Show("The downloaded file has the wrong hash");
return;
}
RunUpdater();
}
catch (Exception exception)
{
NotifyTip($"{i18N.Translate("Download update failed")}\n{exception.Message}");
Logging.Error($"下载更新失败 {exception}");
}
void RunUpdater()
{
// if debugging process stopped, debugger will kill child processes!!!!
// 调试进程结束,调试器将会杀死子进程
// uncomment if(!Debugger.isAttach) block in NetchUpdater Project's main() method and attach to NetchUpdater process to debug
// 在 NetchUpdater 项目的 main() 方法中取消注释 if!Debugger.isAttach并附加到 NetchUpdater 进程进行调试
Process.Start(new ProcessStartInfo
{
FileName = Path.Combine(Global.NetchDir, "NetchUpdater.exe"),
Arguments =
$"{Global.Settings.UDPSocketPort} \"{fileFullPath}\" \"{Global.NetchDir}\""
});
}
}
}
}

View File

@@ -1,189 +0,0 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Netch.Models;
using Netch.Utils;
namespace Netch.Forms
{
public partial class Dummy
{
}
partial class MainForm
{
private int _configurationGroupBoxHeight;
private int _profileConfigurationHeight;
private void InitProfile()
{
// Clear
foreach (var button in ProfileButtons)
button.Dispose();
ProfileButtons.Clear();
ProfileTable.ColumnStyles.Clear();
ProfileTable.RowStyles.Clear();
var numProfile = Global.Settings.ProfileCount;
if (numProfile == 0)
{
// Hide Profile GroupBox, Change window size
configLayoutPanel.RowStyles[2].SizeType = SizeType.Percent;
configLayoutPanel.RowStyles[2].Height = 0;
ProfileGroupBox.Visible = false;
ConfigurationGroupBox.Size = new Size(ConfigurationGroupBox.Size.Width, _configurationGroupBoxHeight - _profileConfigurationHeight);
}
else
{
// Load Profiles
ProfileTable.ColumnCount = numProfile;
while (Global.Settings.Profiles.Count < numProfile)
{
Global.Settings.Profiles.Add(new Profile());
}
for (var i = 0; i < numProfile; ++i)
{
var b = new Button();
b.Click += ProfileButton_Click;
b.Dock = DockStyle.Fill;
b.Text = !Global.Settings.Profiles[i].IsDummy ? Global.Settings.Profiles[i].ProfileName : i18N.Translate("None");
ProfileTable.Controls.Add(b, i, 0);
ProfileButtons.Add(b);
}
// equal column
for (var i = 1; i <= ProfileTable.RowCount; i++)
{
ProfileTable.RowStyles.Add(new RowStyle(SizeType.Percent, 1));
}
for (var i = 1; i <= ProfileTable.ColumnCount; i++)
{
ProfileTable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 1));
}
configLayoutPanel.RowStyles[2].SizeType = SizeType.AutoSize;
ProfileGroupBox.Visible = true;
ConfigurationGroupBox.Size = new Size(ConfigurationGroupBox.Size.Width, _configurationGroupBoxHeight);
}
}
private void LoadProfile(int index)
{
var p = Global.Settings.Profiles[index];
ProfileNameText.Text = p.ModeRemark;
if (p.IsDummy)
throw new Exception("Profile not found.");
var server = ServerComboBox.Items.Cast<Server>().FirstOrDefault(s => s.Remark.Equals(p.ServerRemark));
var mode = ModeComboBox.Items.Cast<Models.Mode>().FirstOrDefault(m => m.Remark.Equals(p.ModeRemark));
if (server == null)
{
throw new Exception("Server not found.");
}
if (mode == null)
{
throw new Exception("Mode not found.");
}
ServerComboBox.SelectedItem = server;
ModeComboBox.SelectedItem = mode;
}
private void SaveProfile(int index)
{
var selectedServer = (Server) ServerComboBox.SelectedItem;
var selectedMode = (Models.Mode) ModeComboBox.SelectedItem;
var name = ProfileNameText.Text;
Global.Settings.Profiles[index] = new Profile(selectedServer, selectedMode, name);
}
private void RemoveProfile(int index)
{
Global.Settings.Profiles[index] = new Profile();
}
private List<Button> ProfileButtons = new List<Button>();
private async void ProfileButton_Click(object sender, EventArgs e)
{
var index = ProfileButtons.IndexOf((Button) sender);
if (ModifierKeys == Keys.Control)
{
if (ServerComboBox.SelectedIndex == -1)
{
MessageBoxX.Show(i18N.Translate("Please select a server first"));
}
else if (ModeComboBox.SelectedIndex == -1)
{
MessageBoxX.Show(i18N.Translate("Please select a mode first"));
}
else if (ProfileNameText.Text == "")
{
MessageBoxX.Show(i18N.Translate("Please enter a profile name first"));
}
else
{
SaveProfile(index);
ProfileButtons[index].Text = ProfileNameText.Text;
}
return;
}
if (Global.Settings.Profiles[index].IsDummy)
{
MessageBoxX.Show(
i18N.Translate("No saved profile here. Save a profile first by Ctrl+Click on the button"));
return;
}
if (ModifierKeys == Keys.Shift)
{
if (MessageBoxX.Show(i18N.Translate("Remove this Profile?"), confirm: true) != DialogResult.OK) return;
RemoveProfile(index);
ProfileButtons[index].Text = i18N.Translate("None");
return;
}
// Reset Mode ComboBox Items
ModeComboBox.Text = string.Empty;
try
{
LoadProfile(index);
}
catch (Exception exception)
{
MessageBoxX.Show(exception.Message, LogLevel.ERROR);
return;
}
// start the profile
ControlFun();
if (State == State.Stopping || State == State.Stopped)
{
while (State != State.Stopped)
{
await Task.Delay(250);
}
ControlFun();
}
}
}
}

View File

@@ -1,175 +0,0 @@
using System;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Netch.Utils;
namespace Netch.Forms
{
public partial class Dummy
{
}
partial class MainForm
{
#region Server
private void InitServer()
{
var comboBoxInitialized = _comboBoxInitialized;
_comboBoxInitialized = false;
ServerComboBox.Items.Clear();
ServerComboBox.Items.AddRange(Global.Settings.Server.ToArray());
SelectLastServer();
_comboBoxInitialized = comboBoxInitialized;
}
private static void TestServer()
{
try
{
Parallel.ForEach(Global.Settings.Server, new ParallelOptions {MaxDegreeOfParallelism = 16},
server => { server.Test(); });
}
catch (Exception)
{
// ignored
}
}
public void SelectLastServer()
{
// 如果值合法,选中该位置
if (Global.Settings.ServerComboBoxSelectedIndex > 0 &&
Global.Settings.ServerComboBoxSelectedIndex < ServerComboBox.Items.Count)
{
ServerComboBox.SelectedIndex = Global.Settings.ServerComboBoxSelectedIndex;
}
// 如果值非法,且当前 ServerComboBox 中有元素,选择第一个位置
else if (ServerComboBox.Items.Count > 0)
{
ServerComboBox.SelectedIndex = 0;
}
// 如果当前 ServerComboBox 中没元素,不做处理
}
#endregion
#region Mode
public void InitMode()
{
var comboBoxInitialized = _comboBoxInitialized;
_comboBoxInitialized = false;
ModeComboBox.Items.Clear();
ModeComboBox.Items.AddRange(Global.Modes.ToArray());
ModeComboBox.Tag = null;
SelectLastMode();
_comboBoxInitialized = comboBoxInitialized;
}
public void SelectLastMode()
{
// 如果值合法,选中该位置
if (Global.Settings.ModeComboBoxSelectedIndex > 0 &&
Global.Settings.ModeComboBoxSelectedIndex < ModeComboBox.Items.Count)
{
ModeComboBox.SelectedIndex = Global.Settings.ModeComboBoxSelectedIndex;
}
// 如果值非法,且当前 ModeComboBox 中有元素,选择第一个位置
else if (ModeComboBox.Items.Count > 0)
{
ModeComboBox.SelectedIndex = 0;
}
// 如果当前 ModeComboBox 中没元素,不做处理
}
#endregion
/// <summary>
/// Init at <see cref="MainForm_Load"/>
/// </summary>
private int _eWidth;
private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
try
{
if (!(sender is ComboBox cbx))
{
return;
}
// 绘制背景颜色
e.Graphics.FillRectangle(new SolidBrush(Color.White), e.Bounds);
if (e.Index < 0) return;
// 绘制 备注/名称 字符串
e.Graphics.DrawString(cbx.Items[e.Index].ToString(), cbx.Font, new SolidBrush(Color.Black), e.Bounds);
switch (cbx.Items[e.Index])
{
case Models.Server item:
{
// 计算延迟底色
SolidBrush brush;
if (item.Delay > 200)
brush = new SolidBrush(Color.Red);
else if (item.Delay > 80)
brush = new SolidBrush(Color.Yellow);
else if (item.Delay >= 0)
brush = new SolidBrush(Color.FromArgb(50, 255, 56));
else
brush = new SolidBrush(Color.Gray);
// 绘制延迟底色
e.Graphics.FillRectangle(brush, _eWidth * 9, e.Bounds.Y, _eWidth, e.Bounds.Height);
// 绘制延迟字符串
e.Graphics.DrawString(item.Delay.ToString(), cbx.Font, new SolidBrush(Color.Black),
_eWidth * 9 + _eWidth / 30, e.Bounds.Y);
break;
}
case Models.Mode item:
{
// 绘制 模式Box 底色
e.Graphics.FillRectangle(new SolidBrush(Color.Gray), _eWidth * 9, e.Bounds.Y, _eWidth,
e.Bounds.Height);
// 绘制 模式行数 字符串
e.Graphics.DrawString(item.Rule.Count.ToString(), cbx.Font, new SolidBrush(Color.Black),
_eWidth * 9 + _eWidth / 30, e.Bounds.Y);
break;
}
}
}
catch (Exception)
{
// ignored
}
}
private void AddAddServerToolStripMenuItems()
{
foreach (var serversUtil in ServerHelper.ServerUtils.Where(i => !string.IsNullOrEmpty(i.FullName)))
{
var fullName = serversUtil.FullName;
var control = new ToolStripMenuItem
{
Name = $"Add{fullName}ServerToolStripMenuItem",
Size = new Size(259, 22),
Text = i18N.TranslateFormat("Add [{0}] Server", fullName),
};
_mainFormText.Add(control.Name, new[] {"Add [{0}] Server", fullName});
control.Click += AddServerToolStripMenuItem_Click;
ServerToolStripMenuItem.DropDownItems.Add(control);
}
}
}
}

View File

@@ -1,237 +0,0 @@
using System;
using System.Drawing;
using System.Text;
using Netch.Models;
using Netch.Utils;
namespace Netch.Forms
{
public partial class Dummy
{
}
partial class MainForm
{
private bool IsWaiting => State == State.Waiting || State == State.Stopped;
private State _state = State.Waiting;
/// <summary>
/// 当前状态
/// </summary>
public State State
{
get => _state;
private set
{
void StartDisableItems(bool enabled)
{
ServerComboBox.Enabled =
ModeComboBox.Enabled =
EditModePictureBox.Enabled =
EditServerPictureBox.Enabled =
DeleteModePictureBox.Enabled =
DeleteServerPictureBox.Enabled = enabled;
// 启动需要禁用的控件
UninstallServiceToolStripMenuItem.Enabled =
updateACLWithProxyToolStripMenuItem.Enabled =
UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled =
UninstallTapDriverToolStripMenuItem.Enabled =
ReloadModesToolStripMenuItem.Enabled = enabled;
}
_state = value;
StatusText(i18N.Translate(StateExtension.GetStatusString(value)));
switch (value)
{
case State.Waiting:
ControlButton.Enabled = true;
ControlButton.Text = i18N.Translate("Start");
break;
case State.Starting:
ControlButton.Enabled = false;
ControlButton.Text = "...";
ProfileGroupBox.Enabled = false;
StartDisableItems(false);
break;
case State.Started:
ControlButton.Enabled = true;
ControlButton.Text = i18N.Translate("Stop");
StatusTextAppend(StatusPortInfoText.Value);
ProfileGroupBox.Enabled = true;
UsedBandwidthLabel.Visible /*= UploadSpeedLabel.Visible*/ = DownloadSpeedLabel.Visible = Global.Flags.IsWindows10Upper;
break;
case State.Stopping:
ControlButton.Enabled = false;
ControlButton.Text = "...";
ProfileGroupBox.Enabled = false;
UsedBandwidthLabel.Visible /*= UploadSpeedLabel.Visible*/ = DownloadSpeedLabel.Visible = false;
NatTypeStatusText();
break;
case State.Stopped:
ControlButton.Enabled = true;
ControlButton.Text = i18N.Translate("Start");
LastUploadBandwidth = 0;
LastDownloadBandwidth = 0;
Bandwidth.Stop();
ProfileGroupBox.Enabled = true;
StartDisableItems(true);
break;
case State.Terminating:
Dispose();
Environment.Exit(Environment.ExitCode);
return;
}
}
}
public void NatTypeStatusText(string text = "", string country = "")
{
if (InvokeRequired)
{
BeginInvoke(new Action<string, string>(NatTypeStatusText), text, country);
return;
}
if (State != State.Started)
{
NatTypeStatusLabel.Text = "";
NatTypeStatusLabel.Visible = NatTypeStatusLightLabel.Visible = false;
return;
}
if (!string.IsNullOrEmpty(text))
{
NatTypeStatusLabel.Text = $"NAT{i18N.Translate(": ")}{text} {(country != string.Empty ? $"[{country}]" : "")}";
UpdateNatTypeLight(int.TryParse(text, out var natType) ? natType : -1);
}
else
{
NatTypeStatusLabel.Text = $@"NAT{i18N.Translate(": ", "Test failed")}";
}
NatTypeStatusLabel.Visible = true;
}
/// <summary>
/// 更新 NAT指示灯颜色
/// </summary>
/// <param name="natType"></param>
private void UpdateNatTypeLight(int natType = -1)
{
if (natType > 0 && natType < 5)
{
NatTypeStatusLightLabel.Visible = Global.Flags.IsWindows10Upper;
Color c;
switch (natType)
{
case 1:
c = Color.LimeGreen;
break;
case 2:
c = Color.Yellow;
break;
case 3:
c = Color.Red;
break;
case 4:
c = Color.Black;
break;
default:
c = Color.Black;
break;
}
NatTypeStatusLightLabel.ForeColor = c;
}
else
{
NatTypeStatusLightLabel.Visible = false;
}
}
/// <summary>
/// 更新状态栏文本
/// </summary>
/// <param name="text"></param>
public void StatusText(string text)
{
if (InvokeRequired)
{
BeginInvoke(new Action<string>(StatusText), text);
return;
}
StatusLabel.Text = i18N.Translate("Status", ": ") + text;
}
public void StatusTextAppend(string text)
{
StatusLabel.Text += text;
}
public static class StatusPortInfoText
{
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 == null && _httpPort == null)
return string.Empty;
var text = new StringBuilder();
if (_shareLan == true)
text.Append(i18N.Translate("Allow other Devices to connect") + " ");
if (_socks5Port != null)
text.Append($"Socks5 {i18N.Translate("Local Port", ": ")}{_socks5Port}");
if (_httpPort != null)
{
if (_socks5Port != null)
text.Append(" | ");
text.Append($"HTTP {i18N.Translate("Local Port", ": ")}{_httpPort}");
}
return $" ({text})";
}
}
public static void Reset()
{
_httpPort = _socks5Port = null;
_shareLan = null;
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,11 @@
using System;
using System.Windows.Forms;
using Netch.Models;
using Netch.Utils;
namespace Netch.Utils
namespace Netch.Forms
{
static class MessageBoxX
public static class MessageBoxX
{
/// <summary>
/// </summary>
@@ -34,11 +35,11 @@ namespace Netch.Utils
};
return MessageBox.Show(
owner: owner,
text: text,
caption: i18N.Translate(title),
buttons: confirm ? MessageBoxButtons.OKCancel : MessageBoxButtons.OK,
icon: msgIcon);
owner,
text,
i18N.Translate(title),
confirm ? MessageBoxButtons.OKCancel : MessageBoxButtons.OK,
msgIcon);
}
}
}

View File

@@ -6,6 +6,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.WindowsAPICodePack.Dialogs;
using Netch.Controllers;
using Netch.Utils;
namespace Netch.Forms.Mode
@@ -139,23 +140,28 @@ namespace Netch.Forms.Mode
{
await Task.Run(() =>
{
if (!string.IsNullOrWhiteSpace(ProcessNameTextBox.Text))
{
var process = ProcessNameTextBox.Text;
if (!RuleListBox.Items.Contains(process))
{
RuleListBox.Items.Add(process);
}
Edited = true;
RuleListBox.SelectedIndex = RuleListBox.Items.IndexOf(process);
ProcessNameTextBox.Text = string.Empty;
}
else
if (string.IsNullOrWhiteSpace(ProcessNameTextBox.Text))
{
MessageBoxX.Show(i18N.Translate("Please enter an process name (xxx.exe)"));
return;
}
if (!NFController.CheckCppRegex(ProcessNameTextBox.Text))
{
MessageBoxX.Show("Rule does not conform to C++ regular expression syntax");
return;
}
var process = ProcessNameTextBox.Text;
if (!RuleListBox.Items.Contains(process))
{
RuleListBox.Items.Add(process);
}
Edited = true;
RuleListBox.SelectedIndex = RuleListBox.Items.IndexOf(process);
ProcessNameTextBox.Text = string.Empty;
});
}

View File

@@ -168,28 +168,37 @@ namespace Netch.Forms
private void ControlButton_Click(object sender, EventArgs e)
{
if (_checkActions.All(pair => pair.Value.Invoke(pair.Key.Text)))
Utils.Utils.ComponentIterator(this, component => Utils.Utils.ChangeControlForeColor(component, Color.Black));
var flag = true;
foreach (var pair in _checkActions.Where(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"));
Utils.Utils.ChangeControlForeColor(pair.Key, Color.Red);
flag = false;
}
else
if (!flag)
{
return;
}
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"));
Close();
}

View File

@@ -34,6 +34,9 @@ namespace Netch.Forms
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SettingForm));
this.TabControl = new System.Windows.Forms.TabControl();
this.GeneralTabPage = new System.Windows.Forms.TabPage();
this.ServerPingTypeLabel = new System.Windows.Forms.Label();
this.TCPingRadioBtn = new System.Windows.Forms.RadioButton();
this.ICMPingRadioBtn = new System.Windows.Forms.RadioButton();
this.PortGroupBox = new System.Windows.Forms.GroupBox();
this.Socks5PortLabel = new System.Windows.Forms.Label();
this.Socks5PortTextBox = new System.Windows.Forms.TextBox();
@@ -46,9 +49,10 @@ namespace Netch.Forms
this.ResolveServerHostnameCheckBox = new System.Windows.Forms.CheckBox();
this.ProfileCountLabel = new System.Windows.Forms.Label();
this.ProfileCountTextBox = new System.Windows.Forms.TextBox();
this.TcpingAtStartedCheckBox = new System.Windows.Forms.CheckBox();
this.DetectionIntervalLabel = new System.Windows.Forms.Label();
this.DetectionIntervalTextBox = new System.Windows.Forms.TextBox();
this.StartedPingLabel = new System.Windows.Forms.Label();
this.DetectionTickLabel = new System.Windows.Forms.Label();
this.StartedPingIntervalTextBox = new System.Windows.Forms.TextBox();
this.DetectionTickTextBox = new System.Windows.Forms.TextBox();
this.STUNServerLabel = new System.Windows.Forms.Label();
this.STUN_ServerComboBox = new System.Windows.Forms.ComboBox();
this.AclLabel = new System.Windows.Forms.Label();
@@ -56,9 +60,12 @@ namespace Netch.Forms
this.LanguageLabel = new System.Windows.Forms.Label();
this.LanguageComboBox = new System.Windows.Forms.ComboBox();
this.NFTabPage = new System.Windows.Forms.TabPage();
this.NoProxyForTcpCheckBox = new System.Windows.Forms.CheckBox();
this.NoProxyForUdpCheckBox = new System.Windows.Forms.CheckBox();
this.ModifySystemDNSCheckBox = new System.Windows.Forms.CheckBox();
this.ModifiedDNSLabel = new System.Windows.Forms.Label();
this.ModifiedDNSTextBox = new System.Windows.Forms.TextBox();
this.RedirectorSSCheckBox = new System.Windows.Forms.CheckBox();
this.TAPTabPage = new System.Windows.Forms.TabPage();
this.TUNTAPGroupBox = new System.Windows.Forms.GroupBox();
this.TUNTAPAddressLabel = new System.Windows.Forms.Label();
@@ -99,7 +106,7 @@ namespace Netch.Forms
this.RunAtStartupCheckBox = new System.Windows.Forms.CheckBox();
this.CheckUpdateWhenOpenedCheckBox = new System.Windows.Forms.CheckBox();
this.CheckBetaUpdateCheckBox = new System.Windows.Forms.CheckBox();
this.UpdateSubscribeatWhenOpenedCheckBox = new System.Windows.Forms.CheckBox();
this.UpdateServersWhenOpenedCheckBox = new System.Windows.Forms.CheckBox();
this.AioDNSTabPage = new System.Windows.Forms.TabPage();
this.AioDNSRuleRuleLabel = new System.Windows.Forms.Label();
this.AioDNSRulePathTextBox = new System.Windows.Forms.TextBox();
@@ -140,14 +147,18 @@ namespace Netch.Forms
// GeneralTabPage
//
this.GeneralTabPage.BackColor = System.Drawing.SystemColors.ButtonFace;
this.GeneralTabPage.Controls.Add(this.ServerPingTypeLabel);
this.GeneralTabPage.Controls.Add(this.TCPingRadioBtn);
this.GeneralTabPage.Controls.Add(this.ICMPingRadioBtn);
this.GeneralTabPage.Controls.Add(this.PortGroupBox);
this.GeneralTabPage.Controls.Add(this.BootShadowsocksFromDLLCheckBox);
this.GeneralTabPage.Controls.Add(this.ResolveServerHostnameCheckBox);
this.GeneralTabPage.Controls.Add(this.ProfileCountLabel);
this.GeneralTabPage.Controls.Add(this.ProfileCountTextBox);
this.GeneralTabPage.Controls.Add(this.TcpingAtStartedCheckBox);
this.GeneralTabPage.Controls.Add(this.DetectionIntervalLabel);
this.GeneralTabPage.Controls.Add(this.DetectionIntervalTextBox);
this.GeneralTabPage.Controls.Add(this.StartedPingLabel);
this.GeneralTabPage.Controls.Add(this.DetectionTickLabel);
this.GeneralTabPage.Controls.Add(this.StartedPingIntervalTextBox);
this.GeneralTabPage.Controls.Add(this.DetectionTickTextBox);
this.GeneralTabPage.Controls.Add(this.STUNServerLabel);
this.GeneralTabPage.Controls.Add(this.STUN_ServerComboBox);
this.GeneralTabPage.Controls.Add(this.AclLabel);
@@ -161,6 +172,37 @@ namespace Netch.Forms
this.GeneralTabPage.TabIndex = 0;
this.GeneralTabPage.Text = "General";
//
// ServerPingTypeLabel
//
this.ServerPingTypeLabel.AutoSize = true;
this.ServerPingTypeLabel.Location = new System.Drawing.Point(267, 66);
this.ServerPingTypeLabel.Name = "ServerPingTypeLabel";
this.ServerPingTypeLabel.Size = new System.Drawing.Size(89, 12);
this.ServerPingTypeLabel.TabIndex = 16;
this.ServerPingTypeLabel.Text = "ServerPingType";
//
// TCPingRadioBtn
//
this.TCPingRadioBtn.AutoSize = true;
this.TCPingRadioBtn.Location = new System.Drawing.Point(332, 85);
this.TCPingRadioBtn.Name = "TCPingRadioBtn";
this.TCPingRadioBtn.Size = new System.Drawing.Size(59, 16);
this.TCPingRadioBtn.TabIndex = 15;
this.TCPingRadioBtn.TabStop = true;
this.TCPingRadioBtn.Text = "TCPing";
this.TCPingRadioBtn.UseVisualStyleBackColor = true;
//
// ICMPingRadioBtn
//
this.ICMPingRadioBtn.AutoSize = true;
this.ICMPingRadioBtn.Location = new System.Drawing.Point(268, 85);
this.ICMPingRadioBtn.Name = "ICMPingRadioBtn";
this.ICMPingRadioBtn.Size = new System.Drawing.Size(65, 16);
this.ICMPingRadioBtn.TabIndex = 14;
this.ICMPingRadioBtn.TabStop = true;
this.ICMPingRadioBtn.Text = "ICMPing";
this.ICMPingRadioBtn.UseVisualStyleBackColor = true;
//
// PortGroupBox
//
this.PortGroupBox.Controls.Add(this.Socks5PortLabel);
@@ -252,7 +294,7 @@ namespace Netch.Forms
// ResolveServerHostnameCheckBox
//
this.ResolveServerHostnameCheckBox.AutoSize = true;
this.ResolveServerHostnameCheckBox.Location = new System.Drawing.Point(266, 42);
this.ResolveServerHostnameCheckBox.Location = new System.Drawing.Point(267, 37);
this.ResolveServerHostnameCheckBox.Name = "ResolveServerHostnameCheckBox";
this.ResolveServerHostnameCheckBox.Size = new System.Drawing.Size(162, 16);
this.ResolveServerHostnameCheckBox.TabIndex = 2;
@@ -276,32 +318,39 @@ namespace Netch.Forms
this.ProfileCountTextBox.TabIndex = 4;
this.ProfileCountTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// TcpingAtStartedCheckBox
// StartedPingLabel
//
this.TcpingAtStartedCheckBox.AutoSize = true;
this.TcpingAtStartedCheckBox.Location = new System.Drawing.Point(15, 186);
this.TcpingAtStartedCheckBox.Name = "TcpingAtStartedCheckBox";
this.TcpingAtStartedCheckBox.Size = new System.Drawing.Size(156, 16);
this.TcpingAtStartedCheckBox.TabIndex = 5;
this.TcpingAtStartedCheckBox.Text = "Delay test after start";
this.TcpingAtStartedCheckBox.UseVisualStyleBackColor = true;
this.StartedPingLabel.AutoSize = true;
this.StartedPingLabel.Location = new System.Drawing.Point(12, 187);
this.StartedPingLabel.Name = "StartedPingLabel";
this.StartedPingLabel.Size = new System.Drawing.Size(137, 12);
this.StartedPingLabel.TabIndex = 5;
this.StartedPingLabel.Text = "Delay test after start";
//
// DetectionIntervalLabel
// DetectionTickLabel
//
this.DetectionIntervalLabel.AutoSize = true;
this.DetectionIntervalLabel.Location = new System.Drawing.Point(228, 187);
this.DetectionIntervalLabel.Name = "DetectionIntervalLabel";
this.DetectionIntervalLabel.Size = new System.Drawing.Size(143, 12);
this.DetectionIntervalLabel.TabIndex = 6;
this.DetectionIntervalLabel.Text = "Detection interval(sec)";
this.DetectionTickLabel.AutoSize = true;
this.DetectionTickLabel.Location = new System.Drawing.Point(225, 160);
this.DetectionTickLabel.Name = "DetectionTickLabel";
this.DetectionTickLabel.Size = new System.Drawing.Size(119, 12);
this.DetectionTickLabel.TabIndex = 6;
this.DetectionTickLabel.Text = "Detection Tick(sec)";
//
// DetectionIntervalTextBox
// StartedPingIntervalTextBox
//
this.DetectionIntervalTextBox.Location = new System.Drawing.Point(366, 184);
this.DetectionIntervalTextBox.Name = "DetectionIntervalTextBox";
this.DetectionIntervalTextBox.Size = new System.Drawing.Size(68, 21);
this.DetectionIntervalTextBox.TabIndex = 7;
this.DetectionIntervalTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.StartedPingIntervalTextBox.Location = new System.Drawing.Point(177, 184);
this.StartedPingIntervalTextBox.Name = "StartedPingIntervalTextBox";
this.StartedPingIntervalTextBox.Size = new System.Drawing.Size(68, 21);
this.StartedPingIntervalTextBox.TabIndex = 7;
this.StartedPingIntervalTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// DetectionTickTextBox
//
this.DetectionTickTextBox.Location = new System.Drawing.Point(366, 157);
this.DetectionTickTextBox.Name = "DetectionTickTextBox";
this.DetectionTickTextBox.Size = new System.Drawing.Size(68, 21);
this.DetectionTickTextBox.TabIndex = 7;
this.DetectionTickTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// STUNServerLabel
//
@@ -333,7 +382,7 @@ namespace Netch.Forms
//
this.AclAddrTextBox.Location = new System.Drawing.Point(120, 245);
this.AclAddrTextBox.Name = "AclAddrTextBox";
this.AclAddrTextBox.Size = new System.Drawing.Size(315, 21);
this.AclAddrTextBox.Size = new System.Drawing.Size(314, 21);
this.AclAddrTextBox.TabIndex = 11;
this.AclAddrTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
@@ -358,9 +407,12 @@ namespace Netch.Forms
// NFTabPage
//
this.NFTabPage.BackColor = System.Drawing.SystemColors.ButtonFace;
this.NFTabPage.Controls.Add(this.NoProxyForTcpCheckBox);
this.NFTabPage.Controls.Add(this.NoProxyForUdpCheckBox);
this.NFTabPage.Controls.Add(this.ModifySystemDNSCheckBox);
this.NFTabPage.Controls.Add(this.ModifiedDNSLabel);
this.NFTabPage.Controls.Add(this.ModifiedDNSTextBox);
this.NFTabPage.Controls.Add(this.RedirectorSSCheckBox);
this.NFTabPage.Location = new System.Drawing.Point(4, 25);
this.NFTabPage.Name = "NFTabPage";
this.NFTabPage.Padding = new System.Windows.Forms.Padding(3);
@@ -368,6 +420,28 @@ namespace Netch.Forms
this.NFTabPage.TabIndex = 1;
this.NFTabPage.Text = "Process Mode";
//
// NoProxyForTcpCheckBox
//
this.NoProxyForTcpCheckBox.AutoSize = true;
this.NoProxyForTcpCheckBox.Location = new System.Drawing.Point(8, 82);
this.NoProxyForTcpCheckBox.Name = "NoProxyForTcpCheckBox";
this.NoProxyForTcpCheckBox.Size = new System.Drawing.Size(120, 16);
this.NoProxyForTcpCheckBox.TabIndex = 4;
this.NoProxyForTcpCheckBox.Text = "No Proxy for Tcp";
this.NoProxyForTcpCheckBox.UseVisualStyleBackColor = true;
this.NoProxyForTcpCheckBox.CheckedChanged += new System.EventHandler(this.NoProxyForTcpCheckBox_CheckedChanged);
//
// NoProxyForUdpCheckBox
//
this.NoProxyForUdpCheckBox.AutoSize = true;
this.NoProxyForUdpCheckBox.Location = new System.Drawing.Point(8, 60);
this.NoProxyForUdpCheckBox.Name = "NoProxyForUdpCheckBox";
this.NoProxyForUdpCheckBox.Size = new System.Drawing.Size(120, 16);
this.NoProxyForUdpCheckBox.TabIndex = 3;
this.NoProxyForUdpCheckBox.Text = "No Proxy for Udp";
this.NoProxyForUdpCheckBox.UseVisualStyleBackColor = true;
this.NoProxyForUdpCheckBox.CheckedChanged += new System.EventHandler(this.NoProxyForUdpCheckBox_CheckedChanged);
//
// ModifySystemDNSCheckBox
//
this.ModifySystemDNSCheckBox.AutoSize = true;
@@ -377,12 +451,11 @@ namespace Netch.Forms
this.ModifySystemDNSCheckBox.TabIndex = 0;
this.ModifySystemDNSCheckBox.Text = "Modify System DNS";
this.ModifySystemDNSCheckBox.UseVisualStyleBackColor = true;
this.ModifySystemDNSCheckBox.CheckedChanged += new System.EventHandler(this.ModifySystemDNSCheckBox_CheckedChanged);
//
// ModifiedDNSLabel
//
this.ModifiedDNSLabel.AutoSize = true;
this.ModifiedDNSLabel.Location = new System.Drawing.Point(24, 41);
this.ModifiedDNSLabel.Location = new System.Drawing.Point(223, 17);
this.ModifiedDNSLabel.Name = "ModifiedDNSLabel";
this.ModifiedDNSLabel.Size = new System.Drawing.Size(23, 12);
this.ModifiedDNSLabel.TabIndex = 2;
@@ -390,12 +463,23 @@ namespace Netch.Forms
//
// ModifiedDNSTextBox
//
this.ModifiedDNSTextBox.Location = new System.Drawing.Point(99, 38);
this.ModifiedDNSTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Enabled", this.ModifySystemDNSCheckBox, "Checked", true));
this.ModifiedDNSTextBox.Location = new System.Drawing.Point(264, 14);
this.ModifiedDNSTextBox.Name = "ModifiedDNSTextBox";
this.ModifiedDNSTextBox.Size = new System.Drawing.Size(194, 21);
this.ModifiedDNSTextBox.TabIndex = 1;
this.ModifiedDNSTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// RedirectorSSCheckBox
//
this.RedirectorSSCheckBox.AutoSize = true;
this.RedirectorSSCheckBox.Location = new System.Drawing.Point(8, 38);
this.RedirectorSSCheckBox.Name = "RedirectorSSCheckBox";
this.RedirectorSSCheckBox.Size = new System.Drawing.Size(102, 16);
this.RedirectorSSCheckBox.TabIndex = 0;
this.RedirectorSSCheckBox.Text = "Redirector SS";
this.RedirectorSSCheckBox.UseVisualStyleBackColor = true;
//
// TAPTabPage
//
this.TAPTabPage.BackColor = System.Drawing.SystemColors.ButtonFace;
@@ -491,6 +575,7 @@ namespace Netch.Forms
//
// TUNTAPDNSTextBox
//
this.TUNTAPDNSTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Enabled", this.UseCustomDNSCheckBox, "Checked", true));
this.TUNTAPDNSTextBox.Location = new System.Drawing.Point(120, 110);
this.TUNTAPDNSTextBox.Name = "TUNTAPDNSTextBox";
this.TUNTAPDNSTextBox.Size = new System.Drawing.Size(294, 21);
@@ -729,7 +814,7 @@ namespace Netch.Forms
this.OtherTabPage.Controls.Add(this.RunAtStartupCheckBox);
this.OtherTabPage.Controls.Add(this.CheckUpdateWhenOpenedCheckBox);
this.OtherTabPage.Controls.Add(this.CheckBetaUpdateCheckBox);
this.OtherTabPage.Controls.Add(this.UpdateSubscribeatWhenOpenedCheckBox);
this.OtherTabPage.Controls.Add(this.UpdateServersWhenOpenedCheckBox);
this.OtherTabPage.Location = new System.Drawing.Point(4, 25);
this.OtherTabPage.Name = "OtherTabPage";
this.OtherTabPage.Padding = new System.Windows.Forms.Padding(3);
@@ -751,7 +836,7 @@ namespace Netch.Forms
// StopWhenExitedCheckBox
//
this.StopWhenExitedCheckBox.AutoSize = true;
this.StopWhenExitedCheckBox.Location = new System.Drawing.Point(200, 7);
this.StopWhenExitedCheckBox.Location = new System.Drawing.Point(200, 6);
this.StopWhenExitedCheckBox.Name = "StopWhenExitedCheckBox";
this.StopWhenExitedCheckBox.Size = new System.Drawing.Size(120, 16);
this.StopWhenExitedCheckBox.TabIndex = 1;
@@ -762,7 +847,7 @@ namespace Netch.Forms
// StartWhenOpenedCheckBox
//
this.StartWhenOpenedCheckBox.AutoSize = true;
this.StartWhenOpenedCheckBox.Location = new System.Drawing.Point(6, 33);
this.StartWhenOpenedCheckBox.Location = new System.Drawing.Point(6, 28);
this.StartWhenOpenedCheckBox.Name = "StartWhenOpenedCheckBox";
this.StartWhenOpenedCheckBox.Size = new System.Drawing.Size(126, 16);
this.StartWhenOpenedCheckBox.TabIndex = 2;
@@ -773,7 +858,7 @@ namespace Netch.Forms
// MinimizeWhenStartedCheckBox
//
this.MinimizeWhenStartedCheckBox.AutoSize = true;
this.MinimizeWhenStartedCheckBox.Location = new System.Drawing.Point(200, 33);
this.MinimizeWhenStartedCheckBox.Location = new System.Drawing.Point(200, 28);
this.MinimizeWhenStartedCheckBox.Name = "MinimizeWhenStartedCheckBox";
this.MinimizeWhenStartedCheckBox.Size = new System.Drawing.Size(150, 16);
this.MinimizeWhenStartedCheckBox.TabIndex = 3;
@@ -783,7 +868,7 @@ namespace Netch.Forms
// RunAtStartupCheckBox
//
this.RunAtStartupCheckBox.AutoSize = true;
this.RunAtStartupCheckBox.Location = new System.Drawing.Point(6, 60);
this.RunAtStartupCheckBox.Location = new System.Drawing.Point(6, 50);
this.RunAtStartupCheckBox.Name = "RunAtStartupCheckBox";
this.RunAtStartupCheckBox.Size = new System.Drawing.Size(108, 16);
this.RunAtStartupCheckBox.TabIndex = 4;
@@ -793,7 +878,7 @@ namespace Netch.Forms
// CheckUpdateWhenOpenedCheckBox
//
this.CheckUpdateWhenOpenedCheckBox.AutoSize = true;
this.CheckUpdateWhenOpenedCheckBox.Location = new System.Drawing.Point(200, 60);
this.CheckUpdateWhenOpenedCheckBox.Location = new System.Drawing.Point(200, 50);
this.CheckUpdateWhenOpenedCheckBox.Name = "CheckUpdateWhenOpenedCheckBox";
this.CheckUpdateWhenOpenedCheckBox.Size = new System.Drawing.Size(168, 16);
this.CheckUpdateWhenOpenedCheckBox.TabIndex = 5;
@@ -804,7 +889,7 @@ namespace Netch.Forms
// CheckBetaUpdateCheckBox
//
this.CheckBetaUpdateCheckBox.AutoSize = true;
this.CheckBetaUpdateCheckBox.Location = new System.Drawing.Point(200, 87);
this.CheckBetaUpdateCheckBox.Location = new System.Drawing.Point(200, 72);
this.CheckBetaUpdateCheckBox.Name = "CheckBetaUpdateCheckBox";
this.CheckBetaUpdateCheckBox.Size = new System.Drawing.Size(126, 16);
this.CheckBetaUpdateCheckBox.TabIndex = 6;
@@ -812,16 +897,16 @@ namespace Netch.Forms
this.CheckBetaUpdateCheckBox.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.CheckBetaUpdateCheckBox.UseVisualStyleBackColor = true;
//
// UpdateSubscribeatWhenOpenedCheckBox
// UpdateServersWhenOpenedCheckBox
//
this.UpdateSubscribeatWhenOpenedCheckBox.AutoSize = true;
this.UpdateSubscribeatWhenOpenedCheckBox.Location = new System.Drawing.Point(200, 109);
this.UpdateSubscribeatWhenOpenedCheckBox.Name = "UpdateSubscribeatWhenOpenedCheckBox";
this.UpdateSubscribeatWhenOpenedCheckBox.Size = new System.Drawing.Size(204, 16);
this.UpdateSubscribeatWhenOpenedCheckBox.TabIndex = 7;
this.UpdateSubscribeatWhenOpenedCheckBox.Text = "Update subscribeat when opened";
this.UpdateSubscribeatWhenOpenedCheckBox.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.UpdateSubscribeatWhenOpenedCheckBox.UseVisualStyleBackColor = true;
this.UpdateServersWhenOpenedCheckBox.AutoSize = true;
this.UpdateServersWhenOpenedCheckBox.Location = new System.Drawing.Point(200, 94);
this.UpdateServersWhenOpenedCheckBox.Name = "UpdateServersWhenOpenedCheckBox";
this.UpdateServersWhenOpenedCheckBox.Size = new System.Drawing.Size(180, 16);
this.UpdateServersWhenOpenedCheckBox.TabIndex = 7;
this.UpdateServersWhenOpenedCheckBox.Text = "Update Servers when opened";
this.UpdateServersWhenOpenedCheckBox.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.UpdateServersWhenOpenedCheckBox.UseVisualStyleBackColor = true;
//
// AioDNSTabPage
//
@@ -859,7 +944,7 @@ namespace Netch.Forms
// ChinaDNSLabel
//
this.ChinaDNSLabel.AutoSize = true;
this.ChinaDNSLabel.Location = new System.Drawing.Point(16, 73);
this.ChinaDNSLabel.Location = new System.Drawing.Point(16, 64);
this.ChinaDNSLabel.Name = "ChinaDNSLabel";
this.ChinaDNSLabel.Size = new System.Drawing.Size(59, 12);
this.ChinaDNSLabel.TabIndex = 2;
@@ -867,7 +952,7 @@ namespace Netch.Forms
//
// ChinaDNSTextBox
//
this.ChinaDNSTextBox.Location = new System.Drawing.Point(147, 70);
this.ChinaDNSTextBox.Location = new System.Drawing.Point(147, 61);
this.ChinaDNSTextBox.Name = "ChinaDNSTextBox";
this.ChinaDNSTextBox.Size = new System.Drawing.Size(201, 21);
this.ChinaDNSTextBox.TabIndex = 3;
@@ -876,7 +961,7 @@ namespace Netch.Forms
// OtherDNSLabel
//
this.OtherDNSLabel.AutoSize = true;
this.OtherDNSLabel.Location = new System.Drawing.Point(16, 109);
this.OtherDNSLabel.Location = new System.Drawing.Point(16, 103);
this.OtherDNSLabel.Name = "OtherDNSLabel";
this.OtherDNSLabel.Size = new System.Drawing.Size(59, 12);
this.OtherDNSLabel.TabIndex = 4;
@@ -884,7 +969,7 @@ namespace Netch.Forms
//
// OtherDNSTextBox
//
this.OtherDNSTextBox.Location = new System.Drawing.Point(147, 106);
this.OtherDNSTextBox.Location = new System.Drawing.Point(147, 100);
this.OtherDNSTextBox.Name = "OtherDNSTextBox";
this.OtherDNSTextBox.Size = new System.Drawing.Size(201, 21);
this.OtherDNSTextBox.TabIndex = 5;
@@ -892,7 +977,7 @@ namespace Netch.Forms
//
// ControlButton
//
this.ControlButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ControlButton.Anchor = ((System.Windows.Forms.AnchorStyles) ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ControlButton.Location = new System.Drawing.Point(397, 363);
this.ControlButton.Name = "ControlButton";
this.ControlButton.Size = new System.Drawing.Size(75, 23);
@@ -916,18 +1001,19 @@ namespace Netch.Forms
//
// SettingForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.AutoSize = true;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.ClientSize = new System.Drawing.Size(480, 400);
this.Controls.Add(this.flowLayoutPanel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Icon = ((System.Drawing.Icon) (resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "SettingForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Settings";
this.Load += new System.EventHandler(this.SettingForm2_Load);
this.Load += new System.EventHandler(this.SettingForm_Load);
this.TabControl.ResumeLayout(false);
this.GeneralTabPage.ResumeLayout(false);
this.GeneralTabPage.PerformLayout();
@@ -949,8 +1035,9 @@ namespace Netch.Forms
this.flowLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.TextBox StartedPingIntervalTextBox;
private System.Windows.Forms.CheckBox NoProxyForTcpCheckBox;
#endregion
@@ -987,7 +1074,7 @@ namespace Netch.Forms
private System.Windows.Forms.Button ControlButton;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.TabPage OtherTabPage;
private System.Windows.Forms.CheckBox UpdateSubscribeatWhenOpenedCheckBox;
private System.Windows.Forms.CheckBox UpdateServersWhenOpenedCheckBox;
private System.Windows.Forms.CheckBox RunAtStartupCheckBox;
private System.Windows.Forms.CheckBox MinimizeWhenStartedCheckBox;
private System.Windows.Forms.CheckBox CheckBetaUpdateCheckBox;
@@ -999,9 +1086,9 @@ namespace Netch.Forms
private System.Windows.Forms.ComboBox LanguageComboBox;
private System.Windows.Forms.TextBox AclAddrTextBox;
private System.Windows.Forms.Label AclLabel;
private System.Windows.Forms.Label DetectionIntervalLabel;
private System.Windows.Forms.TextBox DetectionIntervalTextBox;
private System.Windows.Forms.CheckBox TcpingAtStartedCheckBox;
private System.Windows.Forms.Label DetectionTickLabel;
private System.Windows.Forms.TextBox DetectionTickTextBox;
private System.Windows.Forms.Label StartedPingLabel;
private System.Windows.Forms.Label STUNServerLabel;
private System.Windows.Forms.ComboBox STUN_ServerComboBox;
private System.Windows.Forms.Label ProfileCountLabel;
@@ -1031,5 +1118,10 @@ namespace Netch.Forms
private System.Windows.Forms.TextBox ChinaDNSTextBox;
private System.Windows.Forms.TextBox ModifiedDNSTextBox;
private System.Windows.Forms.Label ModifiedDNSLabel;
private System.Windows.Forms.CheckBox RedirectorSSCheckBox;
private System.Windows.Forms.CheckBox NoProxyForUdpCheckBox;
private System.Windows.Forms.Label ServerPingTypeLabel;
private System.Windows.Forms.RadioButton TCPingRadioBtn;
private System.Windows.Forms.RadioButton ICMPingRadioBtn;
}
}

View File

@@ -1,17 +1,20 @@
using Netch.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
using TaskScheduler;
using Netch.Utils;
namespace Netch.Forms
{
public partial class SettingForm : Form
{
private readonly Dictionary<Control, Func<string, bool>> _checkActions = new();
private readonly Dictionary<Control, Action<Control>> _saveActions = new();
public SettingForm()
{
InitializeComponent();
@@ -19,9 +22,9 @@ namespace Netch.Forms
InitValue();
}
private void SettingForm2_Load(object sender, EventArgs e)
private void SettingForm_Load(object sender, EventArgs e)
{
TUNTAPUseCustomDNSCheckBox_CheckedChanged(null, null);
Task.Run(() => BeginInvoke(new Action(() => UseFakeDNSCheckBox.Visible = Global.Flags.SupportFakeDns)));
}
@@ -30,17 +33,17 @@ namespace Netch.Forms
#region General
BindTextBox<ushort>(Socks5PortTextBox,
p => CheckPort("Socks5", p, Global.Settings.Socks5LocalPort),
p => p.ToString() != HTTPPortTextBox.Text && p.ToString() != RedirectorTextBox.Text,
p => Global.Settings.Socks5LocalPort = p,
Global.Settings.Socks5LocalPort);
BindTextBox<ushort>(HTTPPortTextBox,
p => CheckPort("HTTP", p, Global.Settings.HTTPLocalPort),
p => p.ToString() != Socks5PortTextBox.Text && p.ToString() != RedirectorTextBox.Text,
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);
p => p.ToString() != Socks5PortTextBox.Text && p.ToString() != HTTPPortTextBox.Text,
p => Global.Settings.RedirectorTCPPort = p,
Global.Settings.RedirectorTCPPort);
BindCheckBox(AllowDevicesCheckBox,
c => Global.Settings.LocalAddress = AllowDevicesCheckBox.Checked ? "0.0.0.0" : "127.0.0.1",
Global.Settings.LocalAddress switch
@@ -50,7 +53,6 @@ namespace Netch.Forms
_ => false
});
BindCheckBox(BootShadowsocksFromDLLCheckBox,
c => Global.Settings.BootShadowsocksFromDLL = c,
Global.Settings.BootShadowsocksFromDLL);
@@ -58,17 +60,26 @@ namespace Netch.Forms
c => Global.Settings.ResolveServerHostname = c,
Global.Settings.ResolveServerHostname);
BindRadioBox(ICMPingRadioBtn,
_ => { },
!Global.Settings.ServerTCPing);
BindRadioBox(TCPingRadioBtn,
c => Global.Settings.ServerTCPing = c,
Global.Settings.ServerTCPing);
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);
BindTextBox<int>(DetectionTickTextBox,
i => ServerHelper.DelayTestHelper.Range.InRange(i),
i => Global.Settings.DetectionTick = i,
Global.Settings.DetectionTick);
BindTextBox<int>(StartedPingIntervalTextBox,
_ => true,
i => Global.Settings.StartedPingInterval = i,
Global.Settings.StartedPingInterval);
InitSTUN();
@@ -94,6 +105,18 @@ namespace Netch.Forms
s => Global.Settings.ModifiedDNS = s,
Global.Settings.ModifiedDNS);
BindCheckBox(RedirectorSSCheckBox,
s => Global.Settings.RedirectorSS = s,
Global.Settings.RedirectorSS);
BindCheckBox(NoProxyForUdpCheckBox,
s => Global.Settings.ProcessNoProxyForUdp = s,
Global.Settings.ProcessNoProxyForUdp);
BindCheckBox(NoProxyForTcpCheckBox,
s => Global.Settings.ProcessNoProxyForTcp = s,
Global.Settings.ProcessNoProxyForTcp);
#endregion
#region TUN/TAP
@@ -113,11 +136,14 @@ namespace Netch.Forms
BindCheckBox(UseCustomDNSCheckBox,
b => { Global.Settings.TUNTAP.UseCustomDNS = b; },
Global.Settings.TUNTAP.UseCustomDNS);
TUNTAPUseCustomDNSCheckBox_CheckedChanged(null, null);
BindTextBox(TUNTAPDNSTextBox,
s => !UseCustomDNSCheckBox.Checked || DNS.TrySplit(s, out _, 2),
s => Global.Settings.TUNTAP.DNS = DNS.Split(s).ToList(),
s =>
{
if (UseCustomDNSCheckBox.Checked)
Global.Settings.TUNTAP.DNS = DNS.Split(s).ToList();
},
DNS.Join(Global.Settings.TUNTAP.DNS));
BindCheckBox(ProxyDNSCheckBox,
@@ -212,9 +238,9 @@ namespace Netch.Forms
b => Global.Settings.CheckBetaUpdate = b,
Global.Settings.CheckBetaUpdate);
BindCheckBox(UpdateSubscribeatWhenOpenedCheckBox,
b => Global.Settings.UpdateSubscribeatWhenOpened = b,
Global.Settings.UpdateSubscribeatWhenOpened);
BindCheckBox(UpdateServersWhenOpenedCheckBox,
b => Global.Settings.UpdateServersWhenOpened = b,
Global.Settings.UpdateServersWhenOpened);
#endregion
@@ -240,21 +266,14 @@ namespace Netch.Forms
private void TUNTAPUseCustomDNSCheckBox_CheckedChanged(object sender, EventArgs e)
{
TUNTAPDNSTextBox.Enabled = UseCustomDNSCheckBox.Checked;
if (UseCustomDNSCheckBox.Checked)
{
TUNTAPDNSTextBox.Text = Global.Settings.TUNTAP.DNS.Any()
? DNS.Join(Global.Settings.TUNTAP.DNS)
: "1.1.1.1";
}
else
{
TUNTAPDNSTextBox.Text = "AioDNS";
}
}
private void InitSTUN()
{
try
@@ -279,114 +298,68 @@ namespace Netch.Forms
private void ControlButton_Click(object sender, EventArgs e)
{
if (!_checkActions.All(pair => pair.Value.Invoke(pair.Key.Text)))
return;
Utils.Utils.ComponentIterator(this, component => Utils.Utils.ChangeControlForeColor(component, Color.Black));
#region Check
#region Behavior
// STUN
string stunServer;
int stunServerPort;
try
var flag = true;
foreach (var pair in _checkActions.Where(pair => !pair.Value.Invoke(pair.Key.Text)))
{
var stun = STUN_ServerComboBox.Text.Split(':');
stunServer = stun[0];
stunServerPort = 3478;
if (stun.Length > 1)
stunServerPort = int.Parse(stun[1]);
if (stunServerPort <= 0)
{
throw new FormatException();
}
Utils.Utils.ChangeControlForeColor(pair.Key, Color.Red);
flag = false;
}
catch (FormatException)
{
MessageBoxX.Show(i18N.Translate("STUN_ServerPort value illegal. Try again."));
if (!flag)
return;
}
#endregion
#region CheckSTUN
var errFlag = false;
var stunServer = string.Empty;
ushort stunServerPort = 3478;
var stun = STUN_ServerComboBox.Text.Split(':');
if (stun.Any())
{
stunServer = stun[0];
if (stun.Length > 1)
if (!ushort.TryParse(stun[1], out stunServerPort))
errFlag = true;
}
else
{
errFlag = true;
}
if (errFlag)
{
Utils.Utils.ChangeControlForeColor(STUN_ServerComboBox, Color.Red);
return;
}
#endregion
#region Save
foreach (var pair in _saveActions)
{
pair.Value.Invoke(pair.Key);
}
Global.Settings.STUN_Server = stunServer;
Global.Settings.STUN_Server_Port = stunServerPort;
Global.Settings.Language = LanguageComboBox.Text;
#endregion
#region Register Startup Item
var scheduler = new TaskSchedulerClass();
scheduler.Connect();
var folder = scheduler.GetFolder("\\");
var taskIsExists = false;
try
{
folder.GetTask("Netch Startup");
taskIsExists = true;
}
catch (Exception)
{
// ignored
}
if (Global.Settings.RunAtStartup)
{
if (taskIsExists)
folder.DeleteTask("Netch Startup", 0);
var task = scheduler.NewTask(0);
task.RegistrationInfo.Author = "Netch";
task.RegistrationInfo.Description = "Netch run at startup.";
task.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;
task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);
var action = (IExecAction) task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
action.Path = Application.ExecutablePath;
task.Settings.ExecutionTimeLimit = "PT0S";
task.Settings.DisallowStartIfOnBatteries = false;
task.Settings.RunOnlyIfIdle = false;
folder.RegisterTaskDefinition("Netch Startup", task, (int) _TASK_CREATION.TASK_CREATE, null, null,
_TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");
}
else
{
if (taskIsExists)
folder.DeleteTask("Netch Startup", 0);
}
#endregion
Utils.Utils.RegisterNetchStartupItem();
Configuration.Save();
MessageBoxX.Show(i18N.Translate("Saved"));
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)
{
try
@@ -441,17 +414,22 @@ namespace Netch.Forms
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>>();
private void ModifySystemDNSCheckBox_CheckedChanged(object sender, EventArgs e)
private void BindRadioBox(RadioButton control, Action<bool> save, bool value)
{
ModifiedDNSTextBox.Enabled = ModifySystemDNSCheckBox.Checked;
control.Checked = value;
_saveActions.Add(control, c => save.Invoke(((RadioButton) c).Checked));
}
private void NoProxyForUdpCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (NoProxyForUdpCheckBox.Checked) NoProxyForTcpCheckBox.Checked = false;
}
private void NoProxyForTcpCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (NoProxyForTcpCheckBox.Checked) NoProxyForUdpCheckBox.Checked = false;
}
}
}

View File

@@ -32,7 +32,7 @@
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SubscribeForm));
this.AddSubscriptionBox = new System.Windows.Forms.GroupBox();
this.UserAgentTextBox = new System.Windows.Forms.TextBox();
this.ClearButton = new System.Windows.Forms.Button();
this.UnselectButton = new System.Windows.Forms.Button();
this.AddButton = new System.Windows.Forms.Button();
this.UserAgentLabel = new System.Windows.Forms.Label();
this.LinkTextBox = new System.Windows.Forms.TextBox();
@@ -40,25 +40,24 @@
this.RemarkTextBox = new System.Windows.Forms.TextBox();
this.RemarkLabel = new System.Windows.Forms.Label();
this.SubscribeLinkListView = new System.Windows.Forms.ListView();
this.EnableColumnHeader = new System.Windows.Forms.ColumnHeader();
this.RemarkColumnHeader = new System.Windows.Forms.ColumnHeader();
this.LinkColumnHeader = new System.Windows.Forms.ColumnHeader();
this.UserAgentHeader = new System.Windows.Forms.ColumnHeader();
this.pContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.DeleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteServerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.CopyLinkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.UseSelectedServerCheckBox = new System.Windows.Forms.CheckBox();
this.MainTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.ControlsPanel = new System.Windows.Forms.Panel();
this.AddSubscriptionBox.SuspendLayout();
this.pContextMenuStrip.SuspendLayout();
this.MainTableLayoutPanel.SuspendLayout();
this.ControlsPanel.SuspendLayout();
this.SuspendLayout();
//
// AddSubscriptionBox
//
this.AddSubscriptionBox.Controls.Add(this.UserAgentTextBox);
this.AddSubscriptionBox.Controls.Add(this.ClearButton);
this.AddSubscriptionBox.Controls.Add(this.UnselectButton);
this.AddSubscriptionBox.Controls.Add(this.AddButton);
this.AddSubscriptionBox.Controls.Add(this.UserAgentLabel);
this.AddSubscriptionBox.Controls.Add(this.LinkTextBox);
@@ -66,9 +65,9 @@
this.AddSubscriptionBox.Controls.Add(this.RemarkTextBox);
this.AddSubscriptionBox.Controls.Add(this.RemarkLabel);
this.AddSubscriptionBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.AddSubscriptionBox.Location = new System.Drawing.Point(8, 214);
this.AddSubscriptionBox.Location = new System.Drawing.Point(8, 248);
this.AddSubscriptionBox.Name = "AddSubscriptionBox";
this.AddSubscriptionBox.Size = new System.Drawing.Size(668, 141);
this.AddSubscriptionBox.Size = new System.Drawing.Size(668, 135);
this.AddSubscriptionBox.TabIndex = 1;
this.AddSubscriptionBox.TabStop = false;
//
@@ -79,15 +78,15 @@
this.UserAgentTextBox.Size = new System.Drawing.Size(545, 23);
this.UserAgentTextBox.TabIndex = 6;
//
// ClearButton
// UnselectButton
//
this.ClearButton.Location = new System.Drawing.Point(448, 103);
this.ClearButton.Name = "ClearButton";
this.ClearButton.Size = new System.Drawing.Size(87, 26);
this.ClearButton.TabIndex = 7;
this.ClearButton.Text = "Unselect";
this.ClearButton.UseVisualStyleBackColor = true;
this.ClearButton.Click += new System.EventHandler(this.ClearButton_Click);
this.UnselectButton.Location = new System.Drawing.Point(448, 103);
this.UnselectButton.Name = "UnselectButton";
this.UnselectButton.Size = new System.Drawing.Size(87, 26);
this.UnselectButton.TabIndex = 7;
this.UnselectButton.Text = "Unselect";
this.UnselectButton.UseVisualStyleBackColor = true;
this.UnselectButton.Click += new System.EventHandler(this.UnselectButton_Click);
//
// AddButton
//
@@ -95,7 +94,7 @@
this.AddButton.Name = "AddButton";
this.AddButton.Size = new System.Drawing.Size(113, 26);
this.AddButton.TabIndex = 7;
this.AddButton.Text = "Add / Modify";
this.AddButton.Text = "Add";
this.AddButton.UseVisualStyleBackColor = true;
this.AddButton.Click += new System.EventHandler(this.AddButton_Click);
//
@@ -143,19 +142,29 @@
// SubscribeLinkListView
//
this.SubscribeLinkListView.AllowColumnReorder = true;
this.SubscribeLinkListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {this.RemarkColumnHeader, this.LinkColumnHeader, this.UserAgentHeader});
this.SubscribeLinkListView.CheckBoxes = true;
this.SubscribeLinkListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[]
{
this.EnableColumnHeader, this.RemarkColumnHeader, this.LinkColumnHeader, this.UserAgentHeader
});
this.SubscribeLinkListView.Dock = System.Windows.Forms.DockStyle.Fill;
this.SubscribeLinkListView.FullRowSelect = true;
this.SubscribeLinkListView.HideSelection = false;
this.SubscribeLinkListView.Location = new System.Drawing.Point(8, 8);
this.SubscribeLinkListView.MultiSelect = false;
this.SubscribeLinkListView.Name = "SubscribeLinkListView";
this.SubscribeLinkListView.Size = new System.Drawing.Size(668, 200);
this.SubscribeLinkListView.Size = new System.Drawing.Size(668, 234);
this.SubscribeLinkListView.TabIndex = 0;
this.SubscribeLinkListView.UseCompatibleStateImageBehavior = false;
this.SubscribeLinkListView.View = System.Windows.Forms.View.Details;
this.SubscribeLinkListView.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.SubscribeLinkListView_ItemChecked);
this.SubscribeLinkListView.SelectedIndexChanged += new System.EventHandler(this.SubscribeLinkListView_SelectedIndexChanged);
this.SubscribeLinkListView.MouseUp += new System.Windows.Forms.MouseEventHandler(this.SubscribeLinkListView_MouseUp);
//
// EnableColumnHeader
//
this.EnableColumnHeader.Text = "Status";
//
// RemarkColumnHeader
//
this.RemarkColumnHeader.Text = "Remark";
@@ -164,7 +173,7 @@
// LinkColumnHeader
//
this.LinkColumnHeader.Text = "Link";
this.LinkColumnHeader.Width = 400;
this.LinkColumnHeader.Width = 364;
//
// UserAgentHeader
//
@@ -173,62 +182,51 @@
//
// pContextMenuStrip
//
this.pContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this.DeleteToolStripMenuItem, this.CopyLinkToolStripMenuItem});
this.pContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[]
{
this.DeleteToolStripMenuItem, this.deleteServerToolStripMenuItem, this.CopyLinkToolStripMenuItem
});
this.pContextMenuStrip.Name = "pContextMenuStrip";
this.pContextMenuStrip.Size = new System.Drawing.Size(130, 48);
this.pContextMenuStrip.Size = new System.Drawing.Size(151, 70);
//
// DeleteToolStripMenuItem
//
this.DeleteToolStripMenuItem.Name = "DeleteToolStripMenuItem";
this.DeleteToolStripMenuItem.Size = new System.Drawing.Size(129, 22);
this.DeleteToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.DeleteToolStripMenuItem.Text = "Delete";
this.DeleteToolStripMenuItem.Click += new System.EventHandler(this.DeleteToolStripMenuItem_Click);
//
// deleteServerToolStripMenuItem
//
this.deleteServerToolStripMenuItem.Name = "deleteServerToolStripMenuItem";
this.deleteServerToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.deleteServerToolStripMenuItem.Text = "DeleteServer";
this.deleteServerToolStripMenuItem.Click += new System.EventHandler(this.deleteServerToolStripMenuItem_Click);
//
// CopyLinkToolStripMenuItem
//
this.CopyLinkToolStripMenuItem.Name = "CopyLinkToolStripMenuItem";
this.CopyLinkToolStripMenuItem.Size = new System.Drawing.Size(129, 22);
this.CopyLinkToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.CopyLinkToolStripMenuItem.Text = "CopyLink";
this.CopyLinkToolStripMenuItem.Click += new System.EventHandler(this.CopyLinkToolStripMenuItem_Click);
//
// UseSelectedServerCheckBox
//
this.UseSelectedServerCheckBox.AutoSize = true;
this.UseSelectedServerCheckBox.Location = new System.Drawing.Point(3, 4);
this.UseSelectedServerCheckBox.Name = "UseSelectedServerCheckBox";
this.UseSelectedServerCheckBox.Size = new System.Drawing.Size(285, 21);
this.UseSelectedServerCheckBox.TabIndex = 9;
this.UseSelectedServerCheckBox.Text = "Use Selected Server To Update Subscription";
this.UseSelectedServerCheckBox.UseVisualStyleBackColor = true;
//
// MainTableLayoutPanel
//
this.MainTableLayoutPanel.ColumnCount = 1;
this.MainTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.MainTableLayoutPanel.Controls.Add(this.SubscribeLinkListView, 0, 0);
this.MainTableLayoutPanel.Controls.Add(this.AddSubscriptionBox, 0, 1);
this.MainTableLayoutPanel.Controls.Add(this.ControlsPanel, 0, 2);
this.MainTableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.MainTableLayoutPanel.Location = new System.Drawing.Point(0, 0);
this.MainTableLayoutPanel.Name = "MainTableLayoutPanel";
this.MainTableLayoutPanel.Padding = new System.Windows.Forms.Padding(5);
this.MainTableLayoutPanel.RowCount = 3;
this.MainTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 58.35777F));
this.MainTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 41.64223F));
this.MainTableLayoutPanel.RowCount = 2;
this.MainTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 62.99213F));
this.MainTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 37.00787F));
this.MainTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 27F));
this.MainTableLayoutPanel.Size = new System.Drawing.Size(684, 391);
this.MainTableLayoutPanel.TabIndex = 11;
//
// ControlsPanel
//
this.ControlsPanel.Controls.Add(this.UseSelectedServerCheckBox);
this.ControlsPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.ControlsPanel.Location = new System.Drawing.Point(5, 358);
this.ControlsPanel.Margin = new System.Windows.Forms.Padding(0);
this.ControlsPanel.Name = "ControlsPanel";
this.ControlsPanel.Size = new System.Drawing.Size(674, 28);
this.ControlsPanel.TabIndex = 2;
//
// SubscribeForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
@@ -244,19 +242,16 @@
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Subscribe";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SubscribeForm_FormClosing);
this.Load += new System.EventHandler(this.SubscribeForm_Load);
this.AddSubscriptionBox.ResumeLayout(false);
this.AddSubscriptionBox.PerformLayout();
this.pContextMenuStrip.ResumeLayout(false);
this.MainTableLayoutPanel.ResumeLayout(false);
this.ControlsPanel.ResumeLayout(false);
this.ControlsPanel.PerformLayout();
this.ResumeLayout(false);
}
private System.Windows.Forms.ColumnHeader EnableColumnHeader;
private System.Windows.Forms.Panel ControlsPanel;
private System.Windows.Forms.TableLayoutPanel MainTableLayoutPanel;
private System.Windows.Forms.Button ClearButton;
private System.Windows.Forms.Button UnselectButton;
private System.Windows.Forms.GroupBox AddSubscriptionBox;
private System.Windows.Forms.Label RemarkLabel;
private System.Windows.Forms.TextBox LinkTextBox;
@@ -272,8 +267,9 @@
private System.Windows.Forms.Label UserAgentLabel;
private System.Windows.Forms.TextBox UserAgentTextBox;
private System.Windows.Forms.ColumnHeader UserAgentHeader;
private System.Windows.Forms.CheckBox UseSelectedServerCheckBox;
#endregion
private System.Windows.Forms.ToolStripMenuItem deleteServerToolStripMenuItem;
}
}

View File

@@ -8,85 +8,65 @@ namespace Netch.Forms
{
public partial class SubscribeForm : Form
{
private int _editingIndex = -1;
public SubscribeForm()
{
InitializeComponent();
}
public void InitSubscribeLink()
{
SubscribeLinkListView.Items.Clear();
foreach (var item in Global.Settings.SubscribeLink)
{
SubscribeLinkListView.Items.Add(new ListViewItem(new[]
{
item.Remark,
item.Link,
!string.IsNullOrEmpty(item.UserAgent) ? item.UserAgent : WebUtil.DefaultUserAgent
}));
}
}
private void SubscribeForm_Load(object sender, EventArgs e)
{
i18N.TranslateForm(this);
i18N.TranslateForm(pContextMenuStrip);
ResetEditingGroup();
if (Global.Settings.Server.Count > 0)
{
UseSelectedServerCheckBox.Enabled = true;
UseSelectedServerCheckBox.Checked = Global.Settings.UseProxyToUpdateSubscription;
}
else
{
UseSelectedServerCheckBox.Checked = false;
UseSelectedServerCheckBox.Enabled = false;
}
InitSubscribeLink();
}
private int SelectedIndex
{
get
{
if (SubscribeLinkListView.MultiSelect)
throw new Exception();
return SubscribeLinkListView.SelectedIndices.Count == 0 ? -1 : SubscribeLinkListView.SelectedIndices[0];
}
}
#region EventHandler
private void SubscribeLinkListView_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
if (SelectedIndex != -1)
pContextMenuStrip.Show(SubscribeLinkListView, e.Location);
}
/// <summary>
/// 选中/取消选中
/// </summary>
private void SubscribeLinkListView_SelectedIndexChanged(object sender, EventArgs e)
{
SetEditingGroup(SelectedIndex);
}
/// <summary>
/// 订阅启/禁用
/// </summary>
private void SubscribeLinkListView_ItemChecked(object sender, ItemCheckedEventArgs e)
{
var index = e.Item.Index;
Global.Settings.SubscribeLink[index].Enable = SubscribeLinkListView.Items[index].Checked;
}
private void SubscribeForm_FormClosing(object sender, FormClosingEventArgs e)
{
Configuration.Save();
Global.Settings.UseProxyToUpdateSubscription = UseSelectedServerCheckBox.Checked;
}
private void CopyLinkToolStripMenuItem_Click(object sender, EventArgs e)
{
if (SubscribeLinkListView.SelectedItems.Count > 0)
{
for (var i = SubscribeLinkListView.SelectedItems.Count - 1; i >= 0; i--)
{
var item = SubscribeLinkListView.SelectedItems[i];
var link = Global.Settings.SubscribeLink[item.Index];
Clipboard.SetText(link.Link);
}
}
}
#endregion
private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBoxX.Show(i18N.Translate("Delete or not ? Will clean up the corresponding group of items in the server list"), confirm: true) == DialogResult.OK)
{
if (SubscribeLinkListView.SelectedItems.Count > 0)
{
for (var i = SubscribeLinkListView.SelectedItems.Count - 1; i >= 0; i--)
{
var item = SubscribeLinkListView.SelectedItems[i];
#region EditBox
DeleteServersInGroup(item.SubItems[0].Text);
Global.Settings.SubscribeLink.RemoveAt(item.Index);
SubscribeLinkListView.Items.Remove(item);
ResetEditingGroup();
}
}
}
private void UnselectButton_Click(object sender, EventArgs e)
{
ResetEditingGroup();
}
private void AddButton_Click(object sender, EventArgs e)
@@ -109,7 +89,7 @@ namespace Netch.Forms
return;
}
if (_editingIndex == -1)
if (SelectedIndex == -1)
{
if (Global.Settings.SubscribeLink.Any(link => link.Remark.Equals(RemarkTextBox.Text)))
{
@@ -119,6 +99,7 @@ namespace Netch.Forms
Global.Settings.SubscribeLink.Add(new SubscribeLink
{
Enable = true,
Remark = RemarkTextBox.Text,
Link = LinkTextBox.Text,
UserAgent = UserAgentTextBox.Text
@@ -126,114 +107,107 @@ namespace Netch.Forms
}
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)
{
DeleteServersInGroup(target.Remark);
}
else
{
RenameServersGroup(target.Remark, RemarkTextBox.Text);
}
var subscribeLink = Global.Settings.SubscribeLink[SelectedIndex];
target.Link = LinkTextBox.Text;
target.Remark = RemarkTextBox.Text;
target.UserAgent = UserAgentTextBox.Text;
RenameServers(subscribeLink.Remark, RemarkTextBox.Text);
subscribeLink.Link = LinkTextBox.Text;
subscribeLink.Remark = RemarkTextBox.Text;
subscribeLink.UserAgent = UserAgentTextBox.Text;
}
Configuration.Save();
Global.Settings.UseProxyToUpdateSubscription = UseSelectedServerCheckBox.Checked;
// MessageBoxX.Show(i18N.Translate("Saved"));
ResetEditingGroup();
MessageBoxX.Show(i18N.Translate("Saved"));
InitSubscribeLink();
}
private static void DeleteServersInGroup(string group)
#endregion
#region ContextMenu
private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBoxX.Show(i18N.Translate("Delete or not ? Will clean up the corresponding group of items in the server list"), confirm: true) != DialogResult.OK)
return;
var subscribeLink = Global.Settings.SubscribeLink[SelectedIndex];
DeleteServers(subscribeLink.Remark);
Global.Settings.SubscribeLink.Remove(subscribeLink);
InitSubscribeLink();
}
private void deleteServerToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBoxX.Show(i18N.Translate("Confirm deletion?"), confirm: true) != DialogResult.OK)
return;
DeleteServers(Global.Settings.SubscribeLink[SelectedIndex].Remark);
}
private void CopyLinkToolStripMenuItem_Click(object sender, EventArgs e)
{
Clipboard.SetText(Global.Settings.SubscribeLink[SelectedIndex].Link);
}
#endregion
#region Helper
private static void DeleteServers(string group)
{
Global.Settings.Server.RemoveAll(server => server.Group == group);
}
private static void RenameServersGroup(string oldGroup, string newGroup)
private static void RenameServers(string oldGroup, string newGroup)
{
foreach (var server in Global.Settings.Server)
{
if (server.Group == oldGroup)
{
server.Group = newGroup;
}
}
foreach (var server in Global.Settings.Server.Where(server => server.Group == oldGroup))
server.Group = newGroup;
}
/// <summary>
/// 订阅列表选中节点
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SubscribeLinkListView_SelectedIndexChanged(object sender, EventArgs e)
private void InitSubscribeLink()
{
var editingCanOverwrite = true;
if (_editingIndex != -1)
{
var targetItem = SubscribeLinkListView.Items[_editingIndex].SubItems;
editingCanOverwrite = RemarkTextBox.Text == targetItem[0].Text &&
LinkTextBox.Text == targetItem[1].Text &&
UserAgentTextBox.Text == targetItem[2].Text;
}
SubscribeLinkListView.Items.Clear();
if (SubscribeLinkListView.SelectedItems.Count == 1)
{
if (editingCanOverwrite)
foreach (var item in Global.Settings.SubscribeLink)
SubscribeLinkListView.Items.Add(new ListViewItem(new[]
{
SelectEditing(SubscribeLinkListView.SelectedItems[0].Index);
}
}
else if (SubscribeLinkListView.SelectedItems.Count > 1)
{
}
else if (editingCanOverwrite)
{
// 不选
// 重置
ResetEditingGroup();
}
}
private void SubscribeLinkListView_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (SubscribeLinkListView.SelectedItems.Count > 0)
"",
item.Remark,
item.Link,
!string.IsNullOrEmpty(item.UserAgent) ? item.UserAgent : WebUtil.DefaultUserAgent
})
{
pContextMenuStrip.Show(SubscribeLinkListView, e.Location);
}
}
}
Checked = item.Enable
});
private void SelectEditing(int index)
{
_editingIndex = index;
ListViewItem target;
target = SubscribeLinkListView.Items[index];
AddSubscriptionBox.Text = target.SubItems[0].Text;
RemarkTextBox.Text = target.SubItems[0].Text;
LinkTextBox.Text = target.SubItems[1].Text;
UserAgentTextBox.Text = target.SubItems[2].Text;
ResetEditingGroup();
}
private void ResetEditingGroup()
{
_editingIndex = -1;
AddSubscriptionBox.Text = string.Empty;
RemarkTextBox.Text = string.Empty;
LinkTextBox.Text = string.Empty;
UserAgentTextBox.Text = WebUtil.DefaultUserAgent;
}
private void ClearButton_Click(object sender, EventArgs e)
private void SetEditingGroup(int index)
{
ResetEditingGroup();
if (index == -1)
{
ResetEditingGroup();
AddButton.Text = i18N.Translate("Add");
return;
}
var item = Global.Settings.SubscribeLink[index];
AddSubscriptionBox.Text = item.Remark;
RemarkTextBox.Text = item.Remark;
LinkTextBox.Text = item.Link;
UserAgentTextBox.Text = item.UserAgent;
AddButton.Text = i18N.Translate("Modify");
}
#endregion
}
}

View File

@@ -1,14 +1,14 @@
using System;
using Netch.Controllers;
using Netch.Forms;
using Netch.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Windows.Forms;
using Netch.Controllers;
using Netch.Forms;
using Netch.Models;
using WindowsJobAPI;
namespace Netch
{
@@ -87,5 +87,10 @@ namespace Netch
/// 用于存储模式
/// </summary>
public static readonly List<Mode> Modes = new List<Mode>();
/// <summary>
/// Windows Job API
/// </summary>
public static readonly JobObject Job = new JobObject();
}
}

View File

@@ -33,20 +33,6 @@ 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>
@@ -131,44 +117,15 @@ namespace Netch.Models
/// <returns>模式文件字符串</returns>
public string ToFileString()
{
StringBuilder fileString = new StringBuilder();
switch (Type)
{
case 0:
// 进程模式
fileString.Append($"# {Remark}");
break;
case 1:
// TUN/TAP 规则内 IP CIDR无 Bypass China 设置
fileString.Append($"# {Remark}, {Type}, 0");
break;
default:
fileString.Append($"# {Remark}, {Type}, {(BypassChina ? 1 : 0)}");
break;
}
if (Rule.Any())
{
fileString.Append(Global.EOF);
fileString.Append(string.Join(Global.EOF, Rule));
}
return fileString.ToString();
}
public string TypeToString()
{
return Type switch
{
0 => "Process",
1 => "TUNTAP",
2 => "TUNTAP",
3 => "SYSTEM",
4 => "S5",
5 => "S5+HTTP",
_ => "ERROR",
};
return $"# {Remark}, {Type}, {(BypassChina ? 1 : 0)}{Global.EOF}{string.Join(Global.EOF, Rule)}";
}
}
public static class ModeExtension
{
/// 是否会转发 UDP
public static bool TestNatRequired(this Mode mode) => mode.Type is 0 or 1 or 2;
/// Socks5 分流是否能被有效实施
public static bool ClientRouting(this Mode mode) => mode.Type is not (1 or 2);
}
}

20
Netch/Models/Range.cs Normal file
View File

@@ -0,0 +1,20 @@
namespace Netch.Models
{
public readonly struct Range
{
public int Start { get; }
public int End { get; }
public Range(int start, int end)
{
Start = start;
End = end;
}
public bool InRange(int num)
{
return Start <= num && num <= End;
}
}
}

View File

@@ -1,31 +1,23 @@
using System;
using System.Threading.Tasks;
using Netch.Utils;
using Newtonsoft.Json;
namespace Netch.Models
{
public class Server
public class Server : ICloneable
{
/// <summary>
/// 备注
/// 延迟
/// </summary>
public string Remark;
[JsonIgnore]
public int Delay = -1;
/// <summary>
/// 组
/// </summary>
public string Group = "None";
/// <summary>
/// 代理类型
/// </summary>
public string Type;
/// <summary>
/// 倍率
/// </summary>
public double Rate = 1.0;
/// <summary>
/// 地址
/// </summary>
@@ -37,28 +29,40 @@ namespace Netch.Models
public ushort Port;
/// <summary>
/// 延迟
/// 倍率
/// </summary>
public int Delay = -1;
public double Rate = 1.0;
/// <summary>
/// 备注
/// </summary>
public string Remark;
/// <summary>
/// 获取备注
/// 代理类型
/// </summary>
public string Type;
public object Clone()
{
return MemberwiseClone();
}
/// <summary>
/// 获取备注
/// </summary>
/// <returns>备注</returns>
public override string ToString()
{
if (string.IsNullOrWhiteSpace(Remark))
{
Remark = $"{Hostname}:{Port}";
}
var remark = string.IsNullOrWhiteSpace(Remark) ? $"{Hostname}:{Port}" : Remark;
Group = Group.Equals("None") || Group.Equals("") ? "NONE" : Group;
if (Group.Equals("None") || Group.Equals(""))
Group = "NONE";
return $"[{ServerHelper.GetUtilByTypeName(Type)?.ShortName ?? "WTF"}][{Group}] {Remark}";
return $"[{ServerHelper.GetUtilByTypeName(Type)?.ShortName ?? "WTF"}][{Group}] {remark}";
}
/// <summary>
/// 测试延迟
/// 测试延迟
/// </summary>
/// <returns>延迟</returns>
public int Test()
@@ -67,25 +71,21 @@ namespace Netch.Models
{
var destination = DNS.Lookup(Hostname);
if (destination == null)
{
return Delay = -2;
}
var list = new Task<int>[3];
for (var i = 0; i < 3; i++)
{
list[i] = Task.Run(async () =>
{
try
{
return await Utils.Utils.TCPingAsync(destination, Port);
return Global.Settings.ServerTCPing ? await Utils.Utils.TCPingAsync(destination, Port) : await Utils.Utils.ICMPing(destination, Port);
}
catch (Exception)
{
return -4;
}
});
}
Task.WaitAll(list[0], list[1], list[2]);

View File

@@ -1,64 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Generic;
namespace Netch.Models
{
/// <summary>
/// TUN/TAP 适配器配置类
/// TUN/TAP 适配器配置类
/// </summary>
public class TUNTAPConfig
{
/// <summary>
/// 地址
/// 地址
/// </summary>
public string Address = "10.0.236.10";
/// <summary>
/// 掩码
/// DNS
/// </summary>
public string Netmask = "255.255.255.0";
public List<string> DNS = new();
/// <summary>
/// 网关
/// 网关
/// </summary>
public string Gateway = "10.0.236.1";
/// <summary>
/// DNS
/// 掩码
/// </summary>
public List<string> DNS = new List<string>();
public string Netmask = "255.255.255.0";
/// <summary>
/// 使用自定义 DNS 设置
/// </summary>
public bool UseCustomDNS = false;
/// <summary>
/// 模式 2 下是否代理 DNS
/// 模式 2 下是否代理 DNS
/// </summary>
public bool ProxyDNS = false;
/// <summary>
/// 使用Fake DNS
/// 使用自定义 DNS 设置
/// </summary>
public bool UseCustomDNS = false;
/// <summary>
/// 使用Fake DNS
/// </summary>
public bool UseFakeDNS = false;
}
public class KcpConfig
{
public bool congestion = false;
public int downlinkCapacity = 100;
public int mtu = 1350;
public int readBufferSize = 2;
public int tti = 50;
public int uplinkCapacity = 12;
public int downlinkCapacity = 100;
public bool congestion = false;
public int readBufferSize = 2;
public int writeBufferSize = 2;
}
@@ -66,18 +63,19 @@ namespace Netch.Models
{
public bool AllowInsecure = true;
public KcpConfig KcpConfig = new KcpConfig();
public KcpConfig KcpConfig = new();
public bool UseMux = true;
public bool UseMux = false;
}
public class AioDNSConfig
{
public string RulePath = "bin\\china_site_list";
public string ChinaDNS = "223.5.5.5";
public string OtherDNS = "1.1.1.1";
public string Protocol = "tcp";
public string RulePath = "bin\\china_site_list";
}
/// <summary>
@@ -86,29 +84,61 @@ namespace Netch.Models
public class Setting
{
/// <summary>
/// 服务器选择位置
/// 服务器列表
/// </summary>
public int ServerComboBoxSelectedIndex = 0;
public readonly List<Server> Server = new();
/// <summary>
/// 模式选择位置
/// ACL规则
/// </summary>
public int ModeComboBoxSelectedIndex = 0;
public string ACL = "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/banAD.acl";
public AioDNSConfig AioDNS = new();
/// <summary>
/// 是否关闭窗口时退出
/// 是否使用DLL启动Shadowsocks
/// </summary>
public bool BootShadowsocksFromDLL = true;
/// <summary>
/// 全局绕过 IP 列表
/// </summary>
public List<string> BypassIPs = new();
/// <summary>
/// 是否检查 Beta 更新
/// </summary>
public bool CheckBetaUpdate = false;
/// <summary>
/// 是否打开软件时检查更新
/// </summary>
public bool CheckUpdateWhenOpened = true;
/// <summary>
/// 测试所有服务器心跳/秒
/// </summary>
public int DetectionTick = 10;
/// <summary>
/// 是否关闭窗口时退出
/// </summary>
public bool ExitWhenClosed = false;
/// <summary>
/// 是否退出时停止
/// HTTP 本地端口
/// </summary>
public bool StopWhenExited = false;
public ushort HTTPLocalPort = 2802;
/// <summary>
/// 是否打开软件时启动加速
/// 语言设置
/// </summary>
public bool StartWhenOpened = false;
public string Language = "System";
/// <summary>
/// HTTP 和 Socks5 本地代理地址
/// </summary>
public string LocalAddress = "127.0.0.1";
/// <summary>
/// 是否启动后自动最小化
@@ -116,29 +146,9 @@ namespace Netch.Models
public bool MinimizeWhenStarted = false;
/// <summary>
/// 是否开机启动软件
/// 模式选择位置
/// </summary>
public bool RunAtStartup = false;
/// <summary>
/// 是否打开软件时检查更新
/// </summary>
public bool CheckUpdateWhenOpened = true;
/// <summary>
/// 是否检查 Beta 更新
/// </summary>
public bool CheckBetaUpdate = false;
/// <summary>
/// 是否打开软件时更新订阅
/// </summary>
public bool UpdateSubscribeatWhenOpened = false;
/// <summary>
/// 修改系统 DNS
/// </summary>
public bool ModifySystemDNS = false;
public int ModeComboBoxSelectedIndex = 0;
/// <summary>
/// 要修改为的系统 DNS
@@ -146,9 +156,54 @@ namespace Netch.Models
public string ModifiedDNS = "1.1.1.1,8.8.8.8";
/// <summary>
/// 解析服务器主机名
/// 修改系统 DNS
/// </summary>
public bool ResolveServerHostname = false;
public bool ModifySystemDNS = false;
/// <summary>
/// GFWList
/// </summary>
public string PAC = "https://raw.githubusercontent.com/HMBSbige/Text_Translation/master/ShadowsocksR/ss_white.pac";
/// <summary>
/// PAC端口
/// </summary>
public int Pac_Port = 2803;
/// <summary>
/// PAC URL
/// </summary>
public string Pac_Url = "";
/// <summary>
/// 不代理TCP
/// </summary>
public bool ProcessNoProxyForTcp = false;
/// <summary>
/// 不代理UDP
/// </summary>
public bool ProcessNoProxyForUdp = false;
/// <summary>
/// 快捷配置数量
/// </summary>
public int ProfileCount = 4;
/// <summary>
/// 已保存的快捷配置
/// </summary>
public List<Profile> Profiles = new();
/// <summary>
/// 是否使用RDR内置SS
/// </summary>
public bool RedirectorSS = false;
/// <summary>
/// Redirector TCP 占用端口
/// </summary>
public ushort RedirectorTCPPort = 3901;
/// <summary>
/// 网页请求超时 毫秒
@@ -156,64 +211,44 @@ namespace Netch.Models
public int RequestTimeout = 10000;
/// <summary>
/// HTTP 本地端口
/// 解析服务器主机名
/// </summary>
public ushort HTTPLocalPort = 2802;
public bool ResolveServerHostname = false;
/// <summary>
/// Socks5 本地端口
/// 是否开机启动软件
/// </summary>
public bool RunAtStartup = false;
/// <summary>
/// 服务器选择位置
/// </summary>
public int ServerComboBoxSelectedIndex = 0;
/// <summary>
/// 服务器测试方式 false.ICMPing true.TCPing
/// </summary>
public bool ServerTCPing = true;
/// <summary>
/// Socks5 本地端口
/// </summary>
public ushort Socks5LocalPort = 2801;
/// <summary>
/// Redirector TCP 占用端口
/// 启动后延迟测试间隔/秒
/// </summary>
public ushort RedirectorTCPPort = 3901;
public int StartedPingInterval = -1;
/// <summary>
/// UDP Socket 占用端口
/// 是否打开软件时启动加速
/// </summary>
public ushort UDPSocketPort = 18291;
public bool StartWhenOpened = false;
/// <summary>
/// HTTP 和 Socks5 本地代理地址
/// 是否退出时停止
/// </summary>
public string LocalAddress = "127.0.0.1";
/// <summary>
/// TUNTAP 适配器配置
/// </summary>
public TUNTAPConfig TUNTAP = new TUNTAPConfig();
/// <summary>
/// 使用代理更新订阅
/// </summary>
public bool UseProxyToUpdateSubscription = false;
/// <summary>
/// 订阅链接列表
/// </summary>
public List<SubscribeLink> SubscribeLink = new List<SubscribeLink>();
/// <summary>
/// 服务器列表
/// </summary>
public readonly List<Server> Server = new List<Server>();
/// <summary>
/// 全局绕过 IP 列表
/// </summary>
public List<string> BypassIPs = new List<string>();
/// <summary>
/// 已保存的快捷配置
/// </summary>
public List<Profile> Profiles = new List<Profile>();
/// <summary>
/// 快捷配置数量
/// </summary>
public int ProfileCount = 4;
public bool StopWhenExited = false;
/// <summary>
/// STUN测试服务器
@@ -226,32 +261,34 @@ namespace Netch.Models
public int STUN_Server_Port = 3478;
/// <summary>
/// 是否启用启动后延迟测试
/// 订阅链接列表
/// </summary>
public bool StartedTcping = false;
public List<SubscribeLink> SubscribeLink = new();
/// <summary>
/// 启动后延迟测试间隔/秒
/// TUNTAP 适配器配置
/// </summary>
public int StartedTcping_Interval = 3;
public TUNTAPConfig TUNTAP = new();
/// <summary>
/// ACL规则
/// UDP Socket 占用端口
/// </summary>
public string ACL = "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/banAD.acl";
public ushort UDPSocketPort = 18291;
/// <summary>
/// 是否使用DLL启动Shadowsocks
/// 是否打开软件时更新订阅
/// </summary>
public bool BootShadowsocksFromDLL = true;
public bool UpdateServersWhenOpened = false;
/// <summary>
/// 语言设置
/// 使用代理更新订阅
/// </summary>
public string Language = "System";
public bool UseProxyToUpdateSubscription = false;
public V2rayConfig V2RayConfig = new V2rayConfig();
public AioDNSConfig AioDNS = new AioDNSConfig();
public V2rayConfig V2RayConfig = new();
public Setting Clone()
{
return (Setting) MemberwiseClone();
}
}
}

View File

@@ -2,6 +2,11 @@
{
public class SubscribeLink
{
/// <summary>
/// 启用状态
/// </summary>
public bool Enable = true;
/// <summary>
/// 备注
/// </summary>
@@ -17,4 +22,4 @@
/// </summary>
public string UserAgent;
}
}
}

View File

@@ -13,7 +13,7 @@ namespace Netch
/// <param name="index">适配器索引</param>
/// <param name="metric">跃点数</param>
/// <returns>是否成功</returns>
[DllImport("NetchCore", CallingConvention = CallingConvention.Cdecl, EntryPoint = "CreateRoute")]
[DllImport("RouteHelper.bin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "CreateRoute")]
public static extern bool CreateRoute(string address, int cidr, string gateway, int index, int metric = 0);
/// <summary>
@@ -25,33 +25,9 @@ namespace Netch
/// <param name="index">适配器索引</param>
/// <param name="metric">跃点数</param>
/// <returns>是否成功</returns>
[DllImport("NetchCore", CallingConvention = CallingConvention.Cdecl, EntryPoint = "DeleteRoute")]
[DllImport("RouteHelper.bin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "DeleteRoute")]
public static extern bool DeleteRoute(string address, int cidr, string gateway, int index, int metric = 0);
/// <summary>
/// 设置直连
/// </summary>
/// <returns>是否成功</returns>
[DllImport("sysproxy", CallingConvention = CallingConvention.Cdecl)]
public static extern bool SetDIRECT();
/// <summary>
/// 设置全局
/// </summary>
/// <param name="remote">地址</param>
/// <param name="bypass">绕过</param>
/// <returns>是否成功</returns>
[DllImport("sysproxy", CallingConvention = CallingConvention.Cdecl)]
public static extern bool SetGlobal([MarshalAs(UnmanagedType.LPTStr)] string remote, [MarshalAs(UnmanagedType.LPTStr)] string bypass);
/// <summary>
/// 设置自动代理
/// </summary>
/// <param name="remote">URL</param>
/// <returns>是否成功</returns>
[DllImport("sysproxy", CallingConvention = CallingConvention.Cdecl)]
public static extern bool SetURL([MarshalAs(UnmanagedType.LPTStr)] string remote);
[DllImport("dnsapi", EntryPoint = "DnsFlushResolverCache")]
public static extern uint FlushDNSResolverCache();

View File

@@ -20,8 +20,10 @@ namespace Netch
{
if (args.Contains("-console"))
{
NativeMethods.AllocConsole();
NativeMethods.AttachConsole(-1);
if (!NativeMethods.AttachConsole(-1))
{
NativeMethods.AllocConsole();
}
}
// 创建互斥体防止多次运行

View File

@@ -66,12 +66,14 @@
<ItemGroup>
<PackageReference Include="ILMerge" Version="3.0.41" />
<PackageReference Include="MaxMind.GeoIP2" Version="3.3.0" />
<PackageReference Include="Microsoft.Diagnostics.Tracing.TraceEvent" Version="2.0.61" />
<PackageReference Include="MaxMind.GeoIP2" Version="4.0.1" />
<PackageReference Include="Microsoft.Diagnostics.Tracing.TraceEvent" Version="2.0.62" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<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="System.Collections.Immutable" Version="5.0.0" />
<PackageReference Include="System.Reflection.Metadata" Version="5.0.0" />
<PackageReference Include="WindowsAPICodePack-Shell" Version="1.1.1" />
<PackageReference Include="WindowsJobAPI" Version="5.0.1" />
<PackageReference Include="WindowsProxy" Version="5.0.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -21,3 +21,5 @@ XCOPY /s /Y %SolutionDir%modes\mode %TargetDir%mode\ >NUL
DEL /f %TargetDir%*.config >NUL 2>&1
DEL /f %TargetDir%*.pdb >NUL 2>&1
RD /s /Q %TargetDir%x86 >NUL 2>&1
exit 0

View File

@@ -60,6 +60,16 @@ namespace Netch.Properties {
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] abp_js {
get {
object obj = ResourceManager.GetObject("abp_js", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>

View File

@@ -1,145 +1,172 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string"/>
<xsd:attribute name="type" type="xsd:string"/>
<xsd:attribute name="mimetype" type="xsd:string"/>
<xsd:attribute ref="xml:space"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string"/>
<xsd:attribute name="name" type="xsd:string"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1"/>
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2"/>
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1"/>
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3"/>
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4"/>
<xsd:attribute ref="xml:space"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1"/>
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
</value>
</resheader>
<assembly alias="System.Windows.Forms"
name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<data name="defaultTUNTAP" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\defaultTUNTAP;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
<data name="zh_CN" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\zh-CN;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
</value>
</data>
<data name="speed" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\speed.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a
</value>
</data>
<data name="delete" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\delete.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a
</value>
</data>
<data name="edit" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\edit.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a
</value>
</data>
<data name="Netch" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Netch.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a
</value>
</data>
<data name="Sponsor" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Sponsor.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a
</value>
</data>
<data name="CopyLink" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\CopyLink.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a
</value>
</data>
<data name="abp_js" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\abp.js.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a
</value>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="defaultTUNTAP" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\defaultTUNTAP;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="zh_CN" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\zh-CN;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="speed" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\speed.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="delete" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\delete.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="edit" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\edit.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Netch" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Netch.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Sponsor" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Sponsor.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="CopyLink" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\CopyLink.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

BIN
Netch/Resources/abp.js.gz Normal file

Binary file not shown.

View File

@@ -28,7 +28,7 @@
"Import Servers From Clipboard": "从剪贴板导入服务器",
"Import servers error!": "未找到可导入的链接!",
"Add [{0}] Server": "添加 [{0}] 服务器",
"Netch is now minimized to the notification bar, double click this icon to restore.": "Netch 已最小化至通知栏,双击此图标恢复窗口",
"Netch is now minimized to the notification bar, double click this icon to restore.": "Netch 已最小化至通知栏,双击此图标恢复窗口",
"New version available": "发现新版本",
"Already latest version": "已经是最新版本",
"New version found failed": "寻找新版本失败",
@@ -66,10 +66,18 @@
"Subscribe": "订阅",
"Manage Subscribe Links": "管理订阅链接",
"Update Servers From Subscribe Links": "从订阅链接更新服务器",
"Update Servers From Subscribe Links With Proxy": "使用代理从订阅链接更新服务器",
"No subscription link": "没有任何一条订阅链接",
"Updating in the background": "正在后台更新中",
"Updating {0}": "正在更新 {0}",
"Update {1} server(s) from {0}": "从 {0} 更新 {1} 个服务器",
"Update servers error from {0}": "从 {0} 更新服务器失败",
"Delete the corresponding group of items in the server list?": "是否删除订阅对应服务器?",
"Confirm deletion?": "确认删除?",
"DeleteServer": "删除订阅节点",
"Status": "状态",
"Remark": "备注",
"Link": "链接",
"Unselect": "取消选择",
"Options": "选项",
"NF Service": "NF 服务",
@@ -81,10 +89,16 @@
"Modes have been reload": "模式已重载",
"Clean DNS Cache": "清理 DNS 缓存",
"DNS cache cleanup succeeded": "DNS 缓存清理成功",
"Update PAC": "更新 PAC",
"PAC updated successfully": "PAC 更新成功",
"PAC update failed": "PAC 更新失败",
"Update ACL": "更新 ACL 规则",
"Update ACL with proxy": "使用代理更新 ACL 规则",
"ACL updated successfully": "ACL 更新成功",
"ACL update failed": "ACL 更新失败",
"Open Directory": "打开目录",
"About": "关于",
@@ -113,9 +127,10 @@
"Add": "添加",
"Scan": "扫描",
"Save": "保存",
"Add / Modify": "保存/修改",
"Modify": "修改",
"Select a folder": "选择一个目录",
"Please enter an process name (xxx.exe)": "请输入一个进程名xxx.exe",
"Rule does not conform to C++ regular expression syntax": "规则不符合 C++ 正则表达式语法",
"Scan completed": "扫描完成",
"Mode added successfully": "模式添加成功",
"Mode updated successfully": "模式修改成功",
@@ -149,20 +164,23 @@
"Exit when closed": "关闭时退出",
"Stop when exited": "退出时停止",
"Global Bypass IPs": "全局直连 IP",
"Port value illegal. Try again.": "端口值非法。请重试",
"Port value illegal. Try again.": "端口值非法。请重试",
"Check update when opened": "打开软件时检查更新",
"Check Beta update": "检查 Beta 更新",
"Update subscribeat when opened": "自动更新订阅",
"Update Servers when opened": "打开软件时更新服务器",
"SS DLL": "SS DLL",
"Modify System DNS": "修改系统 DNS",
"No Proxy for Udp": "不代理 UDP 流量",
"No Proxy for Tcp": "不代理 TCP 流量",
"ProfileCount": "快捷配置数量",
"ProfileCount value illegal. Try again.": "快捷配置数值非法。请重试",
"STUN_ServerPort value illegal. Try again.": "STUN 端口数值非法。请重试",
"Detection interval value illegal. Try again.": "检测间隔值非法。请重试",
"ProfileCount value illegal. Try again.": "快捷配置数值非法。请重试",
"STUN_ServerPort value illegal. Try again.": "STUN 端口数值非法。请重试",
"Detection interval value illegal. Try again.": "检测间隔值非法。请重试",
"TUN/TAP driver is not detected. Is it installed now?": "未检测到 TUN/TAP 驱动,是否现在安装?",
"Failed to set the system proxy, it may be caused by the lack of dependent programs. Do you want to jump to Netch's official website to download dependent programs?": "设置系统代理失败,可能是缺少依赖导致,是否跳转 Netch 官网下载依赖程序?",
"Delay test after start": "启动后延迟测试",
"Enable": "启用",
"ServerPingType": "测速方式",
"Detection interval(sec)": "检测间隔(秒)",
"STUN Server": "STUN 服务器",
"STUN Server Port": "STUN 服务器端口",
@@ -180,6 +198,7 @@
"Unable to start? Click me to download": "无法启动?点我下载依赖",
"The {0} port is in use.": "{0} 端口已被占用",
"The {0} port is reserved by system.": "{0} 端口是系统保留端口",
"[Web Proxy] Bypass LAN": "[网页代理] 绕过局域网",
"[Non Web Proxy] Bypass LAN": "[不设置代理] 绕过局域网",
@@ -187,4 +206,4 @@
"[Web Proxy] Bypass LAN and China": "[网页代理] 绕过局域网和中国大陆",
"[Non Web Proxy] Bypass LAN and China": "[不设置代理] 绕过局域网和中国大陆",
"[TUN/TAP] Bypass LAN and China": "[TUN/TAP] 绕过局域网和中国大陆"
}
}

View File

@@ -11,18 +11,17 @@ namespace Netch.Servers.Shadowsocks
public override string Name { get; protected set; } = "Shadowsocks";
public override string MainFile { get; protected set; } = "Shadowsocks.exe";
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 DllFlag;
public bool Start(in Server s, in Mode mode)
{
_savedMode = mode;
Server = s;
var server = (Shadowsocks) s;
DllFlag = Global.Settings.BootShadowsocksFromDLL && mode.Type is 0 or 1 or 2 && !server.HasPlugin();
//从DLL启动Shaowsocks
if (DllFlag)
{
@@ -76,14 +75,12 @@ namespace Netch.Servers.Shadowsocks
public override void Stop()
{
if (Instance == null)
if (DllFlag)
ShadowsocksDLL.Stop();
else
StopInstance();
_savedMode = null;
}
private class ShadowsocksDLL
{
[DllImport("shadowsocks-windows-dynamic", CallingConvention = CallingConvention.Cdecl)]

View File

@@ -29,6 +29,8 @@ namespace Netch.Servers.Shadowsocks
{
Type = "SS";
}
public bool HasPlugin() => !string.IsNullOrWhiteSpace(Plugin) && !string.IsNullOrWhiteSpace(PluginOption);
}
public static class SSGlobal

View File

@@ -1,7 +1,6 @@
using System.Text;
using Netch.Controllers;
using Netch.Models;
using Netch.Utils;
namespace Netch.Servers.ShadowsocksR
{
@@ -11,13 +10,11 @@ namespace Netch.Servers.ShadowsocksR
public override string Name { get; protected set; } = "ShadowsocksR";
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

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Text.RegularExpressions;
using Netch.Controllers;
using Netch.Models;
using Netch.Servers.Shadowsocks;
using Netch.Servers.ShadowsocksR.Form;
using Netch.Utils;
using Newtonsoft.Json.Linq;
@@ -100,6 +101,22 @@ namespace Netch.Servers.ShadowsocksR
var group = paramsDict.ContainsKey("group") ? ShareLink.URLSafeBase64Decode(paramsDict["group"]) : string.Empty;
if (SSGlobal.EncryptMethods.Contains(method) && protocol == "origin" && obfs == "plain")
{
return new[]
{
new Shadowsocks.Shadowsocks
{
Hostname = serverAddr,
Port = serverPort,
EncryptMethod = method,
Password = password,
Remark = remarks,
Group = group
}
};
}
return new[]
{
new ShadowsocksR

View File

@@ -12,9 +12,8 @@ namespace Netch.Servers.Socks5
public bool Start(in Server s, in Mode mode)
{
Server = s;
var server = (Socks5) s;
if (server.Auth() && !mode.SupportSocks5Auth)
if (server.Auth())
{
File.WriteAllText("data\\last.json", V2rayConfigUtils.GenerateClientConfig(s, mode));
if (StartInstanceAuto("-config ..\\data\\last.json"))
@@ -34,7 +33,6 @@ namespace Netch.Servers.Socks5
StopInstance();
}
public Server Server { get; set; }
public ushort? Socks5LocalPort { get; set; }
public string LocalAddress { get; set; }

View File

@@ -3,7 +3,6 @@ using System.IO;
using Netch.Controllers;
using Netch.Models;
using Netch.Servers.Trojan.Models;
using Netch.Utils;
using Newtonsoft.Json;
namespace Netch.Servers.Trojan
@@ -18,27 +17,32 @@ namespace Netch.Servers.Trojan
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
var trojanConfig = new TrojanConfig
{
local_addr = this.LocalAddress(),
local_port = this.Socks5LocalPort(),
remote_addr = server.AutoResolveHostname(),
remote_addr = server.Hostname,
remote_port = server.Port,
password = new List<string>
{
server.Password
}
}));
};
if (!string.IsNullOrWhiteSpace(server.Host))
trojanConfig.ssl.sni = server.Host;
File.WriteAllText("data\\last.json", JsonConvert.SerializeObject(trojanConfig, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}));
return StartInstanceAuto("-c ..\\data\\last.json");
}

View File

@@ -1,5 +1,4 @@
using System.Collections.Generic;
using Netch.Models;
using Netch.Servers.VMess;
namespace Netch.Servers.VLESS
@@ -14,17 +13,17 @@ namespace Netch.Servers.VLESS
/// <summary>
/// 加密方式
/// </summary>
public new string EncryptMethod { get; set; } = "none";
public override string EncryptMethod { get; set; } = "none";
/// <summary>
/// 传输协议
/// </summary>
public new string TransferProtocol { get; set; } = VLESSGlobal.TransferProtocols[0];
public override string TransferProtocol { get; set; } = VLESSGlobal.TransferProtocols[0];
/// <summary>
/// 伪装类型
/// </summary>
public new string FakeType { get; set; } = VLESSGlobal.FakeTypes[0];
public override string FakeType { get; set; } = VLESSGlobal.FakeTypes[0];
/// <summary>
///
@@ -34,7 +33,6 @@ namespace Netch.Servers.VLESS
public class VLESSGlobal
{
public static List<string> TransferProtocols => VMessGlobal.TransferProtocols;
public static readonly List<string> FakeTypes = new List<string>
@@ -42,5 +40,12 @@ namespace Netch.Servers.VLESS
"none",
"http"
};
public static readonly List<string> TLSSecure = new List<string>
{
"",
"tls",
"xtls"
};
}
}

View File

@@ -10,14 +10,12 @@ namespace Netch.Servers.VLESS
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");
}

View File

@@ -48,10 +48,11 @@ namespace Netch.Servers.VLESS.VLESSForm
"false" => false,
_ => null
},
server.UseMux?.ToString() ?? "");
CreateCheckBox("TLSSecure", "TLS Secure",
b => server.TLSSecure = b,
server.TLSSecure);
server.UseMux?.ToString().ToLower() ?? "");
CreateComboBox("TLSSecure", "TLS Secure",
VLESSGlobal.TLSSecure,
s => server.TLSSecureType = s,
server.TLSSecureType);
}
}
}

View File

@@ -57,10 +57,11 @@ namespace Netch.Servers.VMess.Form
"false" => false,
_ => null
},
server.UseMux?.ToString() ?? "");
CreateCheckBox("TLSSecure", "TLS Secure",
s => server.TLSSecure = s,
server.TLSSecure);
server.UseMux?.ToString().ToLower() ?? "");
CreateComboBox("TLSSecure", "TLS Secure",
VMessGlobal.TLSSecure,
s => server.TLSSecureType = s,
server.TLSSecureType);
}
}
}

View File

@@ -195,8 +195,6 @@ namespace Netch.Servers.VMess.Models
public class TcpSettings
{
public bool connectionReuse { get; set; }
public Header header { get; set; }
}
@@ -257,8 +255,6 @@ namespace Netch.Servers.VMess.Models
public class WsSettings
{
public bool connectionReuse { get; set; }
public string path { get; set; }
public Headers headers { get; set; }

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using Netch.Models;
using Netch.Servers.VMess.Models;
using Newtonsoft.Json;
@@ -20,7 +21,7 @@ namespace Netch.Servers.VMess.Utils
outbound(server, mode, ref v2rayConfig);
return JsonConvert.SerializeObject(v2rayConfig);
return JsonConvert.SerializeObject(v2rayConfig, Formatting.Indented, new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
}
catch
{
@@ -58,44 +59,72 @@ namespace Netch.Servers.VMess.Utils
{
try
{
RulesItem rulesItem;
var directRuleObject = new RulesItem
{
type = "field",
ip = new List<string>(),
domain = new List<string>(),
outboundTag = "direct"
};
var blockRuleObject = new RulesItem
{
type = "field",
ip = new List<string>(),
domain = new List<string>(),
outboundTag = "block"
};
if (mode.BypassChina)
{
rulesItem = new RulesItem
switch (mode.Type)
{
type = "field",
ip = new List<string>
{
"geoip:cn",
"geoip:private"
},
domain = new List<string>
{
"geosite:cn"
},
outboundTag = "direct"
};
case 0:
directRuleObject.ip.Add("geoip:cn");
break;
case 1:
case 2:
if (Global.Flags.SupportFakeDns && Global.Settings.TUNTAP.UseFakeDNS)
directRuleObject.domain.Add("geosite:cn");
else
directRuleObject.ip.Add("geoip:cn");
break;
default:
directRuleObject.domain.Add("geosite:cn");
break;
}
}
else
if (mode.Type is 0 or 1 or 2)
{
rulesItem = new RulesItem
{
type = "field",
ip = new List<string>
{
"geoip:private"
},
outboundTag = "direct"
};
blockRuleObject.ip.Add("geoip:private");
}
v2rayConfig.routing = new Routing
{
rules = new List<RulesItem>
{
rulesItem
}
rules = new List<RulesItem>()
};
static bool CheckRuleItem(ref RulesItem rulesItem)
{
bool ipResult, domainResult;
if (!(ipResult = rulesItem.ip.Any()))
{
rulesItem.ip = null;
}
if (!(domainResult = rulesItem.domain.Any()))
{
rulesItem.domain = null;
}
return ipResult || domainResult;
}
if (CheckRuleItem(ref directRuleObject))
v2rayConfig.routing.rules.Add(directRuleObject);
if (CheckRuleItem(ref blockRuleObject))
v2rayConfig.routing.rules.Add(blockRuleObject);
}
catch
{
@@ -121,31 +150,25 @@ namespace Netch.Servers.VMess.Utils
{
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
new ServersItem
{
user = socks5.Username,
pass = socks5.Password,
level = 1
};
serversItem.users.Add(socksUsersItem);
}
users = socks5.Auth()
? new List<SocksUsersItem>
{
new SocksUsersItem
{
user = socks5.Username,
pass = socks5.Password,
level = 1
}
}
: null,
address = server.AutoResolveHostname(),
port = server.Port
}
};
outbound.mux.enabled = false;
outbound.mux.concurrency = -1;
@@ -156,37 +179,36 @@ namespace Netch.Servers.VMess.Utils
{
var vnextItem = new VnextItem
{
users = new List<UsersItem>()
users = new List<UsersItem>(),
address = server.AutoResolveHostname(),
port = server.Port
};
outbound.settings.vnext = new List<VnextItem>
outbound.settings.vnext = new List<VnextItem> {vnextItem};
var usersItem = new UsersItem
{
vnextItem
id = vless.UserID,
alterId = 0,
flow = string.Empty,
encryption = vless.EncryptMethod
};
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 ?? Global.Settings.V2RayConfig.UseMux;
outbound.mux.concurrency = vless.UseMux ?? Global.Settings.V2RayConfig.UseMux ? 8 : -1;
var streamSettings = outbound.streamSettings;
boundStreamSettings(vless, ref streamSettings);
if (vless.TransferProtocol == "xtls")
if (vless.TLSSecureType == "xtls")
{
usersItem.flow = string.IsNullOrEmpty(vless.Flow) ? "xtls-rprx-origin" : vless.Flow;
outbound.mux.enabled = false;
outbound.mux.concurrency = -1;
}
else
{
outbound.mux.enabled = vless.UseMux ?? Global.Settings.V2RayConfig.UseMux;
outbound.mux.concurrency = vless.UseMux ?? Global.Settings.V2RayConfig.UseMux ? 8 : -1;
}
outbound.protocol = "vless";
outbound.settings.servers = null;
@@ -196,29 +218,25 @@ namespace Netch.Servers.VMess.Utils
{
var vnextItem = new VnextItem
{
users = new List<UsersItem>()
users = new List<UsersItem>(),
address = server.AutoResolveHostname(),
port = server.Port
};
outbound.settings.vnext = new List<VnextItem>
outbound.settings.vnext = new List<VnextItem> {vnextItem};
var usersItem = new UsersItem
{
vnextItem
id = vmess.UserID,
alterId = vmess.AlterID,
security = vmess.EncryptMethod
};
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 ?? Global.Settings.V2RayConfig.UseMux;
outbound.mux.concurrency = vmess.UseMux ?? Global.Settings.V2RayConfig.UseMux ? 8 : -1;
var streamSettings = outbound.streamSettings;
boundStreamSettings(vmess, ref streamSettings);
outbound.mux.enabled = vmess.UseMux ?? Global.Settings.V2RayConfig.UseMux;
outbound.mux.concurrency = vmess.UseMux ?? Global.Settings.V2RayConfig.UseMux ? 8 : -1;
outbound.protocol = "vmess";
break;
}
@@ -229,8 +247,11 @@ namespace Netch.Servers.VMess.Utils
outbound,
new Outbounds
{
tag = "direct",
protocol = "freedom"
tag = "direct", protocol = "freedom"
},
new Outbounds
{
tag = "block", protocol = "blackhole"
}
};
}
@@ -245,25 +266,24 @@ namespace Netch.Servers.VMess.Utils
try
{
streamSettings.network = server.TransferProtocol;
var host = server.Host;
if (server.TLSSecure)
{
streamSettings.security = "tls";
if ((streamSettings.security = server.TLSSecureType) != "")
{
var tlsSettings = new TlsSettings
{
allowInsecure = Global.Settings.V2RayConfig.AllowInsecure
allowInsecure = Global.Settings.V2RayConfig.AllowInsecure,
serverName = !string.IsNullOrWhiteSpace(server.Host) ? server.Host : null
};
if (!string.IsNullOrWhiteSpace(host))
{
tlsSettings.serverName = host;
}
streamSettings.tlsSettings = tlsSettings;
}
else
{
streamSettings.security = "";
switch (server.TLSSecureType)
{
case "tls":
streamSettings.tlsSettings = tlsSettings;
break;
case "xtls":
streamSettings.xtlsSettings = tlsSettings;
break;
}
}
switch (server.TransferProtocol)
@@ -285,21 +305,15 @@ namespace Netch.Servers.VMess.Utils
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
}
headers = !string.IsNullOrWhiteSpace(server.Host)
? new Headers {Host = server.Host}
: null,
path = !string.IsNullOrWhiteSpace(path) ? path : null
path = !string.IsNullOrWhiteSpace(server.Path) ? server.Path : null
};
streamSettings.wsSettings = wsSettings;
@@ -319,40 +333,27 @@ namespace Netch.Servers.VMess.Utils
case "quic":
var quicSettings = new QuicSettings
{
security = host,
security = server.Host,
key = server.Path,
header = new Header
{
type = server.FakeType
}
};
if (server.TLSSecure)
if (server.TLSSecureType != "")
{
// tls or xtls
streamSettings.tlsSettings.serverName = server.Hostname;
}
streamSettings.quicSettings = quicSettings;
break;
case "xtls":
streamSettings.security = server.TransferProtocol;
var xtlsSettings = new TlsSettings
{
allowInsecure = Global.Settings.V2RayConfig.AllowInsecure
};
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,

View File

@@ -23,18 +23,18 @@ namespace Netch.Servers.VMess
/// <summary>
/// 加密方式
/// </summary>
public string EncryptMethod { get; set; } = VMessGlobal.EncryptMethods[0];
public virtual string EncryptMethod { get; set; } = VMessGlobal.EncryptMethods[0];
/// <summary>
/// 传输协议
/// </summary>
public string TransferProtocol { get; set; } = VMessGlobal.TransferProtocols[0];
public virtual string TransferProtocol { get; set; } = VMessGlobal.TransferProtocols[0];
/// <summary>
/// 伪装类型
/// </summary>
public string FakeType { get; set; } = VMessGlobal.FakeTypes[0];
public virtual string FakeType { get; set; } = VMessGlobal.FakeTypes[0];
/// <summary>
/// QUIC
@@ -64,12 +64,12 @@ namespace Netch.Servers.VMess
/// <summary>
/// TLS 底层传输安全
/// </summary>
public bool TLSSecure { get; set; } = false;
public string TLSSecureType { get; set; } = VMessGlobal.TLSSecure[0];
/// <summary>
/// Mux 多路复用
/// </summary>
public bool? UseMux { get; set; } = true;
public bool? UseMux { get; set; } = false;
}
public class VMessGlobal
@@ -114,5 +114,14 @@ namespace Netch.Servers.VMess
"dtls",
"wireguard"
};
/// <summary>
/// TLS 安全类型
/// </summary>
public static readonly List<string> TLSSecure = new List<string>
{
"",
"tls"
};
}
}

View File

@@ -15,14 +15,12 @@ namespace Netch.Servers.VMess
public override string Name { get; protected set; } = "VMess";
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");
}

View File

@@ -49,7 +49,7 @@ namespace Netch.Servers.VMess
type = server.FakeType,
host = server.Host,
path = server.Path,
tls = server.TLSSecure ? "tls" : ""
tls = server.TLSSecureType
});
return "vmess://" + ShareLink.URLSafeBase64Encode(vmessJson);
}
@@ -97,7 +97,7 @@ namespace Netch.Servers.VMess
data.Path = vmess.path;
}
data.TLSSecure = vmess.tls == "tls";
data.TLSSecureType = vmess.tls;
data.EncryptMethod = "auto"; // V2Ray 加密方式不包括在链接中,主动添加一个
return CheckServer(data) ? new[] {data} : null;

View File

@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
@@ -53,7 +52,7 @@ namespace Netch.Utils
/// <summary>
/// 根据程序名统计流量
/// </summary>
public static void NetTraffic(in Server server, in Mode mode)
public static void NetTraffic()
{
if (!Global.Flags.IsWindows10Upper)
return;
@@ -63,26 +62,28 @@ namespace Netch.Utils
//var processList = Process.GetProcessesByName(ProcessName).Select(p => p.Id).ToHashSet();
var instances = new List<Process>();
if (server.Type.Equals("Socks5") && MainController.ModeController.Name == "HTTP")
switch (MainController.ServerController)
{
instances.Add(((HTTPController) MainController.ModeController).pPrivoxyController.Instance);
}
else if (MainController.ServerController != null)
{
switch (MainController.ServerController)
{
case SSController ssController when ssController.DllFlag:
instances.Add(Process.GetCurrentProcess());
break;
case Guard instanceController:
case null:
break;
case SSController ssController when ssController.DllFlag:
instances.Add(Process.GetCurrentProcess());
break;
case Guard instanceController:
if (instanceController.Instance != null)
instances.Add(instanceController.Instance);
break;
}
break;
}
else if (MainController.ModeController != null)
if (!instances.Any())
{
switch (MainController.ModeController)
{
case null:
break;
case HTTPController httpController:
instances.Add(httpController.pPrivoxyController.Instance);
break;
case NFController _:
instances.Add(Process.GetCurrentProcess());
break;
@@ -97,6 +98,13 @@ namespace Netch.Utils
Logging.Info("流量统计进程:" + string.Join(",",
instances.Select(instance => $"({instance.Id})" + instance.ProcessName).ToArray()));
received = 0;
if (!instances.Any())
return;
Global.MainForm.BandwidthState(true);
Task.Run(() =>
{
tSession = new TraceEventSession("KernelAndClrEventsSession");

View File

@@ -30,14 +30,14 @@ namespace Netch.Utils
Global.Settings = settingJObject?.ToObject<Setting>() ?? new Setting();
Global.Settings.Server.Clear();
foreach (JObject server in settingJObject["Server"])
{
var serverResult = ServerHelper.ParseJObject(server);
if (serverResult != null)
Global.Settings.Server.Add(serverResult);
}
if (settingJObject?["Server"] != null)
foreach (JObject server in settingJObject["Server"])
{
var serverResult = ServerHelper.ParseJObject(server);
if (serverResult != null)
Global.Settings.Server.Add(serverResult);
}
}
catch (JsonException)
{
}
@@ -62,7 +62,15 @@ namespace Netch.Utils
Directory.CreateDirectory(DATA_DIR);
}
File.WriteAllText(SETTINGS_JSON, JsonConvert.SerializeObject(Global.Settings, Formatting.Indented));
File.WriteAllText(SETTINGS_JSON,
JsonConvert.SerializeObject(
Global.Settings,
Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}
));
}
}
}

View File

@@ -0,0 +1,99 @@
using System;
using System.Net;
using System.Text;
using System.Threading;
namespace Netch.Utils.HttpProxyHandler
{
public class HttpWebServer
{
private HttpListener _listener;
private Func<HttpListenerRequest, string> _responderMethod;
public HttpWebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
try
{
_listener = new HttpListener();
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
// URI prefixes are required, for example
// "http://localhost:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// A responder method is required
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
_listener.Prefixes.Add(s);
_responderMethod = method;
_listener.Start();
}
catch (Exception ex)
{
Logging.Error("HttpWebServer():" + ex.Message);
}
}
public HttpWebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method)
{
}
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Logging.Info("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
string rstr = _responderMethod(ctx.Request);
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.StatusCode = 200;
ctx.Response.ContentType = "application/x-ns-proxy-autoconfig";
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch
{
} // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
//Logging.Error(ex.Message, ex);
Logging.Error(ex.Message);
} // suppress any exceptions
});
}
public void Stop()
{
if (_listener != null)
{
_listener.Stop();
_listener.Close();
_listener = null;
}
}
}
}

View File

@@ -0,0 +1,124 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using WindowsProxy;
namespace Netch.Utils.HttpProxyHandler
{
/// <summary>
/// 提供PAC功能支持
/// </summary>
class PACServerHandle
{
private static Hashtable httpWebServer = new Hashtable();
private static Hashtable pacList = new Hashtable();
public static void InitPACServer(string address)
{
try
{
if (!pacList.ContainsKey(address))
{
pacList.Add(address, GetPacList(address));
}
string prefixes = string.Format("http://{0}:{1}/pac/", address, Global.Settings.Pac_Port);
HttpWebServer ws = new HttpWebServer(SendResponse, prefixes);
ws.Run();
if (!httpWebServer.ContainsKey(address) && ws != null)
{
httpWebServer.Add(address, ws);
}
Global.Settings.Pac_Url = GetPacUrl();
using var service = new ProxyService
{
AutoConfigUrl = Global.Settings.Pac_Url
};
service.Pac();
Logging.Info(service.Set(service.Query()) + "");
Logging.Info($"Webserver InitServer OK: {Global.Settings.Pac_Url}");
}
catch (Exception ex)
{
Logging.Error("Webserver InitServer " + ex.Message);
}
}
public static string SendResponse(HttpListenerRequest request)
{
try
{
string[] arrAddress = request.UserHostAddress.Split(':');
string address = "127.0.0.1";
if (arrAddress.Length > 0)
{
address = arrAddress[0];
}
return pacList[address].ToString();
}
catch (Exception ex)
{
Logging.Error("Webserver SendResponse " + ex.Message);
return ex.Message;
}
}
public static void Stop()
{
try
{
if (httpWebServer == null)
{
return;
}
foreach (var key in httpWebServer.Keys)
{
Logging.Info("Webserver Stop " + key.ToString());
((HttpWebServer)httpWebServer[key]).Stop();
}
httpWebServer.Clear();
}
catch (Exception ex)
{
Logging.Error("Webserver Stop " + ex.Message);
}
}
private static string GetPacList(string address)
{
try
{
List<string> lstProxy = new List<string>();
lstProxy.Add(string.Format("PROXY {0}:{1};", address, Global.Settings.HTTPLocalPort));
var proxy = string.Join("", lstProxy.ToArray());
string strPacfile = Path.Combine(Global.NetchDir, $"bin\\pac.txt");
var pac = File.ReadAllText(strPacfile, Encoding.UTF8).Replace("__PROXY__", proxy);
return pac;
}
catch
{ }
return "No pac content";
}
/// <summary>
/// 获取PAC地址
/// </summary>
/// <returns></returns>
public static string GetPacUrl()
{
string pacUrl = string.Format("http://127.0.0.1:{0}/pac/?t={1}", Global.Settings.Pac_Port,
DateTime.Now.ToString("yyyyMMddHHmmssfff"));
return pacUrl;
}
}
}

View File

@@ -1,5 +1,4 @@
using System;
using System.Linq;
using System.Management;
using Netch.Controllers;
using Netch.Models.WinFW;

View File

@@ -5,6 +5,8 @@ using System.Linq;
using Netch.Controllers;
using Netch.Forms;
using Netch.Models;
using Netch.Servers.Shadowsocks;
using Netch.Servers.Socks5;
namespace Netch.Utils
{
@@ -14,12 +16,21 @@ namespace Netch.Utils
public static readonly string ModeDirectory = Path.Combine(Global.NetchDir, $"{MODE_DIR}\\");
public static string GetRelativePath(string fullName) => fullName.Substring(ModeDirectory.Length);
public static string GetFullPath(string relativeName) => Path.Combine(ModeDirectory, relativeName);
public static string GetFullPath(Mode mode) => Path.Combine(ModeDirectory, mode.RelativePath);
public static string GetRelativePath(string fullName)
{
return fullName.Substring(ModeDirectory.Length);
}
public static string GetFullPath(string relativeName)
{
return Path.Combine(ModeDirectory, relativeName);
}
public static string GetFullPath(Mode mode)
{
return Path.Combine(ModeDirectory, mode.RelativePath);
}
/// <summary>
/// 从模式文件夹读取模式并为 <see cref="Forms.MainForm.ModeComboBox"/> 绑定数据
/// 从模式文件夹读取模式并为 <see cref="Forms.MainForm.ModeComboBox" /> 绑定数据
/// </summary>
public static void Load()
{
@@ -66,17 +77,19 @@ namespace Netch.Utils
if (i == 0)
{
if (text.First() != '#')
return;
try
{
var splited = text.Substring(text.IndexOf('#') + 1).Split(',').Select(s => s.Trim()).ToArray();
var splited = text.Substring(1).Split(',').Select(s => s.Trim()).ToArray();
mode.Remark = splited[0];
var result = int.TryParse(splited.ElementAtOrDefault(1), out var type);
mode.Type = result ? type : 0;
var typeResult = int.TryParse(splited.ElementAtOrDefault(1), out var type);
mode.Type = typeResult ? type : 0;
var result1 = int.TryParse(splited.ElementAtOrDefault(2), out var bypassChina);
mode.BypassChina = result1 && bypassChina == 1;
var bypassChinaResult = int.TryParse(splited.ElementAtOrDefault(2), out var bypassChina);
mode.BypassChina = mode.ClientRouting() && bypassChinaResult && bypassChina == 1;
}
catch
{
@@ -95,16 +108,12 @@ namespace Netch.Utils
public static void WriteFile(Mode mode)
{
if (!Directory.Exists(ModeDirectory))
{
Directory.CreateDirectory(ModeDirectory);
}
var fullName = GetFullPath(mode.RelativePath ?? mode.FileName + ".txt");
if (mode.RelativePath == null && File.Exists(fullName))
{
throw new Exception("新建模式的文件名已存在,请贡献者检查代码");
}
// 写入到模式文件里
File.WriteAllText(fullName, mode.ToFileString());
@@ -127,14 +136,27 @@ namespace Netch.Utils
{
var fullName = GetFullPath(mode);
if (File.Exists(fullName))
{
File.Delete(fullName);
}
Global.Modes.Remove(mode);
Global.MainForm.InitMode();
}
public static bool SkipServerController(Server server, Mode mode)
{
return mode.Type switch
{
0 => server switch
{
Socks5 => true,
Shadowsocks shadowsocks when !shadowsocks.HasPlugin() && Global.Settings.RedirectorSS => true,
_ => false
},
_ => false
};
}
public static IModeController GetModeControllerByType(int type, out ushort? port, out string portName, out PortType portType)
{
IModeController modeController;
@@ -147,6 +169,7 @@ namespace Netch.Utils
modeController = new NFController();
port = Global.Settings.RedirectorTCPPort;
portName = "Redirector TCP";
portType = PortType.TCP;
break;
case 1:
case 2:
@@ -157,6 +180,7 @@ namespace Netch.Utils
modeController = new HTTPController();
port = Global.Settings.HTTPLocalPort;
portName = "HTTP";
portType = PortType.TCP;
MainForm.StatusPortInfoText.HttpPort = (ushort) port;
break;
case 4:

View File

@@ -24,11 +24,21 @@ namespace Netch.Utils
{
try
{
if (PortHelper.PortInUse(Global.Settings.UDPSocketPort))
{
Global.Settings.UDPSocketPort = PortHelper.GetAvailablePort();
Configuration.Save();
}
const int tryLimit = 3;
var i = tryLimit;
while (i > 0)
try
{
PortHelper.CheckPort(Global.Settings.UDPSocketPort, PortType.UDP);
if (i != tryLimit)
Configuration.Save();
break;
}
catch
{
Global.Settings.UDPSocketPort = PortHelper.GetAvailablePort(PortType.UDP);
i--;
}
var data = new byte[1024];
var newsock = new UdpClient(new IPEndPoint(IPAddress.Loopback, Global.Settings.UDPSocketPort));
@@ -38,9 +48,7 @@ namespace Netch.Utils
var result = await newsock.ReceiveAsync();
data = result.Buffer;
if (Enum.TryParse<Commands>(Encoding.ASCII.GetString(data, 0, data.Length), out var command))
{
OnCalled(command);
}
}
}
catch (Exception e)
@@ -53,14 +61,12 @@ namespace Netch.Utils
{
try
{
using (var udpClient = new UdpClient(Global.Settings.UDPSocketPort))
{
udpClient.Connect(IPAddress.Loopback, Global.Settings.UDPSocketPort);
var sendBytes = Encoding.ASCII.GetBytes(command.ToString());
await udpClient.SendAsync(sendBytes, sendBytes.Length);
using var udpClient = new UdpClient(Global.Settings.UDPSocketPort);
udpClient.Connect(IPAddress.Loopback, Global.Settings.UDPSocketPort);
var sendBytes = Encoding.ASCII.GetBytes(command.ToString());
await udpClient.SendAsync(sendBytes, sendBytes.Length);
udpClient.Close();
}
udpClient.Close();
}
catch (Exception e)
{

View File

@@ -3,20 +3,22 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using Netch.Models;
namespace Netch.Utils
{
public static class PortHelper
{
private static readonly List<ushort[]> TCPExcludedRanges = new List<ushort[]>();
private static readonly List<ushort[]> UDPExcludedRanges = new List<ushort[]>();
private static readonly List<Range> TCPReservedRanges = new();
private static readonly List<Range> UDPReservedRanges = new();
private static readonly IPGlobalProperties NetInfo = IPGlobalProperties.GetIPGlobalProperties();
static PortHelper()
{
try
{
GetExcludedPortRange(PortType.TCP, ref TCPExcludedRanges);
GetExcludedPortRange(PortType.UDP, ref UDPExcludedRanges);
GetReservedPortRange(PortType.TCP, ref TCPReservedRanges);
GetReservedPortRange(PortType.UDP, ref UDPReservedRanges);
}
catch (Exception e)
{
@@ -24,7 +26,7 @@ namespace Netch.Utils
}
}
private static void GetExcludedPortRange(PortType portType, ref List<ushort[]> targetList)
private static void GetReservedPortRange(PortType portType, ref List<Range> targetList)
{
var lines = new List<string>();
var process = new Process
@@ -48,47 +50,20 @@ namespace Netch.Utils
var splitLine = false;
foreach (var line in lines)
{
if (!splitLine)
{
if (line.StartsWith("-"))
{
splitLine = true;
}
}
else
{
if (line == string.Empty)
break;
var value = line.Trim().Split(' ').Where(s => s != string.Empty);
var value = line.Trim().Split(' ').Where(s => s != string.Empty).ToArray();
ushort port = 0;
var _ = (from s1 in value
where ushort.TryParse(s1, out port)
select port).ToArray();
targetList.Add(_);
targetList.Add(new Range(ushort.Parse(value[0]), ushort.Parse(value[1])));
}
}
}
/// <summary>
/// 检查端口是否是保留端口
/// </summary>
/// <param name="port">端口</param>
/// <param name="type">端口类型</param>
/// <returns>是否是保留端口</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private static bool IsPortExcluded(ushort port, PortType type)
{
return type switch
{
PortType.TCP => TCPExcludedRanges.Any(range => range[0] <= port && port <= range[1]),
PortType.UDP => UDPExcludedRanges.Any(range => range[0] <= port && port <= range[1]),
PortType.Both => IsPortExcluded(port, PortType.TCP) || IsPortExcluded(port, PortType.UDP),
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
};
}
/// <summary>
@@ -97,39 +72,83 @@ namespace Netch.Utils
/// <param name="port">端口</param>
/// <param name="type">检查端口类型</param>
/// <returns>是否被占用</returns>
public static bool PortInUse(ushort port, PortType type = PortType.Both)
public static void CheckPort(ushort port, PortType type = PortType.Both)
{
var netInfo = IPGlobalProperties.GetIPGlobalProperties();
var isTcpUsed = type != PortType.UDP &&
(IsPortExcluded(port, PortType.TCP) ||
netInfo.GetActiveTcpListeners().Any(ipEndPoint => ipEndPoint.Port == port));
var isUdpUsed = type != PortType.TCP &&
(IsPortExcluded(port, PortType.UDP) ||
netInfo.GetActiveUdpListeners().Any(ipEndPoint => ipEndPoint.Port == port));
var isPortExcluded = !UsingPorts.Contains(port);
return isPortExcluded && (isTcpUsed || isUdpUsed);
switch (type)
{
case PortType.Both:
CheckPort(port, PortType.TCP);
CheckPort(port, PortType.UDP);
break;
default:
CheckPortInUse(port, type);
CheckPortReserved(port, type);
break;
}
}
private static void CheckPortInUse(ushort port, PortType type)
{
switch (type)
{
case PortType.Both:
CheckPortInUse(port, PortType.TCP);
CheckPortInUse(port, PortType.UDP);
break;
case PortType.TCP:
if (NetInfo.GetActiveTcpListeners().Any(ipEndPoint => ipEndPoint.Port == port))
throw new PortInUseException();
break;
case PortType.UDP:
if (NetInfo.GetActiveUdpListeners().Any(ipEndPoint => ipEndPoint.Port == port))
throw new PortInUseException();
break;
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
}
/// <summary>
/// 检查端口是否是保留端口
/// </summary>
private static void CheckPortReserved(ushort port, PortType type)
{
switch (type)
{
case PortType.Both:
CheckPortReserved(port, PortType.TCP);
CheckPortReserved(port, PortType.UDP);
return;
case PortType.TCP:
if (TCPReservedRanges.Any(range => range.InRange(port)))
throw new PortReservedException();
break;
case PortType.UDP:
if (UDPReservedRanges.Any(range => range.InRange(port)))
throw new PortReservedException();
break;
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
}
public static ushort GetAvailablePort()
public static ushort GetAvailablePort(PortType portType = PortType.Both)
{
var random = new Random();
for (ushort i = 0; i < 55535; i++)
{
var p = (ushort) random.Next(10000, 65535);
if (!PortInUse(p))
try
{
CheckPort(p, portType);
return p;
}
catch (Exception)
{
// ignored
}
}
throw new Exception("Cant Generate Available Port");
throw new Exception();
}
/// <summary>
/// 记录Netch使用的端口
/// </summary>
public static readonly List<ushort> UsingPorts = new List<ushort>();
}
/// <summary>
@@ -145,4 +164,7 @@ namespace Netch.Utils
public class PortInUseException : Exception
{
}
public class PortReservedException : Exception
{
}
}

View File

@@ -2,6 +2,8 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Timers;
using Netch.Models;
using Newtonsoft.Json.Linq;
@@ -9,14 +11,87 @@ namespace Netch.Utils
{
public static class ServerHelper
{
public static readonly IEnumerable<IServerUtil> ServerUtils;
static ServerHelper()
{
var serversUtilsTypes = Assembly.GetExecutingAssembly().GetExportedTypes().Where(type => type.GetInterfaces().Any(t => t == typeof(IServerUtil)));
var serversUtilsTypes = Assembly.GetExecutingAssembly().GetExportedTypes().Where(type => type.GetInterfaces().Contains(typeof(IServerUtil)));
ServerUtils = serversUtilsTypes.Select(t => (IServerUtil) Activator.CreateInstance(t)).OrderBy(util => util.Priority);
}
#region Delay
public static class DelayTestHelper
{
private static readonly Timer Timer;
private static bool _mux;
public static readonly Range Range = new(0, int.MaxValue / 1000);
static DelayTestHelper()
{
Timer = new Timer
{
Interval = 10000,
AutoReset = true
};
Timer.Elapsed += (_, _) => TestAllDelay();
}
public static bool Enabled
{
get => Timer.Enabled;
set
{
if (!ValueIsEnabled(Global.Settings.DetectionTick))
return;
Timer.Enabled = value;
}
}
public static int Interval => (int) (Timer.Interval / 1000);
private static bool ValueIsEnabled(int value)
{
return value != 0 && Range.InRange(value);
}
public static event EventHandler TestDelayFinished;
public static void TestAllDelay()
{
if (_mux)
return;
try
{
_mux = true;
Parallel.ForEach(Global.Settings.Server, new ParallelOptions {MaxDegreeOfParallelism = 16},
server => { server.Test(); });
_mux = false;
TestDelayFinished?.Invoke(null, new EventArgs());
}
catch (Exception)
{
// ignored
}
}
public static void UpdateInterval()
{
Timer.Stop();
if (!ValueIsEnabled(Global.Settings.DetectionTick))
return;
Timer.Interval = Global.Settings.DetectionTick * 1000;
Task.Run(TestAllDelay);
Timer.Start();
}
}
#endregion
#region Handler
public static readonly IEnumerable<IServerUtil> ServerUtils;
public static Server ParseJObject(JObject o)
{
var handle = GetUtilByTypeName((string) o["Type"]);
@@ -47,5 +122,7 @@ namespace Netch.Utils
{
return ServerUtils.FirstOrDefault(i => i.UriScheme.Any(s => s.Equals(typeName)));
}
#endregion
}
}

View File

@@ -233,7 +233,8 @@ namespace Netch.Utils
public static string GetNetchLink(Server s)
{
return "Netch://" + URLSafeBase64Encode(JsonConvert.SerializeObject(s));
var server = (Server) s.Clone();
return "Netch://" + URLSafeBase64Encode(JsonConvert.SerializeObject(server, new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}));
}
}
}

46
Netch/Utils/StringEx.cs Normal file
View File

@@ -0,0 +1,46 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Netch.Utils
{
static class StringEx
{
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
public static bool IsNullOrWhiteSpace(this string value)
{
return string.IsNullOrWhiteSpace(value);
}
public static bool BeginWithAny(this string s, IEnumerable<char> chars)
{
if (s.IsNullOrEmpty()) return false;
return chars.Contains(s[0]);
}
public static bool IsWhiteSpace(this string value)
{
foreach (var c in value)
{
if (char.IsWhiteSpace(c)) continue;
return false;
}
return true;
}
public static IEnumerable<string> NonWhiteSpaceLines(this TextReader reader)
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.IsWhiteSpace()) continue;
yield return line;
}
}
}
}

View File

@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Netch.Models;
namespace Netch.Utils
{
public static class Subscription
{
private static readonly object ServerLock = new object();
public static async Task UpdateServersAsync(string proxyServer = default)
{
await Task.WhenAll(
Global.Settings.SubscribeLink.Select(item =>
Task.Run(() => UpdateServer(item, proxyServer))
).ToArray()
);
}
public static void UpdateServer(SubscribeLink item, string proxyServer)
{
try
{
if (!item.Enable)
{
return;
}
var request = WebUtil.CreateRequest(item.Link);
if (!string.IsNullOrEmpty(item.UserAgent)) request.UserAgent = item.UserAgent;
if (!string.IsNullOrEmpty(proxyServer)) request.Proxy = new WebProxy(proxyServer);
List<Server> servers;
var result = WebUtil.DownloadString(request, out var rep);
if (rep.StatusCode == HttpStatusCode.OK)
servers = ShareLink.ParseText(result);
else
throw new Exception($"{item.Remark} Response Status Code: {rep.StatusCode}");
foreach (var server in servers) server.Group = item.Remark;
lock (ServerLock)
{
Global.Settings.Server.RemoveAll(server => server.Group.Equals(item.Remark));
Global.Settings.Server.AddRange(servers);
}
Global.MainForm.NotifyTip(i18N.TranslateFormat("Update {1} server(s) from {0}", item.Remark, servers.Count));
}
catch (Exception e)
{
Global.MainForm.NotifyTip($"{i18N.TranslateFormat("Update servers error from {0}", item.Remark)}\n{e.Message}", info: false);
Logging.Error(e.ToString());
}
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
@@ -7,10 +7,12 @@ using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MaxMind.GeoIP2;
using TaskScheduler;
namespace Netch.Utils
{
@@ -37,12 +39,12 @@ namespace Netch.Utils
public static async Task<int> TCPingAsync(IPAddress ip, int port, int timeout = 1000, CancellationToken ct = default)
{
using var client = new TcpClient(ip.AddressFamily);
var stopwatch = Stopwatch.StartNew();
var task = client.ConnectAsync(ip, port);
var stopwatch = new Stopwatch();
stopwatch.Start();
var resTask = await Task.WhenAny(Task.Delay(timeout, ct), task);
var resTask = await Task.WhenAny(task, Task.Delay(timeout, ct));
stopwatch.Stop();
if (resTask == task && client.Connected)
@@ -54,12 +56,20 @@ namespace Netch.Utils
return timeout;
}
public static async Task<int> ICMPing(IPAddress ip, int timeout = 1000)
{
var reply = new Ping().Send(ip, timeout);
if (reply?.Status == IPStatus.Success)
return Convert.ToInt32(reply.RoundtripTime);
return timeout;
}
public static string GetCityCode(string Hostname)
{
if (Hostname.Contains(":"))
{
Hostname = Hostname.Split(':')[0];
}
string Country;
try
@@ -75,13 +85,9 @@ namespace Netch.Utils
var DnsResult = DNS.Lookup(Hostname);
if (DnsResult != null)
{
Country = databaseReader.Country(DnsResult).Country.IsoCode;
}
else
{
Country = "Unknown";
}
}
}
catch (Exception)
@@ -96,7 +102,7 @@ namespace Netch.Utils
{
try
{
var sha256 = System.Security.Cryptography.SHA256.Create();
var sha256 = SHA256.Create();
var fileStream = File.OpenRead(filePath);
return sha256.ComputeHash(fileStream).Aggregate(string.Empty, (current, b) => current + b.ToString("x2"));
}
@@ -124,7 +130,10 @@ namespace Netch.Utils
}
}
public static string GetFileVersion(string file) => File.Exists(file) ? FileVersionInfo.GetVersionInfo(file).FileVersion : string.Empty;
public static string GetFileVersion(string file)
{
return File.Exists(file) ? FileVersionInfo.GetVersionInfo(file).FileVersion : string.Empty;
}
public static bool SearchOutboundAdapter(bool logging = true)
{
@@ -181,19 +190,12 @@ namespace Netch.Utils
{
e.DrawBackground();
if (e.Index >= 0)
{
var brush = new SolidBrush(cbx.ForeColor);
if (e.Index < 0)
return;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
brush = SystemBrushes.HighlightText as SolidBrush;
e.Graphics.DrawString(cbx.Items[e.Index].ToString(), cbx.Font, brush, e.Bounds, new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center
});
}
TextRenderer.DrawText(e.Graphics, cbx.Items[e.Index].ToString(), cbx.Font, e.Bounds,
(e.State & DrawItemState.Selected) == DrawItemState.Selected ? SystemColors.HighlightText : cbx.ForeColor,
TextFormatFlags.HorizontalCenter);
}
}
@@ -202,34 +204,32 @@ namespace Netch.Utils
func.Invoke(component);
switch (component)
{
case ListView listView:
// ListView sub item
foreach (var item in listView.Columns.Cast<ColumnHeader>())
ComponentIterator(item, func);
break;
case ToolStripMenuItem toolStripMenuItem:
// Iterator Menu strip sub item
foreach (var item in toolStripMenuItem.DropDownItems.Cast<ToolStripItem>())
{
ComponentIterator(item, func);
}
break;
case MenuStrip menuStrip:
// Menu Strip
foreach (var item in menuStrip.Items.Cast<ToolStripItem>())
{
ComponentIterator(item, func);
}
break;
case ContextMenuStrip contextMenuStrip:
foreach (var item in contextMenuStrip.Items.Cast<ToolStripItem>())
{
ComponentIterator(item, func);
}
break;
case Control control:
foreach (var c in control.Controls.Cast<Control>())
{
ComponentIterator(c, func);
}
if (control.ContextMenuStrip != null)
ComponentIterator(control.ContextMenuStrip, func);
@@ -237,5 +237,62 @@ namespace Netch.Utils
break;
}
}
public static void RegisterNetchStartupItem()
{
var scheduler = new TaskSchedulerClass();
scheduler.Connect();
var folder = scheduler.GetFolder("\\");
var taskIsExists = false;
try
{
folder.GetTask("Netch Startup");
taskIsExists = true;
}
catch
{
// ignored
}
if (Global.Settings.RunAtStartup)
{
if (taskIsExists)
folder.DeleteTask("Netch Startup", 0);
var task = scheduler.NewTask(0);
task.RegistrationInfo.Author = "Netch";
task.RegistrationInfo.Description = "Netch run at startup.";
task.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;
task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);
var action = (IExecAction) task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
action.Path = Application.ExecutablePath;
task.Settings.ExecutionTimeLimit = "PT0S";
task.Settings.DisallowStartIfOnBatteries = false;
task.Settings.RunOnlyIfIdle = false;
folder.RegisterTaskDefinition("Netch Startup", task, (int) _TASK_CREATION.TASK_CREATE, null, null,
_TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");
}
else
{
if (taskIsExists)
folder.DeleteTask("Netch Startup", 0);
}
}
public static void ChangeControlForeColor(Component component, Color color)
{
switch (component)
{
case TextBox _:
case ComboBox _:
if (((Control) component).ForeColor != color) ((Control) component).ForeColor = color;
break;
}
}
}
}

View File

@@ -8,8 +8,13 @@ namespace Netch.Utils
{
public static class WebUtil
{
static WebUtil()
{
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
}
public const string DefaultUserAgent =
@"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36";
@"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.55";
private static int DefaultGetTimeout => Global.Settings.RequestTimeout;
@@ -94,4 +99,4 @@ namespace Netch.Utils
fileStream.Flush();
}
}
}
}

View File

@@ -121,6 +121,9 @@ namespace Netch.Utils
case ToolStripItem c:
c.Text = Translate(c.Text);
break;
case ColumnHeader c:
c.Text = Translate(c.Text);
break;
}
});
}

View File

@@ -1,67 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Platforms>x86;x64</Platforms>
<ProjectGuid>{A8715AF4-ACC6-43F9-9381-4294C5360623}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>NetchLib</RootNamespace>
<AssemblyName>NetchLib</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningsAsErrors />
<NoWarn />
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x86'">
<DefineConstants>DEBUG;TRACE</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn />
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningsAsErrors />
<OutputPath>bin\x86\Debug\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn />
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningsAsErrors />
<OutputPath>bin\x86\Release\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn />
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningsAsErrors />
<OutputPath>bin\x64\Release\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SearchComboBox.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<Platforms>x64</Platforms>
<UseWindowsForms>true</UseWindowsForms>
<LangVersion>latest</LangVersion>
</PropertyGroup>
</Project>

View File

@@ -75,7 +75,7 @@ namespace System.Windows.Forms
private bool IsOriginalItems => Items.Count == AutoFillTag.Length;
private void ResetCompletionList()
public void ResetCompletionList()
{
Keyword = null;
try

View File

@@ -5,7 +5,6 @@
[![Version](https://img.shields.io/github/v/release/NetchX/Netch)](https://github.com/NetchX/Netch/releases)
[![Downloads](https://img.shields.io/github/downloads/NetchX/Netch/total.svg)](https://github.com/NetchX/Netch/releases)
[![Netch CI](https://github.com/NetchX/Netch/workflows/Netch%20CI/badge.svg)](https://github.com/NetchX/Netch/actions)
[![Website](https://img.shields.io/website?url=https%3A%2F%2Fnetch.org)](https://netch.org/)
[![License](https://img.shields.io/badge/license-MIT-yellow.svg)](LICENSE)
[中文说明](/docs/README.zh-CN.md)
@@ -41,9 +40,7 @@ As well, Netch avoid the restricted NAT problem caused by SSTap. You can use an
- [RabbitHosts](https://rabbithosts.com/cart.php)
- [ManSora](https://www.mansora.co/cart.php)
- [ExCloud](https://excloud.net/cart.php)
- [NyanCat](https://nyancat.info/register)
- [YoYu](https://home.yoyu.ltd/cart.php)
## Donate
- XMR *48ju3ELNZEa6wwPBMexCJ9G218BGY2XwhH6B6bmkFuJ3QgM4hPw2Pra35jPtuBZSc7SLNWeBpiWJZWjQeMAiLnTx2tH2Efx*
@@ -62,9 +59,10 @@ As well, Netch avoid the restricted NAT problem caused by SSTap. You can use an
- [go-tun2socks](https://github.com/eycorsican/go-tun2socks)
- [shadowsocks-libev](https://github.com/shadowsocks/shadowsocks-libev)
- [shadowsocksr-libev](https://github.com/shadowsocksrr/shadowsocksr-libev)
- [v2ray-core](https://github.com/v2ray/v2ray-core)
- [v2ray-core](https://github.com/v2fly/v2ray-core)
- [trojan](https://github.com/trojan-gfw/trojan)
- [ACL4SSR](https://github.com/ACL4SSR/ACL4SSR)
- [PAC](https://github.com/HMBSbige/Text_Translation/blob/master/ShadowsocksR/ss_white.pac)
- [dnsmasq-china-list](https://github.com/felixonmars/dnsmasq-china-list)
- [tap-windows6](https://github.com/OpenVPN/tap-windows6)
- [Privoxy](https://www.privoxy.org/)

View File

@@ -34,19 +34,21 @@
### 模式 1 进程代理模式
- 根据进程名进行代理
- 底层依赖于 [NetFilter SDK](https://netfiltersdk.com) 和 Redirector.exe未开源
- 底层依赖于 [NetFilter SDK](https://netfiltersdk.com)
- 对于第一次使用 Netch 的用户而言,不需要做多余的事情
- 若 [NetFilter SDK](https://netfiltersdk.com) 的驱动不存在,会自动安装
- 若驱动版本过低,会自动更新
范例文件
在这个模式里,第一行只有备注是有用的
在这个模式里,第一行只有备注是有用的规则内容支持C++正则表达式
```
# 备注
进程名 1会被代理
进程名 2
!进程名 2(不会被代理)
csgo.exe
\\steam\\代理运行路径包含steam的所有程序
...
```
@@ -131,7 +133,7 @@
## Socks 5 代理中转
说明一下Netch 并非是以网页代理为目的开发的程序,如果需要网络代理为目的的程序,需要 PAC规则分流订阅管理等功能的请参考使用以下软件而非 Netch均为 Windows 平台)
说明一下Netch 并非是以网页代理为目的开发的程序,如果需要网络代理为目的的程序,需要 PAC规则分流订阅管理等功能的尽量参考使用以下软件而非 Netch均为 Windows 平台)
ShadowsocksR

View File

@@ -5,7 +5,6 @@
[![版本](https://img.shields.io/github/v/release/NetchX/Netch)](https://github.com/NetchX/Netch/releases)
[![下载](https://img.shields.io/github/downloads/NetchX/Netch/total.svg)](https://github.com/NetchX/Netch/releases)
[![Netch CI](https://github.com/NetchX/Netch/workflows/Netch%20CI/badge.svg)](https://github.com/NetchX/Netch/actions)
[![网站](https://img.shields.io/website?url=https%3A%2F%2Fnetch.org)](https://netch.org/)
[![License](https://img.shields.io/badge/license-MIT-yellow.svg)](LICENSE)
游戏加速工具
@@ -44,9 +43,7 @@ Netch 是一款 Windows 平台的开源游戏加速工具Netch 可以实现
- [RabbitHosts](https://rabbithosts.com/cart.php)
- [ManSora](https://www.mansora.co/cart.php)
- [ExCloud](https://excloud.net/cart.php)
- [NyanCat](https://nyancat.info/register)
- [YoYu](https://home.yoyu.ltd/cart.php)
## 捐赠
- XMR *48ju3ELNZEa6wwPBMexCJ9G218BGY2XwhH6B6bmkFuJ3QgM4hPw2Pra35jPtuBZSc7SLNWeBpiWJZWjQeMAiLnTx2tH2Efx*
@@ -71,9 +68,10 @@ Netch 支持多种语言,在启动时会根据系统语言选择自身语言
- [go-tun2socks](https://github.com/eycorsican/go-tun2socks)
- [shadowsocks-libev](https://github.com/shadowsocks/shadowsocks-libev)
- [shadowsocksr-libev](https://github.com/shadowsocksrr/shadowsocksr-libev)
- [v2ray-core](https://github.com/v2ray/v2ray-core)
- [v2ray-core](https://github.com/v2fly/v2ray-core)
- [trojan](https://github.com/trojan-gfw/trojan)
- [ACL4SSR](https://github.com/ACL4SSR/ACL4SSR)
- [PAC](https://github.com/HMBSbige/Text_Translation/blob/master/ShadowsocksR/ss_white.pac)
- [dnsmasq-china-list](https://github.com/felixonmars/dnsmasq-china-list)
- [tap-windows6](https://github.com/OpenVPN/tap-windows6)
- [Privoxy](https://www.privoxy.org/)

2
modes

Submodule modes updated: 3ac9f3c380...e3ae0d5406