Repository: shadowsocks/shadowsocks-windows
Branch: v4
Commit: 891d971682ee
Files: 138
Total size: 933.1 KB
Directory structure:
gitextract_s4mmpmuw/
├── .gitattributes
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report_en.md
│ │ ├── bug_report_zh.md
│ │ └── feature_request.md
│ └── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── CHANGES
├── CONTRIBUTING.md
├── LICENSE.txt
├── OPENSSL-GUIDE
├── README.md
├── appveyor.yml
├── appveyor.yml.obsolete
├── appveyor.yml.sample
├── packaging/
│ └── upload.sh
├── shadowsocks-csharp/
│ ├── CommandLineOption.cs
│ ├── Controller/
│ │ ├── FileManager.cs
│ │ ├── HotkeyReg.cs
│ │ ├── I18N.cs
│ │ ├── LoggerExtension.cs
│ │ ├── Service/
│ │ │ ├── GeositeUpdater.cs
│ │ │ ├── IPCService.cs
│ │ │ ├── Listener.cs
│ │ │ ├── OnlineConfigResolver.cs
│ │ │ ├── PACDaemon.cs
│ │ │ ├── PACServer.cs
│ │ │ ├── PortForwarder.cs
│ │ │ ├── PrivoxyRunner.cs
│ │ │ ├── Sip003Plugin.cs
│ │ │ ├── TCPRelay.cs
│ │ │ ├── UDPRelay.cs
│ │ │ └── UpdateChecker.cs
│ │ ├── ShadowsocksController.cs
│ │ ├── Strategy/
│ │ │ ├── BalancingStrategy.cs
│ │ │ ├── HighAvailabilityStrategy.cs
│ │ │ ├── IStrategy.cs
│ │ │ └── StrategyManager.cs
│ │ └── System/
│ │ ├── AutoStartup.cs
│ │ ├── Hotkeys/
│ │ │ ├── HotkeyCallbacks.cs
│ │ │ └── Hotkeys.cs
│ │ ├── ProtocolHandler.cs
│ │ └── SystemProxy.cs
│ ├── Data/
│ │ ├── NLog.config
│ │ ├── abp.js
│ │ ├── i18n.csv
│ │ ├── privoxy_conf.txt
│ │ └── user-rule.txt
│ ├── Encryption/
│ │ ├── AEAD/
│ │ │ ├── AEADEncryptor.cs
│ │ │ ├── AEADMbedTLSEncryptor.cs
│ │ │ ├── AEADOpenSSLEncryptor.cs
│ │ │ └── AEADSodiumEncryptor.cs
│ │ ├── CircularBuffer/
│ │ │ └── ByteCircularBuffer.cs
│ │ ├── EncryptorBase.cs
│ │ ├── EncryptorFactory.cs
│ │ ├── Exception/
│ │ │ └── CryptoException.cs
│ │ ├── IEncryptor.cs
│ │ ├── MbedTLS.cs
│ │ ├── OpenSSL.cs
│ │ ├── RNG.cs
│ │ ├── Sodium.cs
│ │ └── Stream/
│ │ └── PlainEncryptor.cs
│ ├── FodyWeavers.xml
│ ├── FodyWeavers.xsd
│ ├── Localization/
│ │ ├── LocalizationProvider.cs
│ │ ├── Strings.Designer.cs
│ │ ├── Strings.fr.resx
│ │ ├── Strings.ja.resx
│ │ ├── Strings.ko.resx
│ │ ├── Strings.resx
│ │ ├── Strings.ru.resx
│ │ ├── Strings.zh-Hans.resx
│ │ └── Strings.zh-Hant.resx
│ ├── Model/
│ │ ├── Configuration.cs
│ │ ├── ForwardProxyConfig.cs
│ │ ├── Geosite/
│ │ │ ├── Geosite.cs
│ │ │ └── geosite.proto
│ │ ├── HotKeyConfig.cs
│ │ ├── LogViewerConfig.cs
│ │ ├── NlogConfig.cs
│ │ ├── Server.cs
│ │ └── SysproxyConfig.cs
│ ├── Program.cs
│ ├── Properties/
│ │ ├── AssemblyInfo.cs
│ │ ├── Resources.Designer.cs
│ │ ├── Resources.resx
│ │ ├── Settings.Designer.cs
│ │ └── Settings.settings
│ ├── Proxy/
│ │ ├── DirectConnect.cs
│ │ ├── HttpProxy.cs
│ │ ├── IProxy.cs
│ │ └── Socks5Proxy.cs
│ ├── Resources/
│ │ ├── ss128.pdn
│ │ └── ss32.pdn
│ ├── Settings.cs
│ ├── Util/
│ │ ├── ProcessManagement/
│ │ │ ├── Job.cs
│ │ │ └── ThreadUtil.cs
│ │ ├── Sockets/
│ │ │ ├── LineReader.cs
│ │ │ ├── SocketUtil.cs
│ │ │ └── WrappedSocket.cs
│ │ ├── SystemProxy/
│ │ │ ├── ProxyException.cs
│ │ │ └── Sysproxy.cs
│ │ ├── Util.cs
│ │ └── ViewUtils.cs
│ ├── View/
│ │ ├── ConfigForm.Designer.cs
│ │ ├── ConfigForm.cs
│ │ ├── ConfigForm.resx
│ │ ├── LogForm.Designer.cs
│ │ ├── LogForm.cs
│ │ ├── LogForm.resx
│ │ └── MenuViewController.cs
│ ├── ViewModels/
│ │ ├── ForwardProxyViewModel.cs
│ │ ├── HotkeysViewModel.cs
│ │ ├── OnlineConfigViewModel.cs
│ │ ├── ServerSharingViewModel.cs
│ │ └── VersionUpdatePromptViewModel.cs
│ ├── Views/
│ │ ├── ForwardProxyView.xaml
│ │ ├── ForwardProxyView.xaml.cs
│ │ ├── HotkeysView.xaml
│ │ ├── HotkeysView.xaml.cs
│ │ ├── OnlineConfigView.xaml
│ │ ├── OnlineConfigView.xaml.cs
│ │ ├── ServerSharingView.xaml
│ │ ├── ServerSharingView.xaml.cs
│ │ ├── VersionUpdatePromptView.xaml
│ │ └── VersionUpdatePromptView.xaml.cs
│ ├── app.config
│ ├── app.manifest
│ ├── packages.config
│ └── shadowsocks-csharp.csproj
├── shadowsocks-windows.sln
└── test/
├── ProcessEnvironment.cs
├── Properties/
│ └── AssemblyInfo.cs
├── ShadowsocksTest.csproj
├── Sip003PluginTest.cs
├── UnitTest.cs
├── UrlTest.cs
├── app.config
└── packages.config
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
* text=auto
# geosite database
*.dat binary
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report_en.md
================================================
---
name: Bug report (English)
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
### Describe the bug
### Environment
- Shadowsocks client version:
- OS version:
- .NET version:
### Steps you have tried
### What did you expect to see?
### What did you see instead?
### Config and error log in detail (with all sensitive info masked)
```
PASTE LOG HERE
```
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report_zh.md
================================================
---
name: Bug报告 (中文)
about: 反馈Bug
title: ''
labels: bug report
assignees: ''
---
### 简要描述问题
### 环境
- Shadowsocks客户端版本:
- 操作系统版本:
- .NET版本:
### 操作步骤
### 期望的结果
### 实际结果
### 配置文件和日志文件(请隐去敏感信息)
```
在此粘贴日志
```
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
## Please follow the guide below
- You will be asked some questions, please read them **carefully** and answer honestly
- Put an `x` into all the boxes [ ] relevant to your *pull request* (like that [x])
- Use *Preview* tab to see how your *pull request* will actually look like
- [ ] [Searched](https://github.com/shadowsocks/shadowsocks-windows/search?q=is%3Apr&type=Issues) for similar pull requests
- [ ] Compiled the code with Visual Studio
- [ ] Require translation update
- [ ] Require document update (readme.md, wikipage, etc)
### What is the purpose of your *pull request*?
- [ ] Bug fix
- [ ] Improvement
- [ ] New feature
---
### Description of your *pull request* and other information
Explanation of your *pull request* in arbitrary form goes here. Please make sure the description explains the purpose and effect of your *pull request* and is worded well enough to be understood. Provide as much context and examples as possible.
================================================
FILE: .gitignore
================================================
## Ignore Visual Studio and VSCode temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
## and https://github.com/github/gitignore/blob/master/Global/VisualStudioCode.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*[.json, .xml, .info]
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
# *.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
================================================
FILE: CHANGES
================================================
4.4.1.0 2022-02-08
- Add plain/none ciphers
4.4.0.0 2021-01-01
- Security: remove infrastructure of stream ciphers (#3048)
- Show warning message when importing from deprecated legacy ss:// links.
- Other minor bug fixes and improvements
4.3.3.0 2020-12-07
- PAC: Add option for custom sha256sum URL of custom geosite source (#3026)
- Update to .NET Framework 4.8
- Other minor bug fixes and improvements
4.3.2.0 2020-11-05
- PAC: direct connection for private IP ranges by @studentmain (#3008)
- Remove duplicate startup entries (#3012)
- Other minor bug fixes and improvements
4.3.1.0 2020-10-25
- Update abp.js (#2999)
- Separate QR code scanning from MenuViewController (#2995)
- Remove statistics strategy (#2994)
- Other minor bug fixes and improvements
4.3.0.0 2020-10-19
- Cleanup and update dependencies (#2983)
- Geosite group validation + PAC regeneration on version update (#2988)
- PAC: add options for direct and proxied groups (#2990)
- Transition to WPF: ForwardProxyView + HotkeysView + OnlineConfigView + VersionUpdatePromptView (#2991)
4.2.1.0 2020-10-12
- SIP008 support (#2942)
- Exclude @cn from PAC proxied list (#2982)
- Transition to WPF: ReactiveUI and ServerSharingView (#2959)
- User-Agent for OnlineConfigResolver and GeositeUpdater (#2978)
4.2.0.1 2020-09-26
- Fix domain rule handling in PAC script (#2956)
4.2.0.0 2020-09-10
- Update TCPHandler.lastActivity (#2858)
- Add Franch translation (#2861)
- New option for ss:// URL association (#2855)
- Updated Korean Language (#2871)
- Decouple statistic and TCPRelay (#2872)
- Fix nLogConfig NullReferenceExceltion (#2887)
- Use v2ray GeoSsite to replace GFWList (#2875)
- Optimize the updater and downloader (#2910)
- Update SIP002 (#2904)
- Update Japanese translations
- Fix improperly parsed remark section (#2935)
- Other minor bug fixes and improvements
4.1.10.0 2020-04-11
- Fix NLog config file issue (#2841, #2846)
- Tweak log level
4.1.9.3 2020-03-31
- Set default method to chacha20-ietf-poly1305
- Using hash in PAC URL (#2759)
- Rename and translate title of statistics form (#2768)
- Russian translation (#2767)
- Refine Updated Notification logic
- Using NLog (#2783)
- Bug fix: wrong server in tray menu (#2782)
- Deprecate unsafe encryption method (#2757, #2801)
- Bug fix: server config is overwritten by others when moving up/down (#2830)
- Other minor bug fixes and improvements
4.1.9.2 2019-12-25
- Fix i18n issues (#2740, #2741)
4.1.9.1 2019-12-22
- Fix #2739: PAC does not work
- Translate Show Plugin Option
4.1.9.0 2019-12-21
- Refine merge PAC+abp script logic (#2598)
- Format the proxy hostname in GfwListUpdater (#2616)
- Fix the trayIcon display issue under Win10 dark theme (#2658)
- Set default encryption method as chacha20-ietf-poly1305 (#2699)
- Translate statistics config form (#2698)
- Update .Net Framework download link (#2731)
- Use MD5 hash instead of timestamp for PAC URL parameter (#2705)
- Add option "Show Plugin Output" (#2722)
- Support custom GFWListUrl defined in config file (#2728)
- Implement new I18N csv structure (#2712)
- Refine message when plugin program file does not exist (#2730)
- Other minor bug fixes and improvements
4.1.8 2019-10-31
- Update the nuget configurations and packages
- Fix some crash about thread-safe in statistics (#2591)
- Fix server list index invalidation (#2543, #2542)
- Refine PAC server (#2539)
- Update the GFWList via IPv6Loopback when available
- Modify PAC request behavior (#2526)
- Fix .NET 4.7.2 on Win7 TLS compatibility (#2473)
- Other minor bug fixes and improvements
4.1.7.1 2019-07-14
- Fix unexpected server delete behavior (#2459)
- Reduce info log when checking Windows 10 Light Theme
4.1.7 2019-07-10
- Fix UDP relay (#2387)
- Support Windows 10 1903 Light Theme (#2379)
- Listening on local IPv6 interface (#2419) (Experimental)
- Turn off per-monitor DPI awareness as it is not supported (#2427)
- Fix a defect when parsing ss:// URL (#2364)
- Upgrade the development environment to VS2017 with .NET Framework 4.7.2
- Refactoring config form (#2410)
- Refactoring tray icon
- Other minor bug fixes and improvements
4.1.6 2019-04-17
- Add http proxy "basic access authentication"
- Add check box to toggle plugin argument input
- Add apply button for server configuration form
- Update UI of switching proxy mode
- Update exception handler for port assignment
4.1.5 2019-03-08
- Update nuget packages
- Update the PAC javascript to support user rules in a better way
- Other minor bug fixes and improvements
4.1.4 2019-02-04
- Update Privoxy to 3.0.28
- Enlarge Privoxy max client connections
- Update the system proxy when user-rule.txt is changed
- Register restart after system reboot
4.1.3.1 2018-12-09
- Fix error when usersettings bypasslist is null
4.1.3 2018-12-08
- Refine sysproxy exception handling
- Keep user bypass setting when use global proxy mode
- Update .Net download link
- Minor improvements
4.1.2 2018-09-13
- Fix plugin CLI argument environment variable issue (#1969 #1818)
- Other minor bug fixes and improvements (#1978 #1968 #1993)
4.1.1 2018-08-18
- Fix auto hotkey reg issue when OS wakeup
- Other minor bug fixes and improvements
4.1.0 2018-08-05
- Support portable mode Temp folder
- Register hotkeys on startup
- Fix sysproxy hanging issue
- Minor improvements
4.0.10 2018-05-10
- Add square bracket for SIP002 IPv6 (RFC3986)
- Add plugin CLI arguments support
- Bug fix: Server address should not be encoded (#1758)
- Bug fix: Wrong splash on multi display (#1729)
- Fix PerPixelAlphaForm's issue in designer
- Other minor bug fixes and improvements
4.0.9 2018-03-14
- Fix port occupied issue
- Add xchacha20-ietf-poly1305
- Update cryptographic libraries
- Bug fixes and improvements
4.0.8 2018-02-16
- Add OpenSSL 1.1.0g support #1671
- Update nuget packages
- Bug fixes and improvements
4.0.7 2017-12-09
- Fix QR code and ss:// protocol import issue
- Add an option to show password
- User rules have higher priority in PAC file
- Bug fixes and improvements
4.0.6 2017-09-09
- SIP002 support
- SIP003 support
4.0.5 2017-08-09
- Fix crash when user-wininet.json fail to parse. (#1178)
- Bug fixes and improvements.
4.0.4 2017-06-01
- Save user wininet settings as user-wininet.json
- Improve performance of aes-256-gcm
4.0.2 2017-05-19
- Fix legacy key derivation
- Bug fixes and improvements
4.0.1 2017-04-08
- Fix UDP relay
- Allow to add multiple servers via Shadowsocks URL
- Bug fixes and improvements
4.0 2017-04-04
- Add AEAD ciphers support, removed OTA
- I18N: add Japanese support, update Traditional Chinese strings
- sysproxy: restore user settings when system proxy is turned off
- Bug fixes and improvements
3.4.3 2017-1-11
- Make the previous portable mode as default
- Refine networking by Noisyfox
- Bug fixes and improvements
3.4.2.1 2016-12-30
- Refine Traditional Chinese translation by LNDDYL
- sysproxy: reduce false positives on virus detection
- sysproxy: set LAN proxy settings even if RAS query fails
- privoxy: drop obsolete tray area refreshing code
- Fix auto startup
- Bug fixes and improvements
3.4.2 2016-12-16
- Fix null ref in TCPRelay. (#940)
- Bring Privoxy back. (#948)
- Bug fixes and improvements.
3.4.1 (pre-release) 2016-12-13
- Fix crash if user input an invaild server address. (#933)
- Fix ERR_TOO_MANY_REDIRECTS with http proxy. (#937)
- Show SS URL in QRCode form.
- Add import URL from clipboard.
- Bug fixes and improvements.
3.4.0 (pre-release) 2016-12-9
- Replace Privoxy with built-in http proxy.
- Try fix system proxy settings on windows 10 insider preview.
- Secure local pac.
- Update bypass list.
- Bug fixes and improvements.
3.3.6 2016-12-6
- Refine system proxy mode switching logic,
merge 'Switch to PAC' and 'Switch to Global' into
'Switch system proxy mode'.
- Don't store LogViewer window size in config file,
now you can sync config between devices with different
resolutions.
- Add tag support for SS url
- Add pre-release channel in update checker
- Bug fixes and improvements
3.3.5 2016-11-7
- Improve system power mode handling
- Update mbed TLS to 2.4.0
- Check .NET Framework version on startup
3.3.4 2016-10-21
- Fix IE dial-up and VPN connection proxy settings
not changed since release 3.3.3.
- Fix a UI bug
3.3.3 2016-10-10
- Add timeout support for server and forward proxy,
only integer is allowed
- Use wininet API to setup system proxy
- Upgrade to .NET Framework 4.6.2
3.3.2 2016-10-03
- Add HTTP forward proxy support
- Bug fixes and improvements
3.3.1 2016-09-20
- Add global hotkey support
- Bug fixes and improvements
3.3 2016-09-09
- Update Privoxy to 3.0.26
- Change minimum system version explicitly to Windows Vista
since we are using dual-mode socket
- Support running multiple instances of Privoxy for system proxy
- Improve networking
- New traffic chart and icon style
- I18N: Traditional Chinese support
- Bug fixes and improvements
3.2 2016-08-13
- Add AES-CTR, blowfish and camellia ciphers support,
including aes-256-ctr, aes-192-ctr, aes-128-ctr,
bf-cfb, camellia-128-cfb, camellia-192-cfb
and camellia-256-cfb.
- Support one-time authentication in ss urls for sharing
- Support traffic chart and traffic icon
- Add proxy support
- Add verbose logging
- Improve LogForm
- Delete log file when clicking "Clean Logs" in the LogForm
- Bug fixes and improvements
3.1 2016-05-01
- Disable StatisticsStrategy by default
3.0 2016-03-02
- Update Privoxy to 3.0.24
- Replace Choose by Total Packet Loss with Choose by Statistics
- Support chacha20-ietf
- Support Onetime Authentication
- Optional checking updates
- Download updates automatically
- Improve log viewer
- Minor fixes
- Other improvements
2.5.8 2015-09-20
- Update GFWList url
2.5.7 2015-09-19
- Fix repeated IV
2.5.6 2015-08-19
- Add portable mode. Create shadowsocks_portable_mode.txt to use it
- Support server reorder
2.5.5 2015-08-17
- Fix crash when enabling Availability Statistics and some servers can not be resolved
- Allow multiple instances
- Other fixes
2.5.4 2015-08-16
- Hide Privoxy icon
2.5.3 2015-08-16
- Replace Polipo with Privoxy
- Add Choose by Total Packet Loss
2.5.2 2015-08-04
- Add log viewer
2.5.1 2015-07-26
- Prevent HA from switching servers too frequently
- Fix server settings can not be updated when using HA
- Fix server port can't be 8123
- Other minor fixes
2.5 2015-07-25
- Support load balance
- Support high availability
2.4 2015-07-11
- Support UDP relay
- Support online PAC
- Migrate update checker to GitHub releases
- Other fixes
2.3.1 2015-03-06
- Support user rule
2.3 2015-01-25
- Use the same port for every profile
- Use the same port for HTTP/Socks5/PAC
- Fix GFWList PAC compatibility issue with IE11
- Encourage users to report to GFWList when no update found
- Minor UI improvements
2.2.1 2015-01-18
- Fix QR Code compatibility
2.2 2015-01-14
- Support updating PAC from GFWList
- Support adding server by scanning QR Code
- Output timestamp in logs
- Minor fixes
2.1.6 2015-01-02
- Fix OPTIONS requests
- Improve logs
2.1.5 2014-12-25
- Fix QR Code compatibility with iOS
- Only left button will trigger double click on tray icon
2.1.4 2014-12-20
- Fix crash when remarks are too long
2.1.3 2014-12-20
- Add Chinese Language
- Fix some UI issues on Windows 8
- Fix some UI issues on high DPI screens
- Log bind error more friendly
- Stability issues
2.1.2 2014-12-14
- Fix sometimes Shadowsocks doesn't respond to requests
2.1.1 2014-12-14
- Add global proxy option
2.1 2014-12-12
- Add salsa20 and chacha20 support
2.0.11 2014-11-23
- Fix a crash
- Only switch the system proxy off if we have switched it on
2.0.10 2014-11-18
- Minor fixes
- Optimize code
2.0.9 2014-11-13
- Fix startup path
- Fix allowed port range for polipo
2.0.8 2014-11-12
- Fix data corruption
- Set proxy for PPPoE
- Auto Startup Option
- Support high DPI screens
2.0.7 2014-11-11
- Use OpenSSL for now
2.0.6 2014-11-10
- Minor bug fixes
2.0.5 2014-11-09
- Fix QRCode size
- Share over LAN option
- Log to temp path instead
2.0.4 2014-11-09
- Try to fix data corruption
- Remove all configuration except x86
2.0.3 2014-11-08
- Support QRCode generation
- Fix compatibility issues with some Chrome version
2.0.2 2014-11-08
- Add remarks
- Fix error when polipo is killed
2.0.1 2014-11-08
- Check already running
2.0 2014-11-08
- Initial release
================================================
FILE: CONTRIBUTING.md
================================================
How to Contribute
=================
Pull Requests
-------------
1. Pull requests are welcome.
2. Make sure to pass the unit tests. Write unit tests for new modules if
needed.
3. Search before sending new pull request.
Issues
------
1. **DO NOT post question about connection problem in issue tracker**, read [Troubleshooting].
2. Search before sending new issue.
[Troubleshooting]: https://github.com/shadowsocks/shadowsocks-windows/wiki/Troubleshooting
================================================
FILE: LICENSE.txt
================================================
shadowsocks-csharp
==================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
Copyright (C) 2015 clowwindy
Copyright (C) 2020 Shadowsocks Project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
3rd party projects
==================
Privoxy
------------------
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
mbed TLS
--------
https://tls.mbed.org
License: https://raw.githubusercontent.com/ARMmbed/mbedtls/master/LICENSE
Newtonsoft.Json
----------
https://raw.githubusercontent.com/JamesNK/Newtonsoft.Json/master/LICENSE.md
The MIT License (MIT)
Copyright (c) 2007 James Newton-King
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
ZXing
-----
Copyright 2007 ZXing authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
libsodium
---------
Copyright (c) 2013-2015
Frank Denis
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
================================================
FILE: OPENSSL-GUIDE
================================================
OpenSSL library guide for VS2017
# Read NOTES.WIN and NOTES.PERL
# use Visual Studio native tools command prompt
# use activeperl, install NASM assembler
ppm install dmake
# Win32 x86
set PATH=D:\NASM-32;%PATH%
perl Configure VC-WIN32 --release --prefix=C:\Users\home\Downloads\openssl-1.1.0g\x86-build --openssldir=C:\Users\home\Downloads\openssl-1.1.0g\x86-install
nmake
nmake test
# to rebuild
nmake distclean
================================================
FILE: README.md
================================================
Shadowsocks for Windows
=======================
[![Build Status]][Appveyor]
[中文说明]
## Features
1. System proxy configuration
2. PAC mode and global mode
3. [GeoSite] and user rules
4. Supports HTTP proxy
5. Supports server auto switching
6. Supports UDP relay (see Usage)
7. Supports plugins
## Downloads
Download the latest release from [release page].
## Requirements
.NET Framework 4.8 or higher, Microsoft [Visual C++ 2015 Redistributable] (x86) .
## Basics
1. Find Shadowsocks icon in the notification tray
2. You can add multiple servers in servers menu
3. Select `Enable System Proxy` menu to enable system proxy. Please disable other
proxy addons in your browser, or set them to use system proxy
4. You can also configure your browser proxy manually if you don't want to enable
system proxy. Set Socks5 or HTTP proxy to 127.0.0.1:1080. You can change this
port in `Servers -> Edit Servers`
## PAC
- The PAC rules are generated from the geosite database in [v2fly/domain-list-community](https://github.com/v2fly/domain-list-community).
- Generation modes: whitelist mode and blacklist mode.
- Domain groups: `geositeDirectGroups` and `geositeProxiedGroups`.
- `geositeDirectGroups` is initialized with `cn` and `geolocation-!cn@cn`.
- `geositeProxiedGroups` is initialized with `geolocation-!cn`.
- To switch between different modes, modify the `geositePreferDirect` property in `gui-config.json`
- When `geositePreferDirect` is false (default), PAC works in whitelist mode. Exception rules are generated from `geositeDirectGroups`. Unmatched domains goes through the proxy.
- When `geositePreferDirect` is true, PAC works in blacklist mode. Blocking rules are generated from `geositeProxiedGroups`. Exception rules are generated from `geositeDirectGroups`. Unmatched domains are connected to directly.
- Starting from 4.3.0.0, shadowsocks-windows defaults to whitelist mode with Chinese domains excluded from connecting via the proxy.
- The new default values make sure that:
- When in whitelist mode, Chinese domains, including non-Chinese companies' Chinese CDNs, are connected to directly.
- When in blacklist mode, only non-Chinese domains goes through the proxy. Chinese domains, as well as non-Chinese companies' Chinese CDNs, are connected to directly.
### User-defined rules
- To define your own PAC rules, it's recommended to use the `user-rule.txt` file.
- You can also modify `pac.txt` directly. But your modifications won't persist after updating geosite from the upstream.
For Windows10 Store and related applications, please execute the following command under Admin privilege:
```
netsh winhttp import proxy source=ie
```
## Server Auto Switching
1. Load balance: choosing server randomly
2. High availability: choosing the best server (low latency and packet loss)
3. Choose By Total Package Loss: ping and choose. Please also enable
`Availability Statistics` in the menu if you want to use this
4. Write your own strategy by implement IStrategy interface and send us a pull request!
## UDP
For UDP, you need to use SocksCap or ProxyCap to force programs you want
to be proxied to tunnel over Shadowsocks
## Multiple Instances
If you want to manage multiple servers using other tools like SwitchyOmega,
you can start multiple Shadowsocks instances. To avoid configuration conflicts,
copy Shadowsocks to a new directory and choose a different local port.
## Plugins
If you would like to connect to server via a plugin, please set the plugin's
path (relative or absolute) on Edit Servers form.
_Note_: Forward Proxy will not be used while a plugin is enabled.
Details:
[Working with non SIP003 standard Plugin].
## Global hotkeys
Hotkeys could be registered automatically on startup.
If you are using multiple instances of Shadowsocks,
you must set different key combination for each instance.
### How to input?
1. Put focus in the corresponding textbox.
2. Press the key combination that you want to use.
3. Release all keys when you think it is ready.
4. Your input appears in the textbox.
### How to change?
1. Put focus in the corresponding textbox.
2. Press BackSpace key to clear content.
3. Re-input new key combination.
### How to deactivate?
1. Clear content in the textbox that you want to deactivate,
if you want to deactivate all, please clear all textboxes.
2. Press OK button to confirm.
### Meaning of label color
- Green: This key combination is not occupied by other programs and register successfully.
- Yellow: This key combination is occupied by other programs and you have to change to another one.
- Transparent without color: The initial status.
## Server Configuration
Please visit [Servers] for more information.
## Experimental
[Experimental Features]
## Development
1. Visual Studio 2019 & .NET Framework 4.8 SDK are required.
2. It is recommended to share your idea on the Issue Board before you start to work,
especially for feature development.
## License
[GPLv3]
## Open Source Components / Libraries
```
Caseless.Fody (MIT) https://github.com/Fody/Caseless
Costura.Fody (MIT) https://github.com/Fody/Costura
Fody (MIT) https://github.com/Fody/Fody
GlobalHotKey (GPLv3) https://github.com/kirmir/GlobalHotKey
MdXaml (MIT) https://github.com/whistyun/MdXaml
Newtonsoft.Json (MIT) https://www.newtonsoft.com/json
ReactiveUI.WPF (MIT) https://github.com/reactiveui/ReactiveUI
ReactiveUI.Events.WPF (MIT) https://github.com/reactiveui/ReactiveUI
ReactiveUI.Fody (MIT) https://github.com/reactiveui/ReactiveUI
ReactiveUI.Validation (MIT) https://github.com/reactiveui/ReactiveUI.Validation
WPFLocalizationExtension (MS-PL) https://github.com/XAMLMarkupExtensions/WPFLocalizationExtension/
ZXing.Net (Apache 2.0) https://github.com/micjahn/ZXing.Net
libsscrypto (GPLv2) https://github.com/shadowsocks/libsscrypto
Privoxy (GPLv2) https://www.privoxy.org
Sysproxy () https://github.com/Noisyfox/sysproxy
```
[Appveyor]: https://ci.appveyor.com/project/celeron533/shadowsocks-windows
[Build Status]: https://ci.appveyor.com/api/projects/status/tfw57q6eecippsl5/branch/master?svg=true
[release page]: https://github.com/shadowsocks/shadowsocks-csharp/releases
[GeoSite]: https://github.com/v2fly/domain-list-community
[Servers]: https://github.com/shadowsocks/shadowsocks/wiki/Ports-and-Clients#linux--server-side
[中文说明]: https://github.com/shadowsocks/shadowsocks-windows/wiki/Shadowsocks-Windows-%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E
[Visual C++ 2015 Redistributable]: https://www.microsoft.com/en-us/download/details.aspx?id=53840
[GPLv3]: https://github.com/shadowsocks/shadowsocks-windows/blob/master/LICENSE.txt
[Working with non SIP003 standard Plugin]: https://github.com/shadowsocks/shadowsocks-windows/wiki/Working-with-non-SIP003-standard-Plugin
[Experimental Features]: https://github.com/shadowsocks/shadowsocks-windows/wiki/Experimental
================================================
FILE: appveyor.yml
================================================
# Notes:
# - Minimal appveyor.yml file is an empty file. All sections are optional.
# - Indent each level of configuration with 2 spaces. Do not use tabs!
# - All section names are case-sensitive.
# - Section names should be unique on each level.
#---------------------------------#
# general configuration #
#---------------------------------#
# version format
# Build version format is taken from UI if it is not set
version: 4.4.1.{build}
# # branches to build
# branches:
# # whitelist
# only:
# - master
# - production
# # blacklist
# except:
# - gh-pages
#---------------------------------#
# environment configuration #
#---------------------------------#
# Build worker image (VM template)
image: Visual Studio 2019
# scripts that are called at very beginning, before repo cloning
# init:
# - git config --global core.autocrlf false
# set clone depth
clone_depth: 5 # clone entire repository history if not defined
# environment variables
environment:
# my_var1: value1
# # this is how to set encrypted variable. Go to "Settings" -> "Encrypt YAML" page in account menu to encrypt data.
# my_secure_var1:
# secure: FW3tJ3fMncxvs58/ifSP7w==
matrix:
- platform: x86
configuration: Debug
- platform: x86
configuration: Release
# this is how to allow failing jobs in the matrix
matrix:
fast_finish: false # set this flag to immediately finish build once one of the jobs fails.
# build cache to preserve files/folders between builds
cache:
- packages -> **\packages.config # preserve "packages" directory in the root of build folder but will reset it if packages.config is modified
# - '%LocalAppData%\NuGet\Cache' # NuGet < v3
- '%LocalAppData%\NuGet\v3-cache' # NuGet v3
# Automatically register private account and/or project AppVeyor NuGet feeds.
# nuget:
# account_feed: true
# project_feed: true
# disable_publish_on_pr: true # disable publishing of .nupkg artifacts to account/project feeds for pull request builds
# publish_wap_octopus: true # disable publishing of Octopus Deploy .nupkg artifacts to account/project feeds
#---------------------------------#
# build configuration #
#---------------------------------#
# Build settings, not to be confused with "before_build" and "after_build".
# "project" is relative to the original build directory and not influenced by directory changes in "before_build".
build:
# parallel: true # enable MSBuild parallel builds
# publish_nuget: true # package projects with .nuspec files and push to artifacts
# publish_nuget_symbols: true # generate and publish NuGet symbol packages
# include_nuget_references: true # add -IncludeReferencedProjects option while packaging NuGet artifacts
# MSBuild verbosity level
verbosity: normal # quiet|minimal|normal|detailed
# scripts to run before build
before_build:
- cmd: nuget restore
# to run your custom scripts instead of automatic MSBuild
# build_script:
# scripts to run after build (working directory and environment changes are persisted from the previous steps)
after_build:
- ps: |+
function CalculateHash($file)
{
$newLine = "`r`n"
$text = (Split-Path $file -Leaf) + $newLine
$text += 'MD5' + $newLine
$text += (Get-FileHash $file -Algorithm MD5).Hash + $newLine
$text += 'SHA-1' + $newLine
$text += (Get-FileHash $file -Algorithm SHA1).Hash + $newLine
$text += 'SHA-256' + $newLine
$text += (Get-FileHash $file -Algorithm SHA256).Hash + $newLine
$text += 'SHA-512' + $newLine
$text += (Get-FileHash $file -Algorithm SHA512).Hash
return $text
}
$WorkingFolder = "$env:APPVEYOR_BUILD_FOLDER\shadowsocks-csharp\bin\$env:PLATFORM\$env:CONFIGURATION"
$ReleaseFile = "$WorkingFolder\Shadowsocks.exe"
$ReleaseHashFile = "$ReleaseFile.hash"
$ReleaseLocalizationFiles = "$WorkingFolder\*\"
$ZipFile = "$WorkingFolder\Shadowsocks-$env:APPVEYOR_BUILD_VERSION.zip"
$ZipHashFile = "$ZipFile.hash"
CalculateHash -file "$ReleaseFile" | Out-File -FilePath "$ReleaseHashFile"
7z a "$ZipFile" "$ReleaseFile" "$ReleaseHashFile" "$ReleaseLocalizationFiles"
Push-AppveyorArtifact "$ZipFile"
# Calculate packed zip Hash
CalculateHash -file "$ZipFile" | Out-File -FilePath "$ZipHashFile"
Push-AppveyorArtifact "$ZipHashFile"
# scripts to run *after* solution is built and *before* automatic packaging occurs (web apps, NuGet packages, Azure Cloud Services)
# before_package:
# to disable automatic builds
#build: off
#---------------------------------#
# deployment configuration #
#---------------------------------#
# providers: Local, FTP, WebDeploy, AzureCS, AzureBlob, S3, NuGet, Environment
# provider names are case-sensitive!
# deploy:
# # scripts to run before deployment
# before_deploy:
# # scripts to run after deployment
# after_deploy:
# # to run your custom scripts instead of provider deployments
# deploy_script:
# # to disable deployment
#deploy: off
================================================
FILE: appveyor.yml.obsolete
================================================
# Created by wongsyrone
version: 1.0.{build}
image: Visual Studio 2017
environment:
matrix:
- platform: x86
configuration: Debug
- platform: x86
configuration: Release
matrix:
fast_finish: false
nuget:
project_feed: true
before_build:
- cmd: nuget restore
build:
parallel: true
verbosity: normal
artifacts:
- path: shadowsocks-csharp\bin\x86\Release\Shadowsocks.exe
name: Shadowsocks-release.exe
- path: shadowsocks-csharp\bin\x86\Debug\Shadowsocks.exe
name: Shadowsocks-debug.exe
================================================
FILE: appveyor.yml.sample
================================================
# Notes:
# - Minimal appveyor.yml file is an empty file. All sections are optional.
# - Indent each level of configuration with 2 spaces. Do not use tabs!
# - All section names are case-sensitive.
# - Section names should be unique on each level.
#---------------------------------#
# general configuration #
#---------------------------------#
# version format
version: 1.0.{build}
# you can use {branch} name in version format too
# version: 1.0.{build}-{branch}
# branches to build
branches:
# whitelist
only:
- master
- production
# blacklist
except:
- gh-pages
# Do not build on tags (GitHub and BitBucket)
skip_tags: true
# Start builds on tags only (GitHub and BitBucket)
skip_non_tags: true
# Skipping commits with particular message or from specific user
skip_commits:
message: /Created.*\.(png|jpg|jpeg|bmp|gif)/ # Regex for matching commit message
author: John # Commit author's username, name, email or regexp maching one of these.
# Including commits with particular message or from specific user
only_commits:
message: /build/ # Start a new build if message contains 'build'
author: jack@company.com # Start a new build for commit of user with email jack@company.com
# Skipping commits affecting specific files (GitHub only). More details here: /docs/appveyor-yml
#skip_commits:
# files:
# - docs/*
# - '**/*.html'
# Including commits affecting specific files (GitHub only). More details here: /docs/appveyor-yml
#only_commits:
# files:
# - Project-A/
# - Project-B/
# Do not build feature branch with open Pull Requests
skip_branch_with_pr: true
# Maximum number of concurrent jobs for the project
max_jobs: 1
#---------------------------------#
# environment configuration #
#---------------------------------#
# Build worker image (VM template)
image: Visual Studio 2015
# scripts that are called at very beginning, before repo cloning
init:
- git config --global core.autocrlf input
# clone directory
clone_folder: c:\projects\myproject
# fetch repository as zip archive
shallow_clone: true # default is "false"
# set clone depth
clone_depth: 5 # clone entire repository history if not defined
# setting up etc\hosts file
hosts:
queue-server: 127.0.0.1
db.server.com: 127.0.0.2
# environment variables
environment:
my_var1: value1
my_var2: value2
# this is how to set encrypted variable. Go to "Settings" -> "Encrypt YAML" page in account menu to encrypt data.
my_secure_var1:
secure: FW3tJ3fMncxvs58/ifSP7w==
# environment:
# global:
# connection_string: server=12;password=13;
# service_url: https://127.0.0.1:8090
#
# matrix:
# - db: mysql
# provider: mysql
#
# - db: mssql
# provider: mssql
# password:
# secure: $#(JFDA)jQ@#$
# this is how to allow failing jobs in the matrix
matrix:
fast_finish: true # set this flag to immediately finish build once one of the jobs fails.
allow_failures:
- platform: x86
configuration: Debug
- platform: x64
configuration: Release
# exclude configuration from the matrix. Works similarly to 'allow_failures' but build not even being started for excluded combination.
exclude:
- platform: x86
configuration: Debug
# build cache to preserve files/folders between builds
cache:
- packages -> **\packages.config # preserve "packages" directory in the root of build folder but will reset it if packages.config is modified
- projectA\libs
- node_modules # local npm modules
- '%LocalAppData%\NuGet\Cache' # NuGet < v3
- '%LocalAppData%\NuGet\v3-cache' # NuGet v3
# enable service required for build/tests
services:
- mssql2014 # start SQL Server 2014 Express
- mssql2014rs # start SQL Server 2014 Express and Reporting Services
- mssql2012sp1 # start SQL Server 2012 SP1 Express
- mssql2012sp1rs # start SQL Server 2012 SP1 Express and Reporting Services
- mssql2008r2sp2 # start SQL Server 2008 R2 SP2 Express
- mssql2008r2sp2rs # start SQL Server 2008 R2 SP2 Express and Reporting Services
- mysql # start MySQL 5.6 service
- postgresql # start PostgreSQL 9.5 service
- iis # start IIS
- msmq # start Queuing services
- mongodb # start MongoDB
# scripts that run after cloning repository
install:
# by default, all script lines are interpreted as batch
- echo This is batch
# to run script as a PowerShell command prepend it with ps:
- ps: Write-Host 'This is PowerShell'
# batch commands start from cmd:
- cmd: echo This is batch again
- cmd: set MY_VAR=12345
# enable patching of AssemblyInfo.* files
assembly_info:
patch: true
file: AssemblyInfo.*
assembly_version: "2.2.{build}"
assembly_file_version: "{version}"
assembly_informational_version: "{version}"
# Automatically register private account and/or project AppVeyor NuGet feeds.
nuget:
account_feed: true
project_feed: true
disable_publish_on_pr: true # disable publishing of .nupkg artifacts to account/project feeds for pull request builds
publish_wap_octopus: true # disable publishing of Octopus Deploy .nupkg artifacts to account/project feeds
#---------------------------------#
# build configuration #
#---------------------------------#
# build platform, i.e. x86, x64, Any CPU. This setting is optional.
platform: Any CPU
# to add several platforms to build matrix:
#platform:
# - x86
# - Any CPU
# build Configuration, i.e. Debug, Release, etc.
configuration: Release
# to add several configurations to build matrix:
#configuration:
# - Debug
# - Release
# Build settings, not to be confused with "before_build" and "after_build".
# "project" is relative to the original build directory and not influenced by directory changes in "before_build".
build:
parallel: true # enable MSBuild parallel builds
project: MyTestAzureCS.sln # path to Visual Studio solution or project
publish_wap: true # package Web Application Projects (WAP) for Web Deploy
publish_wap_xcopy: true # package Web Application Projects (WAP) for XCopy deployment
publish_wap_beanstalk: true # Package Web Applications for AWS Elastic Beanstalk deployment
publish_wap_octopus: true # Package Web Applications for Octopus deployment
publish_azure_webjob: true # Package Azure WebJobs for Zip Push deployment
publish_azure: true # package Azure Cloud Service projects and push to artifacts
publish_aspnet_core: true # Package ASP.NET Core projects
publish_core_console: true # Package .NET Core console projects
publish_nuget: true # package projects with .nuspec files and push to artifacts
publish_nuget_symbols: true # generate and publish NuGet symbol packages
include_nuget_references: true # add -IncludeReferencedProjects option while packaging NuGet artifacts
# MSBuild verbosity level
verbosity: quiet|minimal|normal|detailed
# scripts to run before build
before_build:
# to run your custom scripts instead of automatic MSBuild
build_script:
# scripts to run after build (working directory and environment changes are persisted from the previous steps)
after_build:
# scripts to run *after* solution is built and *before* automatic packaging occurs (web apps, NuGet packages, Azure Cloud Services)
before_package:
# to disable automatic builds
#build: off
#---------------------------------#
# tests configuration #
#---------------------------------#
# to run tests against only selected assemblies and/or categories
test:
assemblies:
only:
- asm1.dll
- asm2.dll
categories:
only:
- UI
- E2E
# to run tests against all except selected assemblies and/or categories
#test:
# assemblies:
# except:
# - asm1.dll
# - asm2.dll
#
# categories:
# except:
# - UI
# - E2E
# to run tests from different categories as separate jobs in parallel
#test:
# categories:
# - A # A category common for all jobs
# - [UI] # 1st job
# - [DAL, BL] # 2nd job
# scripts to run before tests (working directory and environment changes are persisted from the previous steps such as "before_build")
before_test:
- echo script1
- ps: Write-Host "script1"
# to run your custom scripts instead of automatic tests
test_script:
- echo This is my custom test script
# scripts to run after tests
after_test:
# to disable automatic tests
#test: off
#---------------------------------#
# artifacts configuration #
#---------------------------------#
artifacts:
# pushing a single file
- path: test.zip
# pushing a single file with environment variable in path and "Deployment name" specified
- path: MyProject\bin\$(configuration)
name: myapp
# pushing entire folder as a zip archive
- path: logs
# pushing all *.nupkg files in build directory recursively
- path: '**\*.nupkg'
#---------------------------------#
# deployment configuration #
#---------------------------------#
# providers: Local, FTP, WebDeploy, AzureCS, AzureBlob, S3, NuGet, Environment
# provider names are case-sensitive!
deploy:
# FTP deployment provider settings
- provider: FTP
protocol: ftp|ftps|sftp
host: ftp.myserver.com
username: admin
password:
secure: eYKZKFkkEvFYWX6NfjZIVw==
folder:
application:
active_mode: false
beta: true # enable alternative FTP library for 'ftp' and 'ftps' modes
debug: true # show complete FTP log
# Amazon S3 deployment provider settings
- provider: S3
access_key_id:
secure: ABcd==
secret_access_key:
secure: ABcd==
bucket: my_bucket
folder:
artifact:
set_public: false
# Azure Blob storage deployment provider settings
- provider: AzureBlob
storage_account_name:
secure: ABcd==
storage_access_key:
secure: ABcd==
container: my_container
folder:
artifact:
# Web Deploy deployment provider settings
- provider: WebDeploy
server: http://www.deploy.com/myendpoint
website: mywebsite
username: user
password:
secure: eYKZKFkkEvFYWX6NfjZIVw==
ntlm: false
remove_files: false
app_offline: false
do_not_use_checksum: true # do not use check sum for comparing source and destination files. By default checksums are used.
sync_retry_attempts: 2 # sync attempts, max
sync_retry_interval: 2000 # timeout between sync attempts, milliseconds
aspnet_core: true # artifact zip contains ASP.NET Core application
aspnet_core_force_restart: true # poke app's web.config before deploy to force application restart
skip_dirs: \\App_Data
skip_files: web.config
on:
branch: release
platform: x86
configuration: debug
# Deploying to Azure Cloud Service
- provider: AzureCS
subscription_id:
secure: fjZIVw==
subscription_certificate:
secure: eYKZKFkkEv...FYWX6NfjZIVw==
storage_account_name: my_storage
storage_access_key:
secure: ABcd==
service: my_service
slot: Production
target_profile: Cloud
artifact: MyPackage.cspkg
# Deploying to NuGet feed
- provider: NuGet
server: https://my.nuget.server/feed
api_key:
secure: FYWX6NfjZIVw==
skip_symbols: false
symbol_server: https://your.symbol.server/feed
artifact: MyPackage.nupkg
# Deploy to GitHub Releases
- provider: GitHub
artifact: /.*\.nupkg/ # upload all NuGet packages to release assets
draft: false
prerelease: false
on:
branch: master # release from master branch only
APPVEYOR_REPO_TAG: true # deploy on tag push only
# Deploying to a named environment
- provider: Environment
name: staging
on:
branch: staging
env_var1: value1
env_var2: value2
# scripts to run before deployment
before_deploy:
# scripts to run after deployment
after_deploy:
# to run your custom scripts instead of provider deployments
deploy_script:
# to disable deployment
#deploy: off
#---------------------------------#
# global handlers #
#---------------------------------#
# on successful build
on_success:
- do something
# on build failure
on_failure:
- do something
# after build failure or success
on_finish:
- do something
#---------------------------------#
# notifications #
#---------------------------------#
notifications:
# Email
- provider: Email
to:
- user1@email.com
- user2@email.com
subject: 'Build {{status}}' # optional
message: "{{message}}, {{commitId}}, ..." # optional
on_build_status_changed: true
# HipChat
- provider: HipChat
auth_token:
secure: RbOnSMSFKYzxzFRrxM1+XA==
room: ProjectA
template: "{message}, {commitId}, ..."
# Slack
- provider: Slack
incoming_webhook: http://incoming-webhook-url
# ...or using auth token
- provider: Slack
auth_token:
secure: kBl9BlxvRMr9liHmnBs14A==
channel: development
template: "{message}, {commitId}, ..."
# Campfire
- provider: Campfire
account: appveyor
auth_token:
secure: RifLRG8Vfyol+sNhj9u2JA==
room: ProjectA
template: "{message}, {commitId}, ..."
# Webhook
- provider: Webhook
url: http://www.myhook2.com
headers:
User-Agent: myapp 1.0
Authorization:
secure: GhD+5xhLz/tkYY6AO3fcfQ==
on_build_success: false
on_build_failure: true
on_build_status_changed: true
================================================
FILE: packaging/upload.sh
================================================
#!/bin/bash
version=$1
rsync --progress -e ssh shadowsocks-csharp/bin/x86/Release/Shadowsocks-win-dotnet4.0-$1.zip frs.sourceforge.net:/home/frs/project/shadowsocksgui/dist/
rsync --progress -e ssh shadowsocks-csharp/bin/x86/Release/Shadowsocks-win-$1.zip frs.sourceforge.net:/home/frs/project/shadowsocksgui/dist/
================================================
FILE: shadowsocks-csharp/CommandLineOption.cs
================================================
using CommandLine;
namespace Shadowsocks
{
public class CommandLineOption
{
[Option("open-url",Required = false,HelpText = "Add an ss:// URL")]
public string OpenUrl { get; set; }
}
}
================================================
FILE: shadowsocks-csharp/Controller/FileManager.cs
================================================
using NLog;
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace Shadowsocks.Controller
{
public static class FileManager
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public static bool ByteArrayToFile(string fileName, byte[] content)
{
try
{
using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
fs.Write(content, 0, content.Length);
return true;
}
catch (Exception ex)
{
logger.Error(ex);
}
return false;
}
public static void UncompressFile(string fileName, byte[] content)
{
// Because the uncompressed size of the file is unknown,
// we are using an arbitrary buffer size.
byte[] buffer = new byte[4096];
int n;
using(var fs = File.Create(fileName))
using (var input = new GZipStream(new MemoryStream(content),
CompressionMode.Decompress, false))
{
while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, n);
}
}
}
public static string NonExclusiveReadAllText(string path)
{
return NonExclusiveReadAllText(path, Encoding.Default);
}
public static string NonExclusiveReadAllText(string path, Encoding encoding)
{
try
{
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs, encoding))
{
return sr.ReadToEnd();
}
}
catch (Exception ex)
{
logger.Error(ex);
throw ex;
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/HotkeyReg.cs
================================================
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using NLog;
using Shadowsocks.Controller.Hotkeys;
using Shadowsocks.Model;
namespace Shadowsocks.Controller
{
static class HotkeyReg
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public static void RegAllHotkeys()
{
var hotkeyConfig = Program.MainController.GetCurrentConfiguration().hotkey;
if (hotkeyConfig == null || !hotkeyConfig.RegHotkeysAtStartup)
return;
// if any of the hotkey reg fail, undo everything
if (RegHotkeyFromString(hotkeyConfig.SwitchSystemProxy, "SwitchSystemProxyCallback")
&& RegHotkeyFromString(hotkeyConfig.SwitchSystemProxyMode, "SwitchSystemProxyModeCallback")
&& RegHotkeyFromString(hotkeyConfig.SwitchAllowLan, "SwitchAllowLanCallback")
&& RegHotkeyFromString(hotkeyConfig.ShowLogs, "ShowLogsCallback")
&& RegHotkeyFromString(hotkeyConfig.ServerMoveUp, "ServerMoveUpCallback")
&& RegHotkeyFromString(hotkeyConfig.ServerMoveDown, "ServerMoveDownCallback")
)
{
// success
}
else
{
RegHotkeyFromString("", "SwitchSystemProxyCallback");
RegHotkeyFromString("", "SwitchSystemProxyModeCallback");
RegHotkeyFromString("", "SwitchAllowLanCallback");
RegHotkeyFromString("", "ShowLogsCallback");
RegHotkeyFromString("", "ServerMoveUpCallback");
RegHotkeyFromString("", "ServerMoveDownCallback");
MessageBox.Show(I18N.GetString("Register hotkey failed"), I18N.GetString("Shadowsocks"));
}
}
public static bool RegHotkeyFromString(string hotkeyStr, string callbackName, Action onComplete = null)
{
var _callback = HotkeyCallbacks.GetCallback(callbackName);
if (_callback == null)
{
throw new Exception($"{callbackName} not found");
}
var callback = _callback as HotKeys.HotKeyCallBackHandler;
if (string.IsNullOrEmpty(hotkeyStr))
{
HotKeys.UnregExistingHotkey(callback);
onComplete?.Invoke(RegResult.UnregSuccess);
return true;
}
else
{
var hotkey = HotKeys.Str2HotKey(hotkeyStr);
if (hotkey == null)
{
logger.Error($"Cannot parse hotkey: {hotkeyStr}");
onComplete?.Invoke(RegResult.ParseError);
return false;
}
else
{
bool regResult = (HotKeys.RegHotkey(hotkey, callback));
if (regResult)
{
onComplete?.Invoke(RegResult.RegSuccess);
}
else
{
onComplete?.Invoke(RegResult.RegFailure);
}
return regResult;
}
}
}
public enum RegResult
{
RegSuccess,
RegFailure,
ParseError,
UnregSuccess,
//UnregFailure
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/I18N.cs
================================================
using Microsoft.VisualBasic.FileIO;
using NLog;
using Shadowsocks.Properties;
using Shadowsocks.Util;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace Shadowsocks.Controller
{
public static class I18N
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public const string I18N_FILE = "i18n.csv";
private static Dictionary _strings = new Dictionary();
private static void Init(string res, string locale)
{
using (TextFieldParser csvParser = new TextFieldParser(new StringReader(res)))
{
csvParser.SetDelimiters(",");
// search language index
string[] localeNames = csvParser.ReadFields();
int enIndex = 0;
int targetIndex = -1;
for (int i = 0; i < localeNames.Length; i++)
{
if (localeNames[i] == "en")
enIndex = i;
if (localeNames[i] == locale)
targetIndex = i;
}
// Fallback to same language with different region
if (targetIndex == -1)
{
string localeNoRegion = locale.Split('-')[0];
for (int i = 0; i < localeNames.Length; i++)
{
if (localeNames[i].Split('-')[0] == localeNoRegion)
targetIndex = i;
}
if (targetIndex != -1 && enIndex != targetIndex)
{
logger.Info($"Using {localeNames[targetIndex]} translation for {locale}");
}
else
{
// Still not found, exit
logger.Info($"Translation for {locale} not found");
return;
}
}
// read translation lines
while (!csvParser.EndOfData)
{
string[] translations = csvParser.ReadFields();
string source = translations[enIndex];
string translation = translations[targetIndex];
// source string or translation empty
if (string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(translation)) continue;
// line start with comment
if (translations[0].TrimStart(' ')[0] == '#') continue;
_strings[source] = translation;
}
}
}
static I18N()
{
string i18n;
string locale = CultureInfo.CurrentCulture.Name;
if (!File.Exists(I18N_FILE))
{
i18n = Resources.i18n_csv;
//File.WriteAllText(I18N_FILE, i18n, Encoding.UTF8);
}
else
{
logger.Info("Using external translation");
i18n = File.ReadAllText(I18N_FILE, Encoding.UTF8);
}
logger.Info("Current language is: " + locale);
Init(i18n, locale);
}
public static string GetString(string key, params object[] args)
{
return string.Format(_strings.TryGetValue(key.Trim(), out var value) ? value : key, args);
}
public static void TranslateForm(Form c)
{
if (c == null) return;
c.Text = GetString(c.Text);
foreach (var item in ViewUtils.GetChildControls(c))
{
if (item == null) continue;
item.Text = GetString(item.Text);
}
TranslateMenu(c.Menu);
}
public static void TranslateMenu(Menu m)
{
if (m == null) return;
foreach (var item in ViewUtils.GetMenuItems(m))
{
if (item == null) continue;
item.Text = GetString(item.Text);
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/LoggerExtension.cs
================================================
using System;
using System.ComponentModel;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Text;
using Shadowsocks.Util.SystemProxy;
namespace NLog
{
public static class LoggerExtension
{
public static void Dump(this Logger logger, string tag, byte[] arr, int length)
{
if (logger.IsTraceEnabled)
{
var sb = new StringBuilder($"{Environment.NewLine}{tag}: ");
for (int i = 0; i < length - 1; i++)
{
sb.Append($"0x{arr[i]:X2}, ");
}
sb.Append($"0x{arr[length - 1]:X2}");
sb.Append(Environment.NewLine);
logger.Trace(sb.ToString());
}
}
public static void Debug(this Logger logger, EndPoint local, EndPoint remote, int len, string header = null, string tailer = null)
{
if (logger.IsDebugEnabled)
{
if (header == null && tailer == null)
logger.Debug($"{local} => {remote} (size={len})");
else if (header == null && tailer != null)
logger.Debug($"{local} => {remote} (size={len}), {tailer}");
else if (header != null && tailer == null)
logger.Debug($"{header}: {local} => {remote} (size={len})");
else
logger.Debug($"{header}: {local} => {remote} (size={len}), {tailer}");
}
}
public static void Debug(this Logger logger, Socket sock, int len, string header = null, string tailer = null)
{
if (logger.IsDebugEnabled)
{
logger.Debug(sock.LocalEndPoint, sock.RemoteEndPoint, len, header, tailer);
}
}
public static void LogUsefulException(this Logger logger, Exception e)
{
// just log useful exceptions, not all of them
if (e is SocketException)
{
SocketException se = (SocketException)e;
if (se.SocketErrorCode == SocketError.ConnectionAborted)
{
// closed by browser when sending
// normally happens when download is canceled or a tab is closed before page is loaded
}
else if (se.SocketErrorCode == SocketError.ConnectionReset)
{
// received rst
}
else if (se.SocketErrorCode == SocketError.NotConnected)
{
// The application tried to send or receive data, and the System.Net.Sockets.Socket is not connected.
}
else if (se.SocketErrorCode == SocketError.HostUnreachable)
{
// There is no network route to the specified host.
}
else if (se.SocketErrorCode == SocketError.TimedOut)
{
// The connection attempt timed out, or the connected host has failed to respond.
}
else
{
logger.Warn(e);
}
}
else if (e is ObjectDisposedException)
{
}
else if (e is Win32Exception)
{
var ex = (Win32Exception)e;
// Win32Exception (0x80004005): A 32 bit processes cannot access modules of a 64 bit process.
if ((uint)ex.ErrorCode != 0x80004005)
{
logger.Warn(e);
}
}
else if (e is ProxyException)
{
var ex = (ProxyException)e;
switch (ex.Type)
{
case ProxyExceptionType.FailToRun:
case ProxyExceptionType.QueryReturnMalformed:
case ProxyExceptionType.SysproxyExitError:
logger.Error($"sysproxy - {ex.Type.ToString()}:{ex.Message}");
break;
case ProxyExceptionType.QueryReturnEmpty:
case ProxyExceptionType.Unspecific:
logger.Error($"sysproxy - {ex.Type.ToString()}");
break;
}
}
else
{
logger.Warn(e);
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/GeositeUpdater.cs
================================================
using NLog;
using Shadowsocks.Properties;
using Shadowsocks.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Shadowsocks.Model;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace Shadowsocks.Controller
{
public class GeositeResultEventArgs : EventArgs
{
public bool Success;
public GeositeResultEventArgs(bool success)
{
this.Success = success;
}
}
public static class GeositeUpdater
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public static event EventHandler UpdateCompleted;
public static event ErrorEventHandler Error;
private static readonly string DATABASE_PATH = Utils.GetTempPath("dlc.dat");
private static readonly string GEOSITE_URL = "https://github.com/v2fly/domain-list-community/raw/release/dlc.dat";
private static readonly string GEOSITE_SHA256SUM_URL = "https://github.com/v2fly/domain-list-community/raw/release/dlc.dat.sha256sum";
private static byte[] geositeDB;
public static readonly Dictionary> Geosites = new Dictionary>();
static GeositeUpdater()
{
if (File.Exists(DATABASE_PATH) && new FileInfo(DATABASE_PATH).Length > 0)
{
geositeDB = File.ReadAllBytes(DATABASE_PATH);
}
else
{
geositeDB = Resources.dlc_dat;
File.WriteAllBytes(DATABASE_PATH, Resources.dlc_dat);
}
LoadGeositeList();
}
///
/// load new GeoSite data from geositeDB
///
static void LoadGeositeList()
{
var list = GeositeList.Parser.ParseFrom(geositeDB);
foreach (var item in list.Entries)
{
Geosites[item.GroupName.ToLowerInvariant()] = item.Domains;
}
}
public static void ResetEvent()
{
UpdateCompleted = null;
Error = null;
}
public static async Task UpdatePACFromGeosite()
{
var geositeUrl = GEOSITE_URL;
var geositeSha256sumUrl = GEOSITE_SHA256SUM_URL;
var geositeVerifySha256 = true;
var geositeSha256sum = "";
var mySHA256 = SHA256.Create();
var config = Program.MainController.GetCurrentConfiguration();
var blacklist = config.geositePreferDirect;
var httpClient = Program.MainController.GetHttpClient();
if (!string.IsNullOrWhiteSpace(config.geositeUrl))
{
logger.Info("Found custom Geosite URL in config file");
geositeUrl = config.geositeUrl;
geositeSha256sumUrl = config.geositeSha256sumUrl;
if (string.IsNullOrWhiteSpace(geositeSha256sumUrl))
{
geositeVerifySha256 = false;
logger.Info("Geosite SHA256 verification is disabled.");
}
}
logger.Info($"Checking Geosite from {geositeUrl}");
try
{
// Use sha256sum to check if local database is already latest.
if (geositeVerifySha256)
{
// download checksum first
geositeSha256sum = await httpClient.GetStringAsync(geositeSha256sumUrl);
geositeSha256sum = geositeSha256sum.Substring(0, 64).ToUpper();
logger.Info($"Got Sha256sum: {geositeSha256sum}");
// compare downloaded checksum with local geositeDB
byte[] localDBHashBytes = mySHA256.ComputeHash(geositeDB);
string localDBHash = BitConverter.ToString(localDBHashBytes).Replace("-", String.Empty);
logger.Info($"Local Sha256sum: {localDBHash}");
// if already latest
if (geositeSha256sum == localDBHash)
{
logger.Info("Local GeoSite DB is up to date.");
UpdateCompleted?.Invoke(null, new GeositeResultEventArgs(false));
return;
}
}
// not latest. download new DB
var downloadedBytes = await httpClient.GetByteArrayAsync(geositeUrl);
// verify sha256sum
if (geositeVerifySha256)
{
byte[] downloadedDBHashBytes = mySHA256.ComputeHash(downloadedBytes);
string downloadedDBHash = BitConverter.ToString(downloadedDBHashBytes).Replace("-", String.Empty);
logger.Info($"Actual Sha256sum: {downloadedDBHash}");
if (geositeSha256sum != downloadedDBHash)
{
logger.Info("Sha256sum Verification: FAILED. Downloaded GeoSite DB is corrupted. Aborting the update.");
throw new Exception("Sha256sum mismatch");
}
else
{
logger.Info("Sha256sum Verification: PASSED. Applying to local GeoSite DB.");
}
}
// write to geosite file
using (FileStream geositeFileStream = File.Create(DATABASE_PATH))
await geositeFileStream.WriteAsync(downloadedBytes, 0, downloadedBytes.Length);
// update stuff
geositeDB = downloadedBytes;
LoadGeositeList();
bool pacFileChanged = MergeAndWritePACFile(config.geositeDirectGroups, config.geositeProxiedGroups, blacklist);
UpdateCompleted?.Invoke(null, new GeositeResultEventArgs(pacFileChanged));
}
catch (Exception ex)
{
Error?.Invoke(null, new ErrorEventArgs(ex));
}
}
///
/// Merge and write pac.txt from geosite.
/// Used at multiple places.
///
/// A list of geosite groups configured for direct connection.
/// A list of geosite groups configured for proxied connection.
/// Whether to use blacklist mode. False for whitelist.
///
public static bool MergeAndWritePACFile(List directGroups, List proxiedGroups, bool blacklist)
{
string abpContent = MergePACFile(directGroups, proxiedGroups, blacklist);
if (File.Exists(PACDaemon.PAC_FILE))
{
string original = FileManager.NonExclusiveReadAllText(PACDaemon.PAC_FILE, Encoding.UTF8);
if (original == abpContent)
{
return false;
}
}
File.WriteAllText(PACDaemon.PAC_FILE, abpContent, Encoding.UTF8);
return true;
}
///
/// Checks if the specified group exists in GeoSite database.
///
/// The group name to check for.
/// True if the group exists. False if the group doesn't exist.
public static bool CheckGeositeGroup(string group) => SeparateAttributeFromGroupName(group, out string groupName, out _) && Geosites.ContainsKey(groupName);
///
/// Separates the attribute (e.g. @cn) from a group name.
/// No checks are performed.
///
/// A group name potentially with a trailing attribute.
/// The group name with the attribute stripped.
/// The attribute.
/// True for success. False for more than one '@'.
private static bool SeparateAttributeFromGroupName(string group, out string groupName, out string attribute)
{
var splitGroupAttributeList = group.Split('@');
if (splitGroupAttributeList.Length == 1) // no attribute
{
groupName = splitGroupAttributeList[0];
attribute = "";
}
else if (splitGroupAttributeList.Length == 2) // has attribute
{
groupName = splitGroupAttributeList[0];
attribute = splitGroupAttributeList[1];
}
else
{
groupName = "";
attribute = "";
return false;
}
return true;
}
private static string MergePACFile(List directGroups, List proxiedGroups, bool blacklist)
{
string abpContent;
if (File.Exists(PACDaemon.USER_ABP_FILE))
{
abpContent = FileManager.NonExclusiveReadAllText(PACDaemon.USER_ABP_FILE, Encoding.UTF8);
}
else
{
abpContent = Resources.abp_js;
}
List userruleLines = new List();
if (File.Exists(PACDaemon.USER_RULE_FILE))
{
string userrulesString = FileManager.NonExclusiveReadAllText(PACDaemon.USER_RULE_FILE, Encoding.UTF8);
userruleLines = ProcessUserRules(userrulesString);
}
List ruleLines = GenerateRules(directGroups, proxiedGroups, blacklist);
abpContent =
$@"var __USERRULES__ = {JsonConvert.SerializeObject(userruleLines, Formatting.Indented)};
var __RULES__ = {JsonConvert.SerializeObject(ruleLines, Formatting.Indented)};
{abpContent}";
return abpContent;
}
private static List ProcessUserRules(string content)
{
List valid_lines = new List();
using (var stringReader = new StringReader(content))
{
for (string line = stringReader.ReadLine(); line != null; line = stringReader.ReadLine())
{
if (string.IsNullOrWhiteSpace(line) || line.StartsWith("!") || line.StartsWith("["))
continue;
valid_lines.Add(line);
}
}
return valid_lines;
}
///
/// Generates rule lines based on user preference.
///
/// A list of geosite groups configured for direct connection.
/// A list of geosite groups configured for proxied connection.
/// Whether to use blacklist mode. False for whitelist.
/// A list of rule lines.
private static List GenerateRules(List directGroups, List proxiedGroups, bool blacklist)
{
List ruleLines;
if (blacklist) // blocking + exception rules
{
ruleLines = GenerateBlockingRules(proxiedGroups);
ruleLines.AddRange(GenerateExceptionRules(directGroups));
}
else // proxy all + exception rules
{
ruleLines = new List()
{
"/.*/" // block/proxy all unmatched domains
};
ruleLines.AddRange(GenerateExceptionRules(directGroups));
}
return ruleLines;
}
///
/// Generates rules that match domains that should be proxied.
///
/// A list of source groups.
/// A list of rule lines.
private static List GenerateBlockingRules(List groups)
{
List ruleLines = new List();
foreach (var group in groups)
{
// separate group name and attribute
SeparateAttributeFromGroupName(group, out string groupName, out string attribute);
var domainObjects = Geosites[groupName];
if (!string.IsNullOrEmpty(attribute)) // has attribute
{
var attributeObject = new DomainObject.Types.Attribute
{
Key = attribute,
BoolValue = true
};
foreach (var domainObject in domainObjects)
{
if (domainObject.Attribute.Contains(attributeObject))
switch (domainObject.Type)
{
case DomainObject.Types.Type.Plain:
ruleLines.Add(domainObject.Value);
break;
case DomainObject.Types.Type.Regex:
ruleLines.Add($"/{domainObject.Value}/");
break;
case DomainObject.Types.Type.Domain:
ruleLines.Add($"||{domainObject.Value}");
break;
case DomainObject.Types.Type.Full:
ruleLines.Add($"|http://{domainObject.Value}");
ruleLines.Add($"|https://{domainObject.Value}");
break;
}
}
}
else // no attribute
foreach (var domainObject in domainObjects)
{
switch (domainObject.Type)
{
case DomainObject.Types.Type.Plain:
ruleLines.Add(domainObject.Value);
break;
case DomainObject.Types.Type.Regex:
ruleLines.Add($"/{domainObject.Value}/");
break;
case DomainObject.Types.Type.Domain:
ruleLines.Add($"||{domainObject.Value}");
break;
case DomainObject.Types.Type.Full:
ruleLines.Add($"|http://{domainObject.Value}");
ruleLines.Add($"|https://{domainObject.Value}");
break;
}
}
}
return ruleLines;
}
///
/// Generates rules that match domains that should be connected directly without a proxy.
///
/// A list of source groups.
/// A list of rule lines.
private static List GenerateExceptionRules(List groups)
=> GenerateBlockingRules(groups)
.Select(r => $"@@{r}") // convert blocking rules to exception rules
.ToList();
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/IPCService.cs
================================================
using System;
using System.IO.Pipes;
using System.Net;
using System.Text;
namespace Shadowsocks.Controller
{
class RequestAddUrlEventArgs : EventArgs
{
public readonly string Url;
public RequestAddUrlEventArgs(string url)
{
this.Url = url;
}
}
internal class IPCService
{
private const int INT32_LEN = 4;
private const int OP_OPEN_URL = 1;
private static readonly string PIPE_PATH = $"Shadowsocks\\{Program.ExecutablePath.GetHashCode()}";
public event EventHandler OpenUrlRequested;
public async void RunServer()
{
byte[] buf = new byte[4096];
while (true)
{
using (NamedPipeServerStream stream = new NamedPipeServerStream(PIPE_PATH))
{
await stream.WaitForConnectionAsync();
await stream.ReadAsync(buf, 0, INT32_LEN);
int opcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buf, 0));
if (opcode == OP_OPEN_URL)
{
await stream.ReadAsync(buf, 0, INT32_LEN);
int strlen = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buf, 0));
await stream.ReadAsync(buf, 0, strlen);
string url = Encoding.UTF8.GetString(buf, 0, strlen);
OpenUrlRequested?.Invoke(this, new RequestAddUrlEventArgs(url));
}
stream.Close();
}
}
}
private static (NamedPipeClientStream, bool) TryConnect()
{
NamedPipeClientStream pipe = new NamedPipeClientStream(PIPE_PATH);
bool exist;
try
{
pipe.Connect(10);
exist = true;
}
catch (TimeoutException)
{
exist = false;
}
return (pipe, exist);
}
public static bool AnotherInstanceRunning()
{
(NamedPipeClientStream pipe, bool exist) = TryConnect();
pipe.Dispose();
return exist;
}
public static void RequestOpenUrl(string url)
{
(NamedPipeClientStream pipe, bool exist) = TryConnect();
if(!exist) return;
byte[] opAddUrl = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(OP_OPEN_URL));
pipe.Write(opAddUrl, 0, INT32_LEN); // opcode addurl
byte[] b = Encoding.UTF8.GetBytes(url);
byte[] blen = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(b.Length));
pipe.Write(blen, 0, INT32_LEN);
pipe.Write(b, 0, b.Length);
pipe.Close();
pipe.Dispose();
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/Listener.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using NLog;
using Shadowsocks.Model;
namespace Shadowsocks.Controller
{
public class Listener
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public interface IService
{
bool Handle(byte[] firstPacket, int length, Socket socket, object state);
void Stop();
}
public abstract class Service : IService
{
public abstract bool Handle(byte[] firstPacket, int length, Socket socket, object state);
public virtual void Stop() { }
}
public class UDPState
{
public UDPState(Socket s)
{
socket = s;
remoteEndPoint = new IPEndPoint(s.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, 0);
}
public Socket socket;
public byte[] buffer = new byte[4096];
public EndPoint remoteEndPoint;
}
Configuration _config;
bool _shareOverLAN;
Socket _tcpSocket;
Socket _udpSocket;
List _services;
public Listener(List services)
{
this._services = services;
}
private bool CheckIfPortInUse(int port)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
return ipProperties.GetActiveTcpListeners().Any(endPoint => endPoint.Port == port);
}
public void Start(Configuration config)
{
this._config = config;
this._shareOverLAN = config.shareOverLan;
if (CheckIfPortInUse(_config.localPort))
throw new Exception(I18N.GetString("Port {0} already in use", _config.localPort));
try
{
// Create a TCP/IP socket.
_tcpSocket = new Socket(config.isIPv6Enabled ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_udpSocket = new Socket(config.isIPv6Enabled ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint localEndPoint = null;
localEndPoint = _shareOverLAN
? new IPEndPoint(config.isIPv6Enabled ? IPAddress.IPv6Any : IPAddress.Any, _config.localPort)
: new IPEndPoint(config.isIPv6Enabled ? IPAddress.IPv6Loopback : IPAddress.Loopback, _config.localPort);
// Bind the socket to the local endpoint and listen for incoming connections.
_tcpSocket.Bind(localEndPoint);
_udpSocket.Bind(localEndPoint);
_tcpSocket.Listen(1024);
// Start an asynchronous socket to listen for connections.
logger.Info($"Shadowsocks started ({UpdateChecker.Version})");
logger.Debug(Encryption.EncryptorFactory.DumpRegisteredEncryptor());
_tcpSocket.BeginAccept(new AsyncCallback(AcceptCallback), _tcpSocket);
UDPState udpState = new UDPState(_udpSocket);
_udpSocket.BeginReceiveFrom(udpState.buffer, 0, udpState.buffer.Length, 0, ref udpState.remoteEndPoint, new AsyncCallback(RecvFromCallback), udpState);
}
catch (SocketException)
{
_tcpSocket.Close();
throw;
}
}
public void Stop()
{
if (_tcpSocket != null)
{
_tcpSocket.Close();
_tcpSocket = null;
}
if (_udpSocket != null)
{
_udpSocket.Close();
_udpSocket = null;
}
_services.ForEach(s => s.Stop());
}
public void RecvFromCallback(IAsyncResult ar)
{
UDPState state = (UDPState)ar.AsyncState;
var socket = state.socket;
try
{
int bytesRead = socket.EndReceiveFrom(ar, ref state.remoteEndPoint);
foreach (IService service in _services)
{
if (service.Handle(state.buffer, bytesRead, socket, state))
{
break;
}
}
}
catch (ObjectDisposedException)
{
}
catch (Exception ex)
{
logger.Debug(ex);
}
finally
{
try
{
socket.BeginReceiveFrom(state.buffer, 0, state.buffer.Length, 0, ref state.remoteEndPoint, new AsyncCallback(RecvFromCallback), state);
}
catch (ObjectDisposedException)
{
// do nothing
}
catch (Exception)
{
}
}
}
public void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
try
{
Socket conn = listener.EndAccept(ar);
byte[] buf = new byte[4096];
object[] state = new object[] {
conn,
buf
};
conn.BeginReceive(buf, 0, buf.Length, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (ObjectDisposedException)
{
}
catch (Exception e)
{
logger.LogUsefulException(e);
}
finally
{
try
{
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
}
catch (ObjectDisposedException)
{
// do nothing
}
catch (Exception e)
{
logger.LogUsefulException(e);
}
}
}
private void ReceiveCallback(IAsyncResult ar)
{
object[] state = (object[])ar.AsyncState;
Socket conn = (Socket)state[0];
byte[] buf = (byte[])state[1];
try
{
int bytesRead = conn.EndReceive(ar);
if (bytesRead <= 0) goto Shutdown;
foreach (IService service in _services)
{
if (service.Handle(buf, bytesRead, conn, null))
{
return;
}
}
Shutdown:
// no service found for this
if (conn.ProtocolType == ProtocolType.Tcp)
{
conn.Close();
}
}
catch (Exception e)
{
logger.LogUsefulException(e);
conn.Close();
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/OnlineConfigResolver.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Shadowsocks.Model;
namespace Shadowsocks.Controller.Service
{
public class OnlineConfigResolver
{
public static async Task> GetOnline(string url)
{
var httpClient = Program.MainController.GetHttpClient();
string server_json = await httpClient.GetStringAsync(url);
var servers = server_json.GetServers();
foreach (var server in servers)
{
server.group = url;
}
return servers.ToList();
}
}
internal static class OnlineConfigResolverEx
{
private static readonly string[] BASIC_FORMAT = new[] { "server", "server_port", "password", "method" };
private static readonly IEnumerable EMPTY_SERVERS = Array.Empty();
internal static IEnumerable GetServers(this string json) =>
JToken.Parse(json).SearchJToken().AsEnumerable();
private static IEnumerable SearchJArray(JArray array) =>
array == null ? EMPTY_SERVERS : array.SelectMany(SearchJToken).ToList();
private static IEnumerable SearchJObject(JObject obj)
{
if (obj == null)
return EMPTY_SERVERS;
if (BASIC_FORMAT.All(field => obj.ContainsKey(field)))
return new[] { obj.ToObject() };
var servers = new List();
foreach (var kv in obj)
{
var token = kv.Value;
servers.AddRange(SearchJToken(token));
}
return servers;
}
private static IEnumerable SearchJToken(this JToken token)
{
switch (token.Type)
{
default:
return Array.Empty();
case JTokenType.Object:
return SearchJObject(token as JObject);
case JTokenType.Array:
return SearchJArray(token as JArray);
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/PACDaemon.cs
================================================
using NLog;
using Shadowsocks.Model;
using Shadowsocks.Properties;
using Shadowsocks.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shadowsocks.Controller
{
///
/// Processing the PAC file content
///
public class PACDaemon
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public const string PAC_FILE = "pac.txt";
public const string USER_RULE_FILE = "user-rule.txt";
public const string USER_ABP_FILE = "abp.txt";
private Configuration config;
FileSystemWatcher PACFileWatcher;
FileSystemWatcher UserRuleFileWatcher;
public event EventHandler PACFileChanged;
public event EventHandler UserRuleFileChanged;
public PACDaemon(Configuration config)
{
this.config = config;
TouchPACFile();
TouchUserRuleFile();
this.WatchPacFile();
this.WatchUserRuleFile();
}
public string TouchPACFile()
{
if (!File.Exists(PAC_FILE))
{
GeositeUpdater.MergeAndWritePACFile(config.geositeDirectGroups, config.geositeProxiedGroups, config.geositePreferDirect);
}
return PAC_FILE;
}
internal string TouchUserRuleFile()
{
if (!File.Exists(USER_RULE_FILE))
{
File.WriteAllText(USER_RULE_FILE, Resources.user_rule);
}
return USER_RULE_FILE;
}
internal string GetPACContent()
{
if (!File.Exists(PAC_FILE))
{
GeositeUpdater.MergeAndWritePACFile(config.geositeDirectGroups, config.geositeProxiedGroups, config.geositePreferDirect);
}
return File.ReadAllText(PAC_FILE, Encoding.UTF8);
}
private void WatchPacFile()
{
PACFileWatcher?.Dispose();
PACFileWatcher = new FileSystemWatcher(Program.WorkingDirectory);
PACFileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
PACFileWatcher.Filter = PAC_FILE;
PACFileWatcher.Changed += PACFileWatcher_Changed;
PACFileWatcher.Created += PACFileWatcher_Changed;
PACFileWatcher.Deleted += PACFileWatcher_Changed;
PACFileWatcher.Renamed += PACFileWatcher_Changed;
PACFileWatcher.EnableRaisingEvents = true;
}
private void WatchUserRuleFile()
{
UserRuleFileWatcher?.Dispose();
UserRuleFileWatcher = new FileSystemWatcher(Program.WorkingDirectory);
UserRuleFileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
UserRuleFileWatcher.Filter = USER_RULE_FILE;
UserRuleFileWatcher.Changed += UserRuleFileWatcher_Changed;
UserRuleFileWatcher.Created += UserRuleFileWatcher_Changed;
UserRuleFileWatcher.Deleted += UserRuleFileWatcher_Changed;
UserRuleFileWatcher.Renamed += UserRuleFileWatcher_Changed;
UserRuleFileWatcher.EnableRaisingEvents = true;
}
#region FileSystemWatcher.OnChanged()
// FileSystemWatcher Changed event is raised twice
// http://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice
// Add a short delay to avoid raise event twice in a short period
private void PACFileWatcher_Changed(object sender, FileSystemEventArgs e)
{
if (PACFileChanged != null)
{
logger.Info($"Detected: PAC file '{e.Name}' was {e.ChangeType.ToString().ToLower()}.");
Task.Factory.StartNew(() =>
{
((FileSystemWatcher)sender).EnableRaisingEvents = false;
System.Threading.Thread.Sleep(10);
PACFileChanged(this, new EventArgs());
((FileSystemWatcher)sender).EnableRaisingEvents = true;
});
}
}
private void UserRuleFileWatcher_Changed(object sender, FileSystemEventArgs e)
{
if (UserRuleFileChanged != null)
{
logger.Info($"Detected: User Rule file '{e.Name}' was {e.ChangeType.ToString().ToLower()}.");
Task.Factory.StartNew(() =>
{
((FileSystemWatcher)sender).EnableRaisingEvents = false;
System.Threading.Thread.Sleep(10);
UserRuleFileChanged(this, new EventArgs());
((FileSystemWatcher)sender).EnableRaisingEvents = true;
});
}
}
#endregion
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/PACServer.cs
================================================
using Shadowsocks.Encryption;
using Shadowsocks.Model;
using Shadowsocks.Util;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;
using NLog;
namespace Shadowsocks.Controller
{
public class PACServer : Listener.Service
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public const string RESOURCE_NAME = "pac";
private string PacSecret
{
get
{
if (string.IsNullOrEmpty(_cachedPacSecret))
{
var rd = new byte[32];
RNG.GetBytes(rd);
_cachedPacSecret = HttpServerUtility.UrlTokenEncode(rd);
}
return _cachedPacSecret;
}
}
private string _cachedPacSecret = "";
public string PacUrl { get; private set; } = "";
private Configuration _config;
private PACDaemon _pacDaemon;
public PACServer(PACDaemon pacDaemon)
{
_pacDaemon = pacDaemon;
}
public void UpdatePACURL(Configuration config)
{
_config = config;
string usedSecret = _config.secureLocalPac ? $"&secret={PacSecret}" : "";
string contentHash = GetHash(_pacDaemon.GetPACContent());
PacUrl = $"http://{config.LocalHost}:{config.localPort}/{RESOURCE_NAME}?hash={contentHash}{usedSecret}";
logger.Debug("Set PAC URL:" + PacUrl);
}
private static string GetHash(string content)
{
return HttpServerUtility.UrlTokenEncode(MbedTLS.MD5(Encoding.ASCII.GetBytes(content)));
}
public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)
{
if (socket.ProtocolType != ProtocolType.Tcp)
{
return false;
}
try
{
/*
* RFC 7230
*
GET /hello.txt HTTP/1.1
User-Agent: curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
Host: www.example.com
Accept-Language: en, mi
*/
string request = Encoding.UTF8.GetString(firstPacket, 0, length);
string[] lines = request.Split('\r', '\n');
bool hostMatch = false, pathMatch = false, useSocks = false;
bool secretMatch = !_config.secureLocalPac;
if (lines.Length < 2) // need at lease RequestLine + Host
{
return false;
}
// parse request line
string requestLine = lines[0];
// GET /pac?t=yyyyMMddHHmmssfff&secret=foobar HTTP/1.1
string[] requestItems = requestLine.Split(' ');
if (requestItems.Length == 3 && requestItems[0] == "GET")
{
int index = requestItems[1].IndexOf('?');
if (index < 0)
{
index = requestItems[1].Length;
}
string resourceString = requestItems[1].Substring(0, index).Remove(0, 1);
if (string.Equals(resourceString, RESOURCE_NAME, StringComparison.OrdinalIgnoreCase))
{
pathMatch = true;
if (!secretMatch)
{
string queryString = requestItems[1].Substring(index);
if (queryString.Contains(PacSecret))
{
secretMatch = true;
}
}
}
}
// parse request header
for (int i = 1; i < lines.Length; i++)
{
if (string.IsNullOrEmpty(lines[i]))
continue;
string[] kv = lines[i].Split(new char[] { ':' }, 2);
if (kv.Length == 2)
{
if (kv[0] == "Host")
{
if (kv[1].Trim() == ((IPEndPoint)socket.LocalEndPoint).ToString())
{
hostMatch = true;
}
}
//else if (kv[0] == "User-Agent")
//{
// // we need to drop connections when changing servers
// if (kv[1].IndexOf("Chrome") >= 0)
// {
// useSocks = true;
// }
//}
}
}
if (hostMatch && pathMatch)
{
if (!secretMatch)
{
socket.Close(); // Close immediately
}
else
{
SendResponse(socket, useSocks);
}
return true;
}
return false;
}
catch (ArgumentException)
{
return false;
}
}
public void SendResponse(Socket socket, bool useSocks)
{
try
{
IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;
string proxy = GetPACAddress(localEndPoint, useSocks);
string pacContent = $"var __PROXY__ = '{proxy}';\n" + _pacDaemon.GetPACContent();
string responseHead =
$@"HTTP/1.1 200 OK
Server: ShadowsocksWindows/{UpdateChecker.Version}
Content-Type: application/x-ns-proxy-autoconfig
Content-Length: { Encoding.UTF8.GetBytes(pacContent).Length}
Connection: Close
";
byte[] response = Encoding.UTF8.GetBytes(responseHead + pacContent);
socket.BeginSend(response, 0, response.Length, 0, new AsyncCallback(SendCallback), socket);
}
catch (Exception e)
{
logger.LogUsefulException(e);
socket.Close();
}
}
private void SendCallback(IAsyncResult ar)
{
Socket conn = (Socket)ar.AsyncState;
try
{
conn.Shutdown(SocketShutdown.Send);
}
catch
{ }
}
private string GetPACAddress(IPEndPoint localEndPoint, bool useSocks)
{
return localEndPoint.AddressFamily == AddressFamily.InterNetworkV6
? $"{(useSocks ? "SOCKS5" : "PROXY")} [{localEndPoint.Address}]:{_config.localPort};"
: $"{(useSocks ? "SOCKS5" : "PROXY")} {localEndPoint.Address}:{_config.localPort};";
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/PortForwarder.cs
================================================
using System;
using System.Net;
using System.Net.Sockets;
using NLog;
using Shadowsocks.Util.Sockets;
namespace Shadowsocks.Controller
{
class PortForwarder : Listener.Service
{
private readonly int _targetPort;
public PortForwarder(int targetPort)
{
_targetPort = targetPort;
}
public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)
{
if (socket.ProtocolType != ProtocolType.Tcp)
{
return false;
}
new Handler().Start(firstPacket, length, socket, _targetPort);
return true;
}
private class Handler
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private byte[] _firstPacket;
private int _firstPacketLength;
private Socket _local;
private WrappedSocket _remote;
private bool _closed = false;
private bool _localShutdown = false;
private bool _remoteShutdown = false;
private const int RecvSize = 2048;
// remote receive buffer
private byte[] remoteRecvBuffer = new byte[RecvSize];
// connection receive buffer
private byte[] connetionRecvBuffer = new byte[RecvSize];
// instance-based lock
private readonly object _Lock = new object();
public void Start(byte[] firstPacket, int length, Socket socket, int targetPort)
{
_firstPacket = firstPacket;
_firstPacketLength = length;
_local = socket;
try
{
// Local Port Forward use IP as is
EndPoint remoteEP = SocketUtil.GetEndPoint(_local.AddressFamily == AddressFamily.InterNetworkV6 ? "[::1]" : "127.0.0.1", targetPort);
// Connect to the remote endpoint.
_remote = new WrappedSocket();
_remote.BeginConnect(remoteEP, ConnectCallback, null);
}
catch (Exception e)
{
logger.LogUsefulException(e);
Close();
}
}
private void ConnectCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
_remote.EndConnect(ar);
_remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
HandshakeReceive();
}
catch (Exception e)
{
logger.LogUsefulException(e);
Close();
}
}
private void HandshakeReceive()
{
if (_closed)
{
return;
}
try
{
_remote.BeginSend(_firstPacket, 0, _firstPacketLength, 0, StartPipe, null);
}
catch (Exception e)
{
logger.LogUsefulException(e);
Close();
}
}
private void StartPipe(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
_remote.EndSend(ar);
_remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0,
PipeRemoteReceiveCallback, null);
_local.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
PipeConnectionReceiveCallback, null);
}
catch (Exception e)
{
logger.LogUsefulException(e);
Close();
}
}
private void PipeRemoteReceiveCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
int bytesRead = _remote.EndReceive(ar);
if (bytesRead > 0)
{
_local.BeginSend(remoteRecvBuffer, 0, bytesRead, 0, PipeConnectionSendCallback, null);
}
else
{
_local.Shutdown(SocketShutdown.Send);
_localShutdown = true;
CheckClose();
}
}
catch (Exception e)
{
logger.LogUsefulException(e);
Close();
}
}
private void PipeConnectionReceiveCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
int bytesRead = _local.EndReceive(ar);
if (bytesRead > 0)
{
_remote.BeginSend(connetionRecvBuffer, 0, bytesRead, 0, PipeRemoteSendCallback, null);
}
else
{
_remote.Shutdown(SocketShutdown.Send);
_remoteShutdown = true;
CheckClose();
}
}
catch (Exception e)
{
logger.LogUsefulException(e);
Close();
}
}
private void PipeRemoteSendCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
_remote.EndSend(ar);
_local.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
PipeConnectionReceiveCallback, null);
}
catch (Exception e)
{
logger.LogUsefulException(e);
Close();
}
}
private void PipeConnectionSendCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
_local.EndSend(ar);
_remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0,
PipeRemoteReceiveCallback, null);
}
catch (Exception e)
{
logger.LogUsefulException(e);
Close();
}
}
private void CheckClose()
{
if (_localShutdown && _remoteShutdown)
{
Close();
}
}
public void Close()
{
lock (_Lock)
{
if (_closed)
{
return;
}
_closed = true;
}
if (_local != null)
{
try
{
_local.Shutdown(SocketShutdown.Both);
_local.Close();
}
catch (Exception e)
{
logger.LogUsefulException(e);
}
}
if (_remote != null)
{
try
{
_remote.Shutdown(SocketShutdown.Both);
_remote.Dispose();
}
catch (SocketException e)
{
logger.LogUsefulException(e);
}
}
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/PrivoxyRunner.cs
================================================
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using NLog;
using Shadowsocks.Model;
using Shadowsocks.Properties;
using Shadowsocks.Util;
using Shadowsocks.Util.ProcessManagement;
namespace Shadowsocks.Controller
{
class PrivoxyRunner
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private static int _uid;
private static string _uniqueConfigFile;
private static Job _privoxyJob;
private Process _process;
private int _runningPort;
static PrivoxyRunner()
{
try
{
_uid = Program.WorkingDirectory.GetHashCode(); // Currently we use ss's StartupPath to identify different Privoxy instance.
_uniqueConfigFile = $"privoxy_{_uid}.conf";
_privoxyJob = new Job();
FileManager.UncompressFile(Utils.GetTempPath("ss_privoxy.exe"), Resources.privoxy_exe);
}
catch (IOException e)
{
logger.LogUsefulException(e);
}
}
public int RunningPort => _runningPort;
public void Start(Configuration configuration)
{
if (_process == null)
{
Process[] existingPrivoxy = Process.GetProcessesByName("ss_privoxy");
foreach (Process p in existingPrivoxy.Where(IsChildProcess))
{
KillProcess(p);
}
string privoxyConfig = Resources.privoxy_conf;
_runningPort = GetFreePort(configuration.isIPv6Enabled);
privoxyConfig = privoxyConfig.Replace("__SOCKS_PORT__", configuration.localPort.ToString());
privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_PORT__", _runningPort.ToString());
privoxyConfig = configuration.isIPv6Enabled
? privoxyConfig.Replace("__PRIVOXY_BIND_IP__", configuration.shareOverLan ? "[::]" : "[::1]")
.Replace("__SOCKS_HOST__", "[::1]")
: privoxyConfig.Replace("__PRIVOXY_BIND_IP__", configuration.shareOverLan ? "0.0.0.0" : "127.0.0.1")
.Replace("__SOCKS_HOST__", "127.0.0.1");
FileManager.ByteArrayToFile(Utils.GetTempPath(_uniqueConfigFile), Encoding.UTF8.GetBytes(privoxyConfig));
_process = new Process
{
// Configure the process using the StartInfo properties.
StartInfo =
{
FileName = "ss_privoxy.exe",
Arguments = _uniqueConfigFile,
WorkingDirectory = Utils.GetTempPath(),
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = true,
CreateNoWindow = true
}
};
_process.Start();
/*
* Add this process to job obj associated with this ss process, so that
* when ss exit unexpectedly, this process will be forced killed by system.
*/
_privoxyJob.AddProcess(_process.Handle);
}
}
public void Stop()
{
if (_process != null)
{
KillProcess(_process);
_process.Dispose();
_process = null;
}
}
private static void KillProcess(Process p)
{
try
{
p.CloseMainWindow();
p.WaitForExit(100);
if (!p.HasExited)
{
p.Kill();
p.WaitForExit();
}
}
catch (Exception e)
{
logger.LogUsefulException(e);
}
}
/*
* We won't like to kill other ss instances' ss_privoxy.exe.
* This function will check whether the given process is created
* by this process by checking the module path or command line.
*
* Since it's required to put ss in different dirs to run muti instances,
* different instance will create their unique "privoxy_UID.conf" where
* UID is hash of ss's location.
*/
private static bool IsChildProcess(Process process)
{
try
{
/*
* Under PortableMode, we could identify it by the path of ss_privoxy.exe.
*/
var path = process.MainModule.FileName;
return Utils.GetTempPath("ss_privoxy.exe").Equals(path);
}
catch (Exception ex)
{
/*
* Sometimes Process.GetProcessesByName will return some processes that
* are already dead, and that will cause exceptions here.
* We could simply ignore those exceptions.
*/
logger.LogUsefulException(ex);
return false;
}
}
private int GetFreePort(bool isIPv6 = false)
{
int defaultPort = 8123;
try
{
// TCP stack please do me a favor
TcpListener l = new TcpListener(isIPv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0);
l.Start();
var port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
catch (Exception e)
{
// in case access denied
logger.LogUsefulException(e);
return defaultPort;
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/Sip003Plugin.cs
================================================
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Shadowsocks.Model;
using Shadowsocks.Util.ProcessManagement;
namespace Shadowsocks.Controller.Service
{
// https://github.com/shadowsocks/shadowsocks-org/wiki/Plugin
public sealed class Sip003Plugin : IDisposable
{
public IPEndPoint LocalEndPoint { get; private set; }
public int ProcessId => _started ? _pluginProcess.Id : 0;
private readonly object _startProcessLock = new object();
private readonly Job _pluginJob;
private readonly Process _pluginProcess;
private bool _started;
private bool _disposed;
public static Sip003Plugin CreateIfConfigured(Server server, bool showPluginOutput)
{
if (server == null)
{
throw new ArgumentNullException(nameof(server));
}
if (string.IsNullOrWhiteSpace(server.plugin))
{
return null;
}
return new Sip003Plugin(
server.plugin,
server.plugin_opts,
server.plugin_args,
server.server,
server.server_port,
showPluginOutput);
}
private Sip003Plugin(string plugin, string pluginOpts, string pluginArgs, string serverAddress, int serverPort, bool showPluginOutput)
{
if (plugin == null) throw new ArgumentNullException(nameof(plugin));
if (string.IsNullOrWhiteSpace(serverAddress))
{
throw new ArgumentException("Value cannot be null or whitespace.", nameof(serverAddress));
}
if (serverPort <= 0 || serverPort > 65535)
{
throw new ArgumentOutOfRangeException("serverPort");
}
_pluginProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = plugin,
Arguments = pluginArgs,
UseShellExecute = false,
CreateNoWindow = !showPluginOutput,
ErrorDialog = false,
WindowStyle = ProcessWindowStyle.Hidden,
WorkingDirectory = Program.WorkingDirectory ?? Environment.CurrentDirectory,
Environment =
{
["SS_REMOTE_HOST"] = serverAddress,
["SS_REMOTE_PORT"] = serverPort.ToString(),
["SS_PLUGIN_OPTIONS"] = pluginOpts
}
}
};
_pluginJob = new Job();
}
public bool StartIfNeeded()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
lock (_startProcessLock)
{
if (_started && !_pluginProcess.HasExited)
{
return false;
}
var localPort = GetNextFreeTcpPort();
LocalEndPoint = new IPEndPoint(IPAddress.Loopback, localPort);
_pluginProcess.StartInfo.Environment["SS_LOCAL_HOST"] = LocalEndPoint.Address.ToString();
_pluginProcess.StartInfo.Environment["SS_LOCAL_PORT"] = LocalEndPoint.Port.ToString();
_pluginProcess.StartInfo.Arguments = ExpandEnvironmentVariables(_pluginProcess.StartInfo.Arguments, _pluginProcess.StartInfo.EnvironmentVariables);
try
{
_pluginProcess.Start();
}
catch (System.ComponentModel.Win32Exception ex)
{
// do not use File.Exists(...), it can not handle the scenarios when the plugin file is in system environment path.
// https://docs.microsoft.com/en-us/windows/win32/seccrypto/common-hresult-values
//if ((uint)ex.ErrorCode == 0x80004005)
// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d
if (ex.NativeErrorCode == 0x00000002)
{
throw new FileNotFoundException(I18N.GetString("Cannot find the plugin program file"), _pluginProcess.StartInfo.FileName, ex);
}
throw new ApplicationException(I18N.GetString("Plugin Program"), ex);
}
_pluginJob.AddProcess(_pluginProcess.Handle);
_started = true;
}
return true;
}
public string ExpandEnvironmentVariables(string name, StringDictionary environmentVariables = null)
{
// Expand the environment variables from the new process itself
if (environmentVariables != null)
{
foreach(string key in environmentVariables.Keys)
{
name = name.Replace($"%{key}%", environmentVariables[key]);
}
}
// Also expand the environment variables from current main process (system)
name = Environment.ExpandEnvironmentVariables(name);
return name;
}
static int GetNextFreeTcpPort()
{
var l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
public void Dispose()
{
if (_disposed)
{
return;
}
try
{
if (!_pluginProcess.HasExited)
{
_pluginProcess.Kill();
_pluginProcess.WaitForExit();
}
}
catch (Exception) { }
finally
{
try
{
_pluginProcess.Dispose();
_pluginJob.Dispose();
}
catch (Exception) { }
_disposed = true;
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/TCPRelay.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Timers;
using NLog;
using Shadowsocks.Controller.Strategy;
using Shadowsocks.Encryption;
using Shadowsocks.Encryption.AEAD;
using Shadowsocks.Encryption.Exception;
using Shadowsocks.Model;
using Shadowsocks.Proxy;
using Shadowsocks.Util.Sockets;
using static Shadowsocks.Encryption.EncryptorBase;
namespace Shadowsocks.Controller
{
internal class TCPRelay : Listener.Service
{
public event EventHandler OnConnected;
public event EventHandler OnInbound;
public event EventHandler OnOutbound;
public event EventHandler OnFailed;
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
private readonly ShadowsocksController _controller;
private DateTime _lastSweepTime;
private readonly Configuration _config;
public ISet Handlers { get; set; }
public TCPRelay(ShadowsocksController controller, Configuration conf)
{
_controller = controller;
_config = conf;
Handlers = new HashSet();
_lastSweepTime = DateTime.Now;
}
public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)
{
if (socket.ProtocolType != ProtocolType.Tcp
|| (length < 2 || firstPacket[0] != 5))
{
return false;
}
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
TCPHandler handler = new TCPHandler(_controller, _config, socket);
handler.OnConnected += OnConnected;
handler.OnInbound += OnInbound;
handler.OnOutbound += OnOutbound;
handler.OnFailed += OnFailed;
handler.OnClosed += (h, arg) =>
{
lock (Handlers)
{
Handlers.Remove(handler);
}
};
IList handlersToClose = new List();
lock (Handlers)
{
Handlers.Add(handler);
DateTime now = DateTime.Now;
if (now - _lastSweepTime > TimeSpan.FromSeconds(1))
{
_lastSweepTime = now;
foreach (TCPHandler handler1 in Handlers)
{
if (now - handler1.lastActivity > TimeSpan.FromSeconds(900))
{
handlersToClose.Add(handler1);
}
}
}
}
foreach (TCPHandler handler1 in handlersToClose)
{
logger.Debug("Closing timed out TCP connection.");
handler1.Close();
}
/*
* Start after we put it into Handlers set. Otherwise if it failed in handler.Start()
* then it will call handler.Close() before we add it into the set.
* Then the handler will never release until the next Handle call. Sometimes it will
* cause odd problems (especially during memory profiling).
*/
handler.Start(firstPacket, length);
return true;
}
public override void Stop()
{
List handlersToClose = new List();
lock (Handlers)
{
handlersToClose.AddRange(Handlers);
}
handlersToClose.ForEach(h => h.Close());
}
}
public class SSRelayEventArgs : EventArgs
{
public readonly Server server;
public SSRelayEventArgs(Server server)
{
this.server = server;
}
}
public class SSTransmitEventArgs : SSRelayEventArgs
{
public readonly long length;
public SSTransmitEventArgs(Server server, long length) : base(server)
{
this.length = length;
}
}
public class SSTCPConnectedEventArgs : SSRelayEventArgs
{
public readonly TimeSpan latency;
public SSTCPConnectedEventArgs(Server server, TimeSpan latency) : base(server)
{
this.latency = latency;
}
}
internal class TCPHandler
{
public event EventHandler OnConnected;
public event EventHandler OnInbound;
public event EventHandler OnOutbound;
public event EventHandler OnClosed;
public event EventHandler OnFailed;
private class AsyncSession
{
public IProxy Remote { get; }
public AsyncSession(IProxy remote)
{
Remote = remote;
}
}
private class AsyncSession : AsyncSession
{
public T State { get; set; }
public AsyncSession(IProxy remote, T state) : base(remote)
{
State = state;
}
public AsyncSession(AsyncSession session, T state) : base(session.Remote)
{
State = state;
}
}
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly int _serverTimeout;
private readonly int _proxyTimeout;
// each recv size.
public const int RecvSize = 2048;
// overhead of one chunk, reserved for AEAD ciphers
public const int ChunkOverheadSize = 16 * 2 /* two tags */ + AEADEncryptor.CHUNK_LEN_BYTES;
// max chunk size
public const uint MaxChunkSize = AEADEncryptor.CHUNK_LEN_MASK + AEADEncryptor.CHUNK_LEN_BYTES + 16 * 2;
// In general, the ciphertext length, we should take overhead into account
public const int BufferSize = RecvSize + (int)MaxChunkSize + 32 /* max salt len */;
public DateTime lastActivity;
private readonly ShadowsocksController _controller;
private readonly ForwardProxyConfig _config;
private readonly Socket _connection;
private IEncryptor _encryptor;
private Server _server;
private AsyncSession _currentRemoteSession;
private bool _proxyConnected;
private bool _destConnected;
private byte _command;
private byte[] _firstPacket;
private int _firstPacketLength;
private const int CMD_CONNECT = 0x01;
private const int CMD_BIND = 0x02;
private const int CMD_UDP_ASSOC = 0x03;
private int _addrBufLength = -1;
private int _totalRead = 0;
private int _totalWrite = 0;
// remote -> local proxy (ciphertext, before decrypt)
private readonly byte[] _remoteRecvBuffer = new byte[BufferSize];
// client -> local proxy (plaintext, before encrypt)
private readonly byte[] _connetionRecvBuffer = new byte[BufferSize];
// local proxy -> remote (plaintext, after decrypt)
private readonly byte[] _remoteSendBuffer = new byte[BufferSize];
// local proxy -> client (ciphertext, before decrypt)
private readonly byte[] _connetionSendBuffer = new byte[BufferSize];
private bool _connectionShutdown = false;
private bool _remoteShutdown = false;
private bool _closed = false;
// instance-based lock without static
private readonly object _encryptionLock = new object();
private readonly object _decryptionLock = new object();
private readonly object _closeConnLock = new object();
private DateTime _startConnectTime;
private DateTime _startReceivingTime;
private DateTime _startSendingTime;
private EndPoint _destEndPoint = null;
// TODO: decouple controller
public TCPHandler(ShadowsocksController controller, Configuration config, Socket socket)
{
_controller = controller;
_config = config.proxy;
_connection = socket;
_proxyTimeout = config.proxy.proxyTimeout * 1000;
_serverTimeout = config.GetCurrentServer().timeout * 1000;
lastActivity = DateTime.Now;
}
public void CreateRemote()
{
Server server = _controller.GetAServer(IStrategyCallerType.TCP, (IPEndPoint)_connection.RemoteEndPoint,
_destEndPoint);
if (server == null || server.server == "")
{
throw new ArgumentException("No server configured");
}
_encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
_server = server;
/* prepare address buffer length for AEAD */
Logger.Trace($"_addrBufLength={_addrBufLength}");
_encryptor.AddrBufLength = _addrBufLength;
}
public void Start(byte[] firstPacket, int length)
{
_firstPacket = firstPacket;
_firstPacketLength = length;
HandshakeReceive();
}
private void CheckClose()
{
if (_connectionShutdown && _remoteShutdown)
{
Close();
}
}
private void ErrorClose(Exception e)
{
Logger.LogUsefulException(e);
Close();
}
public void Close()
{
lock (_closeConnLock)
{
if (_closed)
{
return;
}
_closed = true;
}
OnClosed?.Invoke(this, new SSRelayEventArgs(_server));
try
{
_connection.Shutdown(SocketShutdown.Both);
_connection.Close();
}
catch (Exception e)
{
Logger.LogUsefulException(e);
}
if (_currentRemoteSession != null)
{
try
{
IProxy remote = _currentRemoteSession.Remote;
remote.Shutdown(SocketShutdown.Both);
remote.Close();
}
catch (Exception e)
{
Logger.LogUsefulException(e);
}
}
lock (_encryptionLock)
{
lock (_decryptionLock)
{
_encryptor?.Dispose();
}
}
}
private void HandshakeReceive()
{
if (_closed)
{
return;
}
try
{
int bytesRead = _firstPacketLength;
if (bytesRead > 1)
{
byte[] response = { 5, 0 };
if (_firstPacket[0] != 5)
{
// reject socks 4
response = new byte[] { 0, 91 };
Logger.Error("socks 5 protocol error");
}
_connection.BeginSend(response, 0, response.Length, SocketFlags.None,
HandshakeSendCallback, null);
}
else
{
Close();
}
}
catch (Exception e)
{
ErrorClose(e);
}
}
private void HandshakeSendCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
_connection.EndSend(ar);
// +-----+-----+-------+------+----------+----------+
// | VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +-----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +-----+-----+-------+------+----------+----------+
// Skip first 3 bytes, and read 2 more bytes to analysis the address.
// 2 more bytes is designed if address is domain then we don't need to read once more to get the addr length.
// validate is unnecessary, we did it in first packet, but we can do it in future version
_connection.BeginReceive(_connetionRecvBuffer, 0, 3 + ADDR_ATYP_LEN + 1, SocketFlags.None,
AddressReceiveCallback, null);
}
catch (Exception e)
{
ErrorClose(e);
}
}
private void AddressReceiveCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
int bytesRead = _connection.EndReceive(ar);
if (bytesRead >= 5)
{
_command = _connetionRecvBuffer[1];
switch (_command)
{
case CMD_CONNECT:
// +----+-----+-------+------+----------+----------+
// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
byte[] response = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 };
_connection.BeginSend(response, 0, response.Length, SocketFlags.None,
ConnectResponseCallback, null);
break;
case CMD_UDP_ASSOC:
ReadAddress(HandleUDPAssociate);
break;
case CMD_BIND: // not implemented
default:
Logger.Debug("Unsupported CMD=" + _command);
Close();
break;
}
}
else
{
Logger.Debug(
"failed to recv data in Shadowsocks.Controller.TCPHandler.handshakeReceive2Callback()");
Close();
}
}
catch (Exception e)
{
ErrorClose(e);
}
}
private void ConnectResponseCallback(IAsyncResult ar)
{
try
{
_connection.EndSend(ar);
ReadAddress(StartConnect);
}
catch (Exception e)
{
ErrorClose(e);
}
}
private void ReadAddress(Action onSuccess)
{
int atyp = _connetionRecvBuffer[3];
switch (atyp)
{
case ATYP_IPv4: // IPv4 address, 4 bytes
ReadAddress(4 + ADDR_PORT_LEN - 1, onSuccess);
break;
case ATYP_DOMAIN: // domain name, length + str
int len = _connetionRecvBuffer[4];
ReadAddress(len + ADDR_PORT_LEN, onSuccess);
break;
case ATYP_IPv6: // IPv6 address, 16 bytes
ReadAddress(16 + ADDR_PORT_LEN - 1, onSuccess);
break;
default:
Logger.Debug("Unsupported ATYP=" + atyp);
Close();
break;
}
}
private void ReadAddress(int bytesRemain, Action onSuccess)
{
// drop [ VER | CMD | RSV ]
Array.Copy(_connetionRecvBuffer, 3, _connetionRecvBuffer, 0, ADDR_ATYP_LEN + 1);
// Read the remain address bytes
_connection.BeginReceive(_connetionRecvBuffer, 2, RecvSize - 2, SocketFlags.None, OnAddressFullyRead,
new object[] { bytesRemain, onSuccess });
}
private void OnAddressFullyRead(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
int bytesRead = _connection.EndReceive(ar);
object[] states = (object[])ar.AsyncState;
int bytesRemain = (int)states[0];
Action onSuccess = (Action)states[1];
if (bytesRead >= bytesRemain)
{
_firstPacketLength = bytesRead + 2;
int atyp = _connetionRecvBuffer[0];
string dstAddr = "Unknown";
int dstPort = -1;
switch (atyp)
{
case ATYP_IPv4: // IPv4 address, 4 bytes
dstAddr = new IPAddress(_connetionRecvBuffer.Skip(1).Take(4).ToArray()).ToString();
dstPort = (_connetionRecvBuffer[5] << 8) + _connetionRecvBuffer[6];
_addrBufLength = ADDR_ATYP_LEN + 4 + ADDR_PORT_LEN;
break;
case ATYP_DOMAIN: // domain name, length + str
int len = _connetionRecvBuffer[1];
dstAddr = System.Text.Encoding.UTF8.GetString(_connetionRecvBuffer, 2, len);
dstPort = (_connetionRecvBuffer[len + 2] << 8) + _connetionRecvBuffer[len + 3];
_addrBufLength = ADDR_ATYP_LEN + 1 + len + ADDR_PORT_LEN;
break;
case ATYP_IPv6: // IPv6 address, 16 bytes
dstAddr = $"[{new IPAddress(_connetionRecvBuffer.Skip(1).Take(16).ToArray())}]";
dstPort = (_connetionRecvBuffer[17] << 8) + _connetionRecvBuffer[18];
_addrBufLength = ADDR_ATYP_LEN + 16 + ADDR_PORT_LEN;
break;
}
Logger.Debug($"connect to {dstAddr}:{dstPort}");
_destEndPoint = SocketUtil.GetEndPoint(dstAddr, dstPort);
onSuccess.Invoke(); /* StartConnect() */
}
else
{
Logger.Debug("failed to recv data in Shadowsocks.Controller.TCPHandler.OnAddressFullyRead()");
Close();
}
}
catch (Exception e)
{
ErrorClose(e);
}
}
private void HandleUDPAssociate()
{
IPEndPoint endPoint = (IPEndPoint)_connection.LocalEndPoint;
byte[] address = endPoint.Address.GetAddressBytes();
int port = endPoint.Port;
byte[] response = new byte[4 + address.Length + ADDR_PORT_LEN];
response[0] = 5;
switch (endPoint.AddressFamily)
{
case AddressFamily.InterNetwork:
response[3] = ATYP_IPv4;
break;
case AddressFamily.InterNetworkV6:
response[3] = ATYP_IPv6;
break;
}
address.CopyTo(response, 4);
response[response.Length - 1] = (byte)(port & 0xFF);
response[response.Length - 2] = (byte)((port >> 8) & 0xFF);
_connection.BeginSend(response, 0, response.Length, SocketFlags.None, ReadAll, true);
}
private void ReadAll(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
if (ar.AsyncState != null)
{
_connection.EndSend(ar);
_connection.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None,
ReadAll, null);
}
else
{
int bytesRead = _connection.EndReceive(ar);
if (bytesRead > 0)
{
_connection.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None,
ReadAll, null);
}
else
{
Close();
}
}
}
catch (Exception e)
{
ErrorClose(e);
}
}
// inner class
private class ProxyTimer : Timer
{
public AsyncSession Session;
public EndPoint DestEndPoint;
public Server Server;
public ProxyTimer(int p) : base(p)
{
}
}
private class ServerTimer : Timer
{
public AsyncSession Session;
public Server Server;
public ServerTimer(int p) : base(p)
{
}
}
private void StartConnect()
{
try
{
CreateRemote();
// Setting up proxy
IProxy remote;
EndPoint proxyEP = null;
EndPoint serverEP = SocketUtil.GetEndPoint(_server.server, _server.server_port);
EndPoint pluginEP = _controller.GetPluginLocalEndPointIfConfigured(_server);
if (pluginEP != null)
{
serverEP = pluginEP;
remote = new DirectConnect();
}
else if (_config.useProxy)
{
switch (_config.proxyType)
{
case ForwardProxyConfig.PROXY_SOCKS5:
remote = new Socks5Proxy();
break;
case ForwardProxyConfig.PROXY_HTTP:
remote = new HttpProxy();
break;
default:
throw new NotSupportedException("Unknown forward proxy.");
}
proxyEP = SocketUtil.GetEndPoint(_config.proxyServer, _config.proxyPort);
}
else
{
remote = new DirectConnect();
}
AsyncSession session = new AsyncSession(remote);
lock (_closeConnLock)
{
if (_closed)
{
remote.Close();
return;
}
_currentRemoteSession = session;
}
ProxyTimer proxyTimer = new ProxyTimer(_proxyTimeout) { AutoReset = false };
proxyTimer.Elapsed += ProxyConnectTimer_Elapsed;
proxyTimer.Enabled = true;
proxyTimer.Session = session;
proxyTimer.DestEndPoint = serverEP;
proxyTimer.Server = _server;
_proxyConnected = false;
// Connect to the proxy server.
remote.BeginConnectProxy(proxyEP, ProxyConnectCallback,
new AsyncSession(remote, proxyTimer));
}
catch (Exception e)
{
ErrorClose(e);
}
}
private void ProxyConnectTimer_Elapsed(object sender, ElapsedEventArgs e)
{
ProxyTimer timer = (ProxyTimer)sender;
timer.Elapsed -= ProxyConnectTimer_Elapsed;
timer.Enabled = false;
timer.Dispose();
if (_proxyConnected || _destConnected || _closed)
{
return;
}
IProxy proxy = timer.Session.Remote;
Logger.Info($"Proxy {proxy.ProxyEndPoint} timed out");
proxy.Close();
Close();
}
private void ProxyConnectCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
AsyncSession session = (AsyncSession)ar.AsyncState;
ProxyTimer timer = session.State;
EndPoint destEndPoint = timer.DestEndPoint;
Server server = timer.Server;
timer.Elapsed -= ProxyConnectTimer_Elapsed;
timer.Enabled = false;
timer.Dispose();
IProxy remote = session.Remote;
// Complete the connection.
remote.EndConnectProxy(ar);
_proxyConnected = true;
if (!(remote is DirectConnect))
{
Logger.Debug($"Socket connected to proxy {remote.ProxyEndPoint}");
}
_startConnectTime = DateTime.Now;
ServerTimer connectTimer = new ServerTimer(_serverTimeout) { AutoReset = false };
connectTimer.Elapsed += DestConnectTimer_Elapsed;
connectTimer.Enabled = true;
connectTimer.Session = session;
connectTimer.Server = server;
_destConnected = false;
NetworkCredential auth = null;
if (_config.useAuth)
{
auth = new NetworkCredential(_config.authUser, _config.authPwd);
}
// Connect to the remote endpoint.
remote.BeginConnectDest(destEndPoint, ConnectCallback,
new AsyncSession(session, connectTimer), auth);
}
catch (ArgumentException)
{
}
catch (Exception e)
{
ErrorClose(e);
}
}
private void DestConnectTimer_Elapsed(object sender, ElapsedEventArgs e)
{
ServerTimer timer = (ServerTimer)sender;
timer.Elapsed -= DestConnectTimer_Elapsed;
timer.Enabled = false;
timer.Dispose();
if (_destConnected || _closed)
{
return;
}
AsyncSession session = timer.Session;
Server server = timer.Server;
OnFailed?.Invoke(this, new SSRelayEventArgs(_server));
Logger.Info($"{server.ToString()} timed out");
session.Remote.Close();
Close();
}
private void ConnectCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
AsyncSession session = (AsyncSession)ar.AsyncState;
ServerTimer timer = session.State;
_server = timer.Server;
timer.Elapsed -= DestConnectTimer_Elapsed;
timer.Enabled = false;
timer.Dispose();
IProxy remote = session.Remote;
// Complete the connection.
remote.EndConnectDest(ar);
_destConnected = true;
Logger.Debug($"Socket connected to ss server: {_server.ToString()}");
TimeSpan latency = DateTime.Now - _startConnectTime;
OnConnected?.Invoke(this, new SSTCPConnectedEventArgs(_server, latency));
StartPipe(session);
}
catch (ArgumentException)
{
}
catch (Exception e)
{
if (_server != null)
{
OnFailed?.Invoke(this, new SSRelayEventArgs(_server));
}
ErrorClose(e);
}
}
private void TryReadAvailableData()
{
int available = Math.Min(_connection.Available, RecvSize - _firstPacketLength);
if (available > 0)
{
int size = _connection.Receive(_connetionRecvBuffer, _firstPacketLength, available,
SocketFlags.None);
_firstPacketLength += size;
}
}
private void StartPipe(AsyncSession session)
{
if (_closed)
{
return;
}
try
{
_startReceivingTime = DateTime.Now;
session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None,
PipeRemoteReceiveCallback, session);
TryReadAvailableData();
Logger.Trace($"_firstPacketLength = {_firstPacketLength}");
SendToServer(_firstPacketLength, session);
}
catch (Exception e)
{
ErrorClose(e);
}
}
private void PipeRemoteReceiveCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
AsyncSession session = (AsyncSession)ar.AsyncState;
int bytesRead = session.Remote.EndReceive(ar);
_totalRead += bytesRead;
OnInbound?.Invoke(this, new SSTransmitEventArgs(_server, bytesRead));
if (bytesRead > 0)
{
lastActivity = DateTime.Now;
int bytesToSend = -1;
lock (_decryptionLock)
{
try
{
_encryptor.Decrypt(_remoteRecvBuffer, bytesRead, _remoteSendBuffer, out bytesToSend);
}
catch (CryptoErrorException)
{
Logger.Error("decryption error");
Close();
return;
}
}
if (bytesToSend == 0)
{
// need more to decrypt
Logger.Trace("Need more to decrypt");
session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None,
PipeRemoteReceiveCallback, session);
return;
}
Logger.Trace($"start sending {bytesToSend}");
_connection.BeginSend(_remoteSendBuffer, 0, bytesToSend, SocketFlags.None,
PipeConnectionSendCallback, new object[] { session, bytesToSend });
}
else
{
_connection.Shutdown(SocketShutdown.Send);
_connectionShutdown = true;
CheckClose();
}
}
catch (Exception e)
{
ErrorClose(e);
}
}
private void PipeConnectionReceiveCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
int bytesRead = _connection.EndReceive(ar);
AsyncSession session = (AsyncSession)ar.AsyncState;
IProxy remote = session.Remote;
if (bytesRead > 0)
{
SendToServer(bytesRead, session);
}
else
{
remote.Shutdown(SocketShutdown.Send);
_remoteShutdown = true;
CheckClose();
}
}
catch (Exception e)
{
ErrorClose(e);
}
}
private void SendToServer(int length, AsyncSession session)
{
_totalWrite += length;
int bytesToSend;
lock (_encryptionLock)
{
try
{
_encryptor.Encrypt(_connetionRecvBuffer, length, _connetionSendBuffer, out bytesToSend);
}
catch (CryptoErrorException)
{
Logger.Debug("encryption error");
Close();
return;
}
}
OnOutbound?.Invoke(this, new SSTransmitEventArgs(_server, bytesToSend));
_startSendingTime = DateTime.Now;
session.Remote.BeginSend(_connetionSendBuffer, 0, bytesToSend, SocketFlags.None,
PipeRemoteSendCallback, new object[] { session, bytesToSend });
}
private void PipeRemoteSendCallback(IAsyncResult ar)
{
if (_closed)
{
return;
}
try
{
object[] container = (object[])ar.AsyncState;
AsyncSession session = (AsyncSession)container[0];
int bytesShouldSend = (int)container[1];
int bytesSent = session.Remote.EndSend(ar);
if (bytesSent > 0)
{
lastActivity = DateTime.Now;
}
int bytesRemaining = bytesShouldSend - bytesSent;
if (bytesRemaining > 0)
{
Logger.Info("reconstruct _connetionSendBuffer to re-send");
Buffer.BlockCopy(_connetionSendBuffer, bytesSent, _connetionSendBuffer, 0, bytesRemaining);
session.Remote.BeginSend(_connetionSendBuffer, 0, bytesRemaining, SocketFlags.None,
PipeRemoteSendCallback, new object[] { session, bytesRemaining });
return;
}
_connection.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None,
PipeConnectionReceiveCallback, session);
}
catch (Exception e)
{
ErrorClose(e);
}
}
// In general, we assume there is no delay between local proxy and client, add this for sanity
private void PipeConnectionSendCallback(IAsyncResult ar)
{
try
{
object[] container = (object[])ar.AsyncState;
AsyncSession session = (AsyncSession)container[0];
int bytesShouldSend = (int)container[1];
int bytesSent = _connection.EndSend(ar);
int bytesRemaining = bytesShouldSend - bytesSent;
if (bytesRemaining > 0)
{
Logger.Info("reconstruct _remoteSendBuffer to re-send");
Buffer.BlockCopy(_remoteSendBuffer, bytesSent, _remoteSendBuffer, 0, bytesRemaining);
_connection.BeginSend(_remoteSendBuffer, 0, bytesRemaining, SocketFlags.None,
PipeConnectionSendCallback, new object[] { session, bytesRemaining });
return;
}
session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None,
PipeRemoteReceiveCallback, session);
}
catch (Exception e)
{
ErrorClose(e);
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Service/UDPRelay.cs
================================================
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using NLog;
using Shadowsocks.Controller.Strategy;
using Shadowsocks.Encryption;
using Shadowsocks.Model;
namespace Shadowsocks.Controller
{
class UDPRelay : Listener.Service
{
private ShadowsocksController _controller;
// TODO: choose a smart number
private LRUCache _cache = new LRUCache(512);
public long outbound = 0;
public long inbound = 0;
public UDPRelay(ShadowsocksController controller)
{
this._controller = controller;
}
public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)
{
if (socket.ProtocolType != ProtocolType.Udp)
{
return false;
}
if (length < 4)
{
return false;
}
Listener.UDPState udpState = (Listener.UDPState)state;
IPEndPoint remoteEndPoint = (IPEndPoint)udpState.remoteEndPoint;
UDPHandler handler = _cache.get(remoteEndPoint);
if (handler == null)
{
handler = new UDPHandler(socket, _controller.GetAServer(IStrategyCallerType.UDP, remoteEndPoint, null/*TODO: fix this*/), remoteEndPoint);
handler.Receive();
_cache.add(remoteEndPoint, handler);
}
handler.Send(firstPacket, length);
return true;
}
public class UDPHandler
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private Socket _local;
private Socket _remote;
private Server _server;
private byte[] _buffer = new byte[65536];
private IPEndPoint _localEndPoint;
private IPEndPoint _remoteEndPoint;
private IPAddress GetIPAddress()
{
switch (_remote.AddressFamily)
{
case AddressFamily.InterNetwork:
return IPAddress.Any;
case AddressFamily.InterNetworkV6:
return IPAddress.IPv6Any;
default:
return IPAddress.Any;
}
}
public UDPHandler(Socket local, Server server, IPEndPoint localEndPoint)
{
_local = local;
_server = server;
_localEndPoint = localEndPoint;
// TODO async resolving
IPAddress ipAddress;
bool parsed = IPAddress.TryParse(server.server, out ipAddress);
if (!parsed)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server);
ipAddress = ipHostInfo.AddressList[0];
}
_remoteEndPoint = new IPEndPoint(ipAddress, server.server_port);
_remote = new Socket(_remoteEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
_remote.Bind(new IPEndPoint(GetIPAddress(), 0));
}
public void Send(byte[] data, int length)
{
IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);
byte[] dataIn = new byte[length - 3];
Array.Copy(data, 3, dataIn, 0, length - 3);
byte[] dataOut = new byte[65536]; // enough space for AEAD ciphers
int outlen;
encryptor.EncryptUDP(dataIn, length - 3, dataOut, out outlen);
logger.Debug(_localEndPoint, _remoteEndPoint, outlen, "UDP Relay");
_remote?.SendTo(dataOut, outlen, SocketFlags.None, _remoteEndPoint);
}
public void Receive()
{
EndPoint remoteEndPoint = new IPEndPoint(GetIPAddress(), 0);
logger.Debug($"++++++Receive Server Port, size:" + _buffer.Length);
_remote?.BeginReceiveFrom(_buffer, 0, _buffer.Length, 0, ref remoteEndPoint, new AsyncCallback(RecvFromCallback), null);
}
public void RecvFromCallback(IAsyncResult ar)
{
try
{
if (_remote == null) return;
EndPoint remoteEndPoint = new IPEndPoint(GetIPAddress(), 0);
int bytesRead = _remote.EndReceiveFrom(ar, ref remoteEndPoint);
byte[] dataOut = new byte[bytesRead];
int outlen;
IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);
encryptor.DecryptUDP(_buffer, bytesRead, dataOut, out outlen);
byte[] sendBuf = new byte[outlen + 3];
Array.Copy(dataOut, 0, sendBuf, 3, outlen);
logger.Debug(_localEndPoint, _remoteEndPoint, outlen, "UDP Relay");
_local?.SendTo(sendBuf, outlen + 3, 0, _localEndPoint);
Receive();
}
catch (ObjectDisposedException)
{
// TODO: handle the ObjectDisposedException
}
catch (Exception)
{
// TODO: need more think about handle other Exceptions, or should remove this catch().
}
finally
{
// No matter success or failed, we keep receiving
}
}
public void Close()
{
try
{
_remote?.Close();
}
catch (ObjectDisposedException)
{
// TODO: handle the ObjectDisposedException
}
catch (Exception)
{
// TODO: need more think about handle other Exceptions, or should remove this catch().
}
}
}
}
#region LRU cache
// cc by-sa 3.0 http://stackoverflow.com/a/3719378/1124054
class LRUCache where V : UDPRelay.UDPHandler
{
private int capacity;
private Dictionary>> cacheMap = new Dictionary>>();
private LinkedList> lruList = new LinkedList>();
public LRUCache(int capacity)
{
this.capacity = capacity;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public V get(K key)
{
LinkedListNode> node;
if (cacheMap.TryGetValue(key, out node))
{
V value = node.Value.value;
lruList.Remove(node);
lruList.AddLast(node);
return value;
}
return default(V);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void add(K key, V val)
{
if (cacheMap.Count >= capacity)
{
RemoveFirst();
}
LRUCacheItem cacheItem = new LRUCacheItem(key, val);
LinkedListNode> node = new LinkedListNode>(cacheItem);
lruList.AddLast(node);
cacheMap.Add(key, node);
}
private void RemoveFirst()
{
// Remove from LRUPriority
LinkedListNode> node = lruList.First;
lruList.RemoveFirst();
// Remove from cache
cacheMap.Remove(node.Value.key);
node.Value.value.Close();
}
}
class LRUCacheItem
{
public LRUCacheItem(K k, V v)
{
key = k;
value = v;
}
public K key;
public V value;
}
#endregion
}
================================================
FILE: shadowsocks-csharp/Controller/Service/UpdateChecker.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using Newtonsoft.Json.Linq;
using NLog;
using Shadowsocks.Localization;
using Shadowsocks.Model;
using Shadowsocks.Util;
using Shadowsocks.Views;
namespace Shadowsocks.Controller
{
public class UpdateChecker
{
private readonly Logger logger;
private readonly HttpClient httpClient;
// https://developer.github.com/v3/repos/releases/
private const string UpdateURL = "https://api.github.com/repos/shadowsocks/shadowsocks-windows/releases";
private Configuration _config;
private Window versionUpdatePromptWindow;
private JToken _releaseObject;
public string NewReleaseVersion { get; private set; }
public string NewReleaseZipFilename { get; private set; }
public event EventHandler CheckUpdateCompleted;
public const string Version = "4.4.1.0";
private readonly Version _version;
public UpdateChecker()
{
logger = LogManager.GetCurrentClassLogger();
httpClient = Program.MainController.GetHttpClient();
_version = new Version(Version);
_config = Program.MainController.GetCurrentConfiguration();
}
///
/// Checks for updates and asks the user if updates are found.
///
/// A delay in milliseconds before checking.
///
public async Task CheckForVersionUpdate(int millisecondsDelay = 0)
{
// delay
logger.Info($"Waiting for {millisecondsDelay}ms before checking for version update.");
await Task.Delay(millisecondsDelay);
// update _config so we would know if the user checked or unchecked pre-release checks
_config = Program.MainController.GetCurrentConfiguration();
// start
logger.Info($"Checking for version update.");
try
{
// list releases via API
var releasesListJsonString = await httpClient.GetStringAsync(UpdateURL);
// parse
var releasesJArray = JArray.Parse(releasesListJsonString);
foreach (var releaseObject in releasesJArray)
{
var releaseTagName = (string)releaseObject["tag_name"];
var releaseVersion = new Version(releaseTagName);
if (releaseTagName == _config.skippedUpdateVersion) // finished checking
break;
if (releaseVersion.CompareTo(_version) > 0 &&
(!(bool)releaseObject["prerelease"] || _config.checkPreRelease && (bool)releaseObject["prerelease"])) // selected
{
logger.Info($"Found new version {releaseTagName}.");
_releaseObject = releaseObject;
NewReleaseVersion = releaseTagName;
AskToUpdate(releaseObject);
return;
}
}
logger.Info($"No new versions found.");
CheckUpdateCompleted?.Invoke(this, new EventArgs());
}
catch (Exception e)
{
logger.LogUsefulException(e);
}
}
///
/// Opens a window to show the update's information.
///
/// The update release object.
private void AskToUpdate(JToken releaseObject)
{
if (versionUpdatePromptWindow == null)
{
versionUpdatePromptWindow = new Window()
{
Title = LocalizationProvider.GetLocalizedValue("VersionUpdate"),
Height = 480,
Width = 640,
MinHeight = 480,
MinWidth = 640,
Content = new VersionUpdatePromptView(releaseObject)
};
versionUpdatePromptWindow.Closed += VersionUpdatePromptWindow_Closed;
versionUpdatePromptWindow.Show();
}
versionUpdatePromptWindow.Activate();
}
private void VersionUpdatePromptWindow_Closed(object sender, EventArgs e)
{
versionUpdatePromptWindow = null;
}
///
/// Downloads the selected update and notifies the user.
///
///
public async Task DoUpdate()
{
try
{
var assets = (JArray)_releaseObject["assets"];
// download all assets
foreach (JObject asset in assets)
{
var filename = (string)asset["name"];
var browser_download_url = (string)asset["browser_download_url"];
var response = await httpClient.GetAsync(browser_download_url);
using (var downloadedFileStream = File.Create(Utils.GetTempPath(filename)))
await response.Content.CopyToAsync(downloadedFileStream);
logger.Info($"Downloaded {filename}.");
// store .zip filename
if (filename.EndsWith(".zip"))
NewReleaseZipFilename = filename;
}
logger.Info("Finished downloading.");
// notify user
CloseVersionUpdatePromptWindow();
Process.Start("explorer.exe", $"/select, \"{Utils.GetTempPath(NewReleaseZipFilename)}\"");
}
catch (Exception e)
{
logger.LogUsefulException(e);
}
}
///
/// Saves the skipped update version.
///
public void SkipUpdate()
{
var version = (string)_releaseObject["tag_name"] ?? "";
_config.skippedUpdateVersion = version;
Program.MainController.SaveSkippedUpdateVerion(version);
logger.Info($"The update {version} has been skipped and will be ignored next time.");
CloseVersionUpdatePromptWindow();
}
///
/// Closes the update prompt window.
///
public void CloseVersionUpdatePromptWindow()
{
if (versionUpdatePromptWindow != null)
{
versionUpdatePromptWindow.Close();
versionUpdatePromptWindow = null;
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/ShadowsocksController.cs
================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using NLog;
using Shadowsocks.Controller.Service;
using Shadowsocks.Controller.Strategy;
using Shadowsocks.Model;
using Shadowsocks.Util;
using WPFLocalizeExtension.Engine;
namespace Shadowsocks.Controller
{
public class ShadowsocksController
{
private readonly Logger logger;
private readonly HttpClient httpClient;
// controller:
// handle user actions
// manipulates UI
// interacts with low level logic
#region Members definition
private Thread _trafficThread;
private Listener _listener;
private PACDaemon _pacDaemon;
private PACServer _pacServer;
private Configuration _config;
private StrategyManager _strategyManager;
private PrivoxyRunner privoxyRunner;
private readonly ConcurrentDictionary _pluginsByServer;
private long _inboundCounter = 0;
private long _outboundCounter = 0;
public long InboundCounter => Interlocked.Read(ref _inboundCounter);
public long OutboundCounter => Interlocked.Read(ref _outboundCounter);
public Queue trafficPerSecondQueue;
private bool stopped = false;
public class PathEventArgs : EventArgs
{
public string Path;
}
public class UpdatedEventArgs : EventArgs
{
public string OldVersion;
public string NewVersion;
}
public class TrafficPerSecond
{
public long inboundCounter;
public long outboundCounter;
public long inboundIncreasement;
public long outboundIncreasement;
}
public event EventHandler ConfigChanged;
public event EventHandler EnableStatusChanged;
public event EventHandler EnableGlobalChanged;
public event EventHandler ShareOverLANStatusChanged;
public event EventHandler VerboseLoggingStatusChanged;
public event EventHandler ShowPluginOutputChanged;
public event EventHandler TrafficChanged;
// when user clicked Edit PAC, and PAC file has already created
public event EventHandler PACFileReadyToOpen;
public event EventHandler UserRuleFileReadyToOpen;
public event EventHandler UpdatePACFromGeositeCompleted;
public event ErrorEventHandler UpdatePACFromGeositeError;
public event ErrorEventHandler Errored;
// Invoked when controller.Start();
public event EventHandler ProgramUpdated;
#endregion
public ShadowsocksController()
{
logger = LogManager.GetCurrentClassLogger();
httpClient = new HttpClient();
_config = Configuration.Load();
Configuration.Process(ref _config);
_strategyManager = new StrategyManager(this);
_pluginsByServer = new ConcurrentDictionary();
StartTrafficStatistics(61);
ProgramUpdated += (o, e) =>
{
// version update precedures
if (e.OldVersion == "4.3.0.0" || e.OldVersion == "4.3.1.0")
_config.geositeDirectGroups.Add("private");
logger.Info($"Updated from {e.OldVersion} to {e.NewVersion}");
};
}
#region Basic
public void Start(bool systemWakeUp = false)
{
if (_config.firstRunOnNewVersion && !systemWakeUp)
{
ProgramUpdated.Invoke(this, new UpdatedEventArgs()
{
OldVersion = _config.version,
NewVersion = UpdateChecker.Version,
});
// delete pac.txt when regeneratePacOnUpdate is true
if (_config.regeneratePacOnUpdate)
try
{
File.Delete(PACDaemon.PAC_FILE);
logger.Info("Deleted pac.txt from previous version.");
}
catch (Exception e)
{
logger.LogUsefulException(e);
}
// finish up first run of new version
_config.firstRunOnNewVersion = false;
_config.version = UpdateChecker.Version;
Configuration.Save(_config);
}
Reload();
if (!systemWakeUp)
HotkeyReg.RegAllHotkeys();
}
public void Stop()
{
if (stopped)
{
return;
}
stopped = true;
if (_listener != null)
{
_listener.Stop();
}
StopPlugins();
if (privoxyRunner != null)
{
privoxyRunner.Stop();
}
if (_config.enabled)
{
SystemProxy.Update(_config, true, null);
}
Encryption.RNG.Close();
}
protected void Reload()
{
Encryption.RNG.Reload();
// some logic in configuration updated the config when saving, we need to read it again
_config = Configuration.Load();
Configuration.Process(ref _config);
NLogConfig.LoadConfiguration();
logger.Info($"WPF Localization Extension|Current culture: {LocalizeDictionary.CurrentCulture}");
// set User-Agent for httpClient
try
{
if (!string.IsNullOrWhiteSpace(_config.userAgentString))
httpClient.DefaultRequestHeaders.Add("User-Agent", _config.userAgentString);
}
catch
{
// reset userAgent to default and reapply
Configuration.ResetUserAgent(_config);
httpClient.DefaultRequestHeaders.Add("User-Agent", _config.userAgentString);
}
privoxyRunner = privoxyRunner ?? new PrivoxyRunner();
_pacDaemon = _pacDaemon ?? new PACDaemon(_config);
_pacDaemon.PACFileChanged += PacDaemon_PACFileChanged;
_pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged;
_pacServer = _pacServer ?? new PACServer(_pacDaemon);
_pacServer.UpdatePACURL(_config); // So PACServer works when system proxy disabled.
GeositeUpdater.ResetEvent();
GeositeUpdater.UpdateCompleted += PacServer_PACUpdateCompleted;
GeositeUpdater.Error += PacServer_PACUpdateError;
_listener?.Stop();
StopPlugins();
// don't put PrivoxyRunner.Start() before pacServer.Stop()
// or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1
// though UseShellExecute is set to true now
// http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open
privoxyRunner.Stop();
try
{
var strategy = GetCurrentStrategy();
strategy?.ReloadServers();
StartPlugin();
privoxyRunner.Start(_config);
TCPRelay tcpRelay = new TCPRelay(this, _config);
tcpRelay.OnInbound += UpdateInboundCounter;
tcpRelay.OnOutbound += UpdateOutboundCounter;
tcpRelay.OnFailed += (o, e) => GetCurrentStrategy()?.SetFailure(e.server);
UDPRelay udpRelay = new UDPRelay(this);
List services = new List
{
tcpRelay,
udpRelay,
_pacServer,
new PortForwarder(privoxyRunner.RunningPort)
};
_listener = new Listener(services);
_listener.Start(_config);
}
catch (Exception e)
{
// translate Microsoft language into human language
// i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
if (e is SocketException se)
{
if (se.SocketErrorCode == SocketError.AddressAlreadyInUse)
{
e = new Exception(I18N.GetString("Port {0} already in use", _config.localPort), e);
}
else if (se.SocketErrorCode == SocketError.AccessDenied)
{
e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e);
}
}
logger.LogUsefulException(e);
ReportError(e);
}
ConfigChanged?.Invoke(this, new EventArgs());
UpdateSystemProxy();
}
protected void SaveConfig(Configuration newConfig)
{
Configuration.Save(newConfig);
Reload();
}
protected void ReportError(Exception e)
{
Errored?.Invoke(this, new ErrorEventArgs(e));
}
public HttpClient GetHttpClient() => httpClient;
public Server GetCurrentServer() => _config.GetCurrentServer();
public Configuration GetCurrentConfiguration() => _config;
public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)
{
IStrategy strategy = GetCurrentStrategy();
if (strategy != null)
{
return strategy.GetAServer(type, localIPEndPoint, destEndPoint);
}
if (_config.index < 0)
{
_config.index = 0;
}
return GetCurrentServer();
}
public void SaveServers(List servers, int localPort, bool portableMode)
{
_config.configs = servers;
_config.localPort = localPort;
_config.portableMode = portableMode;
Configuration.Save(_config);
}
public void SelectServerIndex(int index)
{
_config.index = index;
_config.strategy = null;
SaveConfig(_config);
}
public void ToggleShareOverLAN(bool enabled)
{
_config.shareOverLan = enabled;
SaveConfig(_config);
ShareOverLANStatusChanged?.Invoke(this, new EventArgs());
}
#endregion
#region OS Proxy
public void ToggleEnable(bool enabled)
{
_config.enabled = enabled;
SaveConfig(_config);
EnableStatusChanged?.Invoke(this, new EventArgs());
}
public void ToggleGlobal(bool global)
{
_config.global = global;
SaveConfig(_config);
EnableGlobalChanged?.Invoke(this, new EventArgs());
}
public void SaveProxy(ForwardProxyConfig proxyConfig)
{
_config.proxy = proxyConfig;
SaveConfig(_config);
}
private void UpdateSystemProxy()
{
SystemProxy.Update(_config, false, _pacServer);
}
#endregion
#region PAC
private void PacDaemon_PACFileChanged(object sender, EventArgs e)
{
UpdateSystemProxy();
}
private void PacServer_PACUpdateCompleted(object sender, GeositeResultEventArgs e)
{
UpdatePACFromGeositeCompleted?.Invoke(this, e);
}
private void PacServer_PACUpdateError(object sender, ErrorEventArgs e)
{
UpdatePACFromGeositeError?.Invoke(this, e);
}
private static readonly IEnumerable IgnoredLineBegins = new[] { '!', '[' };
private void PacDaemon_UserRuleFileChanged(object sender, EventArgs e)
{
GeositeUpdater.MergeAndWritePACFile(_config.geositeDirectGroups, _config.geositeProxiedGroups, _config.geositePreferDirect);
UpdateSystemProxy();
}
public void CopyPacUrl()
{
Clipboard.SetDataObject(_pacServer.PacUrl);
}
public void SavePACUrl(string pacUrl)
{
_config.pacUrl = pacUrl;
SaveConfig(_config);
ConfigChanged?.Invoke(this, new EventArgs());
}
public void UseOnlinePAC(bool useOnlinePac)
{
_config.useOnlinePac = useOnlinePac;
SaveConfig(_config);
ConfigChanged?.Invoke(this, new EventArgs());
}
public void TouchPACFile()
{
string pacFilename = _pacDaemon.TouchPACFile();
PACFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = pacFilename });
}
public void TouchUserRuleFile()
{
string userRuleFilename = _pacDaemon.TouchUserRuleFile();
UserRuleFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = userRuleFilename });
}
public void ToggleSecureLocalPac(bool enabled)
{
_config.secureLocalPac = enabled;
SaveConfig(_config);
ConfigChanged?.Invoke(this, new EventArgs());
}
public void ToggleRegeneratePacOnUpdate(bool enabled)
{
_config.regeneratePacOnUpdate = enabled;
SaveConfig(_config);
ConfigChanged?.Invoke(this, new EventArgs());
}
#endregion
#region SIP002
public bool AskAddServerBySSURL(string ssURL)
{
var dr = MessageBox.Show(I18N.GetString("Import from URL: {0} ?", ssURL), I18N.GetString("Shadowsocks"), MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
if (AddServerBySSURL(ssURL))
{
MessageBox.Show(I18N.GetString("Successfully imported from {0}", ssURL));
return true;
}
else
{
MessageBox.Show(I18N.GetString("Failed to import. Please check if the link is valid."));
}
}
return false;
}
public bool AddServerBySSURL(string ssURL)
{
try
{
if (string.IsNullOrWhiteSpace(ssURL))
return false;
var servers = Server.GetServers(ssURL);
if (servers == null || servers.Count == 0)
return false;
foreach (var server in servers)
{
_config.configs.Add(server);
if (server.warnLegacyUrl)
MessageBox.Show(I18N.GetString("Warning: importing {0} from a legacy ss:// link. Support for legacy ss:// links will be dropped in version 5. Make sure to update your ss:// links.", server.ToString()));
}
_config.index = _config.configs.Count - 1;
SaveConfig(_config);
return true;
}
catch (Exception e)
{
logger.LogUsefulException(e);
return false;
}
}
public string GetServerURLForCurrentServer()
{
return GetCurrentServer().GetURL(_config.generateLegacyUrl);
}
#endregion
#region Misc
public void ToggleVerboseLogging(bool enabled)
{
_config.isVerboseLogging = enabled;
SaveConfig(_config);
NLogConfig.LoadConfiguration(); // reload nlog
VerboseLoggingStatusChanged?.Invoke(this, new EventArgs());
}
public void ToggleCheckingUpdate(bool enabled)
{
_config.autoCheckUpdate = enabled;
Configuration.Save(_config);
ConfigChanged?.Invoke(this, new EventArgs());
}
public void ToggleCheckingPreRelease(bool enabled)
{
_config.checkPreRelease = enabled;
Configuration.Save(_config);
ConfigChanged?.Invoke(this, new EventArgs());
}
public void SaveSkippedUpdateVerion(string version)
{
_config.skippedUpdateVersion = version;
Configuration.Save(_config);
}
public void SaveLogViewerConfig(LogViewerConfig newConfig)
{
_config.logViewer = newConfig;
newConfig.SaveSize();
Configuration.Save(_config);
ConfigChanged?.Invoke(this, new EventArgs());
}
public void SaveHotkeyConfig(HotkeyConfig newConfig)
{
_config.hotkey = newConfig;
SaveConfig(_config);
ConfigChanged?.Invoke(this, new EventArgs());
}
#endregion
#region Strategy
public void SelectStrategy(string strategyID)
{
_config.index = -1;
_config.strategy = strategyID;
SaveConfig(_config);
}
public IList GetStrategies()
{
return _strategyManager.GetStrategies();
}
public IStrategy GetCurrentStrategy()
{
foreach (var strategy in _strategyManager.GetStrategies())
{
if (strategy.ID == _config.strategy)
{
return strategy;
}
}
return null;
}
public void UpdateInboundCounter(object sender, SSTransmitEventArgs args)
{
GetCurrentStrategy()?.UpdateLastRead(args.server);
Interlocked.Add(ref _inboundCounter, args.length);
}
public void UpdateOutboundCounter(object sender, SSTransmitEventArgs args)
{
GetCurrentStrategy()?.UpdateLastWrite(args.server);
Interlocked.Add(ref _outboundCounter, args.length);
}
#endregion
#region SIP003
private void StartPlugin()
{
var server = _config.GetCurrentServer();
GetPluginLocalEndPointIfConfigured(server);
}
private void StopPlugins()
{
foreach (var serverAndPlugin in _pluginsByServer)
{
serverAndPlugin.Value?.Dispose();
}
_pluginsByServer.Clear();
}
public EndPoint GetPluginLocalEndPointIfConfigured(Server server)
{
var plugin = _pluginsByServer.GetOrAdd(
server,
x => Sip003Plugin.CreateIfConfigured(x, _config.showPluginOutput));
if (plugin == null)
{
return null;
}
try
{
if (plugin.StartIfNeeded())
{
logger.Info(
$"Started SIP003 plugin for {server.Identifier()} on {plugin.LocalEndPoint} - PID: {plugin.ProcessId}");
}
}
catch (Exception ex)
{
logger.Error("Failed to start SIP003 plugin: " + ex.Message);
throw;
}
return plugin.LocalEndPoint;
}
public void ToggleShowPluginOutput(bool enabled)
{
_config.showPluginOutput = enabled;
SaveConfig(_config);
ShowPluginOutputChanged?.Invoke(this, new EventArgs());
}
#endregion
#region Traffic Statistics
private void StartTrafficStatistics(int queueMaxSize)
{
trafficPerSecondQueue = new Queue();
for (int i = 0; i < queueMaxSize; i++)
{
trafficPerSecondQueue.Enqueue(new TrafficPerSecond());
}
_trafficThread = new Thread(new ThreadStart(() => TrafficStatistics(queueMaxSize)))
{
IsBackground = true
};
_trafficThread.Start();
}
private void TrafficStatistics(int queueMaxSize)
{
TrafficPerSecond previous, current;
while (true)
{
previous = trafficPerSecondQueue.Last();
current = new TrafficPerSecond
{
inboundCounter = InboundCounter,
outboundCounter = OutboundCounter
};
current.inboundIncreasement = current.inboundCounter - previous.inboundCounter;
current.outboundIncreasement = current.outboundCounter - previous.outboundCounter;
trafficPerSecondQueue.Enqueue(current);
if (trafficPerSecondQueue.Count > queueMaxSize)
trafficPerSecondQueue.Dequeue();
TrafficChanged?.Invoke(this, new EventArgs());
Thread.Sleep(1000);
}
}
#endregion
#region SIP008
public async Task UpdateOnlineConfigInternal(string url)
{
var onlineServer = await OnlineConfigResolver.GetOnline(url);
_config.configs = Configuration.SortByOnlineConfig(
_config.configs
.Where(c => c.group != url)
.Concat(onlineServer)
);
logger.Info($"updated {onlineServer.Count} server from {url}");
return onlineServer.Count;
}
public async Task UpdateOnlineConfig(string url)
{
var selected = GetCurrentServer();
try
{
int count = await UpdateOnlineConfigInternal(url);
}
catch (Exception e)
{
logger.LogUsefulException(e);
return false;
}
_config.index = _config.configs.IndexOf(selected);
SaveConfig(_config);
return true;
}
public async Task> UpdateAllOnlineConfig()
{
var selected = GetCurrentServer();
var failedUrls = new List();
foreach (var url in _config.onlineConfigSource)
{
try
{
await UpdateOnlineConfigInternal(url);
}
catch (Exception e)
{
logger.LogUsefulException(e);
failedUrls.Add(url);
}
}
_config.index = _config.configs.IndexOf(selected);
SaveConfig(_config);
return failedUrls;
}
public void SaveOnlineConfigSource(List sources)
{
_config.onlineConfigSource = sources;
SaveConfig(_config);
}
public void RemoveOnlineConfig(string url)
{
_config.onlineConfigSource.RemoveAll(v => v == url);
_config.configs = Configuration.SortByOnlineConfig(
_config.configs.Where(c => c.group != url)
);
SaveConfig(_config);
}
#endregion
}
}
================================================
FILE: shadowsocks-csharp/Controller/Strategy/BalancingStrategy.cs
================================================
using Shadowsocks.Controller;
using Shadowsocks.Model;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace Shadowsocks.Controller.Strategy
{
class BalancingStrategy : IStrategy
{
ShadowsocksController _controller;
Random _random;
public BalancingStrategy(ShadowsocksController controller)
{
_controller = controller;
_random = new Random();
}
public string Name
{
get { return I18N.GetString("Load Balance"); }
}
public string ID
{
get { return "com.shadowsocks.strategy.balancing"; }
}
public void ReloadServers()
{
// do nothing
}
public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)
{
var configs = _controller.GetCurrentConfiguration().configs;
int index;
if (type == IStrategyCallerType.TCP)
{
index = _random.Next();
}
else
{
index = localIPEndPoint.GetHashCode();
}
return configs[index % configs.Count];
}
public void UpdateLatency(Model.Server server, TimeSpan latency)
{
// do nothing
}
public void UpdateLastRead(Model.Server server)
{
// do nothing
}
public void UpdateLastWrite(Model.Server server)
{
// do nothing
}
public void SetFailure(Model.Server server)
{
// do nothing
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Strategy/HighAvailabilityStrategy.cs
================================================
using NLog;
using Shadowsocks.Model;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace Shadowsocks.Controller.Strategy
{
class HighAvailabilityStrategy : IStrategy
{
private static Logger logger = LogManager.GetCurrentClassLogger();
protected ServerStatus _currentServer;
protected Dictionary _serverStatus;
ShadowsocksController _controller;
Random _random;
public class ServerStatus
{
// time interval between SYN and SYN+ACK
public TimeSpan latency;
public DateTime lastTimeDetectLatency;
// last time anything received
public DateTime lastRead;
// last time anything sent
public DateTime lastWrite;
// connection refused or closed before anything received
public DateTime lastFailure;
public Server server;
public double score;
}
public HighAvailabilityStrategy(ShadowsocksController controller)
{
_controller = controller;
_random = new Random();
_serverStatus = new Dictionary();
}
public string Name
{
get { return I18N.GetString("High Availability"); }
}
public string ID
{
get { return "com.shadowsocks.strategy.ha"; }
}
public void ReloadServers()
{
// make a copy to avoid locking
var newServerStatus = new Dictionary(_serverStatus);
foreach (var server in _controller.GetCurrentConfiguration().configs)
{
if (!newServerStatus.ContainsKey(server))
{
var status = new ServerStatus();
status.server = server;
status.lastFailure = DateTime.MinValue;
status.lastRead = DateTime.Now;
status.lastWrite = DateTime.Now;
status.latency = new TimeSpan(0, 0, 0, 0, 10);
status.lastTimeDetectLatency = DateTime.Now;
newServerStatus[server] = status;
}
else
{
// update settings for existing server
newServerStatus[server].server = server;
}
}
_serverStatus = newServerStatus;
ChooseNewServer();
}
public Server GetAServer(IStrategyCallerType type, System.Net.IPEndPoint localIPEndPoint, EndPoint destEndPoint)
{
if (type == IStrategyCallerType.TCP)
{
ChooseNewServer();
}
if (_currentServer == null)
{
return null;
}
return _currentServer.server;
}
/**
* once failed, try after 5 min
* and (last write - last read) < 5s
* and (now - last read) < 5s // means not stuck
* and latency < 200ms, try after 30s
*/
public void ChooseNewServer()
{
ServerStatus oldServer = _currentServer;
List servers = new List(_serverStatus.Values);
DateTime now = DateTime.Now;
foreach (var status in servers)
{
// all of failure, latency, (lastread - lastwrite) normalized to 1000, then
// 100 * failure - 2 * latency - 0.5 * (lastread - lastwrite)
status.score =
100 * 1000 * Math.Min(5 * 60, (now - status.lastFailure).TotalSeconds)
-2 * 5 * (Math.Min(2000, status.latency.TotalMilliseconds) / (1 + (now - status.lastTimeDetectLatency).TotalSeconds / 30 / 10) +
-0.5 * 200 * Math.Min(5, (status.lastRead - status.lastWrite).TotalSeconds));
logger.Debug(String.Format("server: {0} latency:{1} score: {2}", status.server.ToString(), status.latency, status.score));
}
ServerStatus max = null;
foreach (var status in servers)
{
if (max == null)
{
max = status;
}
else
{
if (status.score >= max.score)
{
max = status;
}
}
}
if (max != null)
{
if (_currentServer == null || max.score - _currentServer.score > 200)
{
_currentServer = max;
logger.Info($"HA switching to server: {_currentServer.server.ToString()}");
}
}
}
public void UpdateLatency(Model.Server server, TimeSpan latency)
{
logger.Debug($"latency: {server.ToString()} {latency}");
ServerStatus status;
if (_serverStatus.TryGetValue(server, out status))
{
status.latency = latency;
status.lastTimeDetectLatency = DateTime.Now;
}
}
public void UpdateLastRead(Model.Server server)
{
logger.Debug($"last read: {server.ToString()}");
ServerStatus status;
if (_serverStatus.TryGetValue(server, out status))
{
status.lastRead = DateTime.Now;
}
}
public void UpdateLastWrite(Model.Server server)
{
logger.Debug($"last write: {server.ToString()}");
ServerStatus status;
if (_serverStatus.TryGetValue(server, out status))
{
status.lastWrite = DateTime.Now;
}
}
public void SetFailure(Model.Server server)
{
logger.Debug($"failure: {server.ToString()}");
ServerStatus status;
if (_serverStatus.TryGetValue(server, out status))
{
status.lastFailure = DateTime.Now;
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/Strategy/IStrategy.cs
================================================
using Shadowsocks.Model;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace Shadowsocks.Controller.Strategy
{
public enum IStrategyCallerType
{
TCP,
UDP
}
/*
* IStrategy
*
* Subclasses must be thread-safe
*/
public interface IStrategy
{
string Name { get; }
string ID { get; }
/*
* Called when servers need to be reloaded, i.e. new configuration saved
*/
void ReloadServers();
/*
* Get a new server to use in TCPRelay or UDPRelay
*/
Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint);
/*
* TCPRelay will call this when latency of a server detected
*/
void UpdateLatency(Server server, TimeSpan latency);
/*
* TCPRelay will call this when reading from a server
*/
void UpdateLastRead(Server server);
/*
* TCPRelay will call this when writing to a server
*/
void UpdateLastWrite(Server server);
/*
* TCPRelay will call this when fatal failure detected
*/
void SetFailure(Server server);
}
}
================================================
FILE: shadowsocks-csharp/Controller/Strategy/StrategyManager.cs
================================================
using Shadowsocks.Controller;
using System;
using System.Collections.Generic;
using System.Text;
namespace Shadowsocks.Controller.Strategy
{
class StrategyManager
{
List _strategies;
public StrategyManager(ShadowsocksController controller)
{
_strategies = new List();
_strategies.Add(new BalancingStrategy(controller));
_strategies.Add(new HighAvailabilityStrategy(controller));
// TODO: load DLL plugins
}
public IList GetStrategies()
{
return _strategies;
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/System/AutoStartup.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using NLog;
using Shadowsocks.Util;
namespace Shadowsocks.Controller
{
static class AutoStartup
{
private static Logger logger = LogManager.GetCurrentClassLogger();
// Don't use Application.ExecutablePath
// see https://stackoverflow.com/questions/12945805/odd-c-sharp-path-issue
private static string Key = "Shadowsocks_" + Program.ExecutablePath.GetHashCode();
public static bool Set(bool enabled)
{
RegistryKey runKey = null;
try
{
runKey = Utils.OpenRegKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
if (runKey == null)
{
logger.Error(@"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Run");
return false;
}
if (enabled)
{
runKey.SetValue(Key, Program.ExecutablePath);
}
else
{
runKey.DeleteValue(Key);
}
// When autostartup setting change, change RegisterForRestart state to avoid start 2 times
RegisterForRestart(!enabled);
return true;
}
catch (Exception e)
{
logger.LogUsefulException(e);
return false;
}
finally
{
if (runKey != null)
{
try
{
runKey.Close();
runKey.Dispose();
}
catch (Exception e)
{ logger.LogUsefulException(e); }
}
}
}
public static bool Check()
{
RegistryKey runKey = null;
try
{
runKey = Utils.OpenRegKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
if (runKey == null)
{
logger.Error(@"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Run");
return false;
}
var check = false;
foreach (var valueName in runKey.GetValueNames())
{
if (valueName.Equals(Key, StringComparison.InvariantCultureIgnoreCase))
{
check = true;
continue;
}
// Remove other startup keys with the same executable path. fixes #3011 and also assures compatibility with older versions
if (Program.ExecutablePath.Equals(runKey.GetValue(valueName).ToString(), StringComparison.InvariantCultureIgnoreCase))
{
runKey.DeleteValue(valueName);
runKey.SetValue(Key, Program.ExecutablePath);
check = true;
}
}
return check;
}
catch (Exception e)
{
logger.LogUsefulException(e);
return false;
}
finally
{
if (runKey != null)
{
try
{
runKey.Close();
runKey.Dispose();
}
catch (Exception e)
{ logger.LogUsefulException(e); }
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
static extern int RegisterApplicationRestart([MarshalAs(UnmanagedType.LPWStr)] string commandLineArgs, int Flags);
[DllImport("kernel32.dll", SetLastError = true)]
static extern int UnregisterApplicationRestart();
[Flags]
enum ApplicationRestartFlags
{
RESTART_ALWAYS = 0,
RESTART_NO_CRASH = 1,
RESTART_NO_HANG = 2,
RESTART_NO_PATCH = 4,
RESTART_NO_REBOOT = 8,
}
// register restart after system reboot/update
public static void RegisterForRestart(bool register)
{
// requested register and not autostartup
if (register && !Check())
{
// escape command line parameter
string[] args = new List(Program.Args)
.Select(p => p.Replace("\"", "\\\"")) // escape " to \"
.Select(p => p.IndexOf(" ") >= 0 ? "\"" + p + "\"" : p) // encapsule with "
.ToArray();
string cmdline = string.Join(" ", args);
// first parameter is process command line parameter
// needn't include the name of the executable in the command line
RegisterApplicationRestart(cmdline, (int)(ApplicationRestartFlags.RESTART_NO_CRASH | ApplicationRestartFlags.RESTART_NO_HANG));
logger.Debug("Register restart after system reboot, command line:" + cmdline);
}
// requested unregister, which has no side effect
else if (!register)
{
UnregisterApplicationRestart();
logger.Debug("Unregister restart after system reboot");
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/System/Hotkeys/HotkeyCallbacks.cs
================================================
using System;
using System.Reflection;
namespace Shadowsocks.Controller.Hotkeys
{
public class HotkeyCallbacks
{
public static void InitInstance(ShadowsocksController controller)
{
if (Instance != null)
{
return;
}
Instance = new HotkeyCallbacks(controller);
}
///
/// Create hotkey callback handler delegate based on callback name
///
///
///
public static Delegate GetCallback(string methodname)
{
if (string.IsNullOrEmpty(methodname)) throw new ArgumentException(nameof(methodname));
MethodInfo dynMethod = typeof(HotkeyCallbacks).GetMethod(methodname,
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase);
return dynMethod == null ? null : Delegate.CreateDelegate(typeof(HotKeys.HotKeyCallBackHandler), Instance, dynMethod);
}
#region Singleton
private static HotkeyCallbacks Instance { get; set; }
private readonly ShadowsocksController _controller;
private HotkeyCallbacks(ShadowsocksController controller)
{
_controller = controller;
}
#endregion
#region Callbacks
private void SwitchSystemProxyCallback()
{
bool enabled = _controller.GetCurrentConfiguration().enabled;
_controller.ToggleEnable(!enabled);
}
private void SwitchSystemProxyModeCallback()
{
var config = _controller.GetCurrentConfiguration();
if (config.enabled)
_controller.ToggleGlobal(!config.global);
}
private void SwitchAllowLanCallback()
{
var status = _controller.GetCurrentConfiguration().shareOverLan;
_controller.ToggleShareOverLAN(!status);
}
private void ShowLogsCallback()
{
Program.MenuController.ShowLogForm_HotKey();
}
private void ServerMoveUpCallback()
{
int currIndex;
int serverCount;
GetCurrServerInfo(out currIndex, out serverCount);
if (currIndex - 1 < 0)
{
// revert to last server
currIndex = serverCount - 1;
}
else
{
currIndex -= 1;
}
_controller.SelectServerIndex(currIndex);
}
private void ServerMoveDownCallback()
{
int currIndex;
int serverCount;
GetCurrServerInfo(out currIndex, out serverCount);
if (currIndex + 1 == serverCount)
{
// revert to first server
currIndex = 0;
}
else
{
currIndex += 1;
}
_controller.SelectServerIndex(currIndex);
}
private void GetCurrServerInfo(out int currIndex, out int serverCount)
{
var currConfig = _controller.GetCurrentConfiguration();
currIndex = currConfig.index;
serverCount = currConfig.configs.Count;
}
#endregion
}
}
================================================
FILE: shadowsocks-csharp/Controller/System/Hotkeys/Hotkeys.cs
================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Input;
using GlobalHotKey;
namespace Shadowsocks.Controller.Hotkeys
{
public static class HotKeys
{
private static HotKeyManager _hotKeyManager;
public delegate void HotKeyCallBackHandler();
// map key and corresponding handler function
private static Dictionary _keymap = new Dictionary();
public static void Init(ShadowsocksController controller)
{
_hotKeyManager = new HotKeyManager();
_hotKeyManager.KeyPressed += HotKeyManagerPressed;
HotkeyCallbacks.InitInstance(controller);
}
public static void Destroy()
{
_hotKeyManager.KeyPressed -= HotKeyManagerPressed;
_hotKeyManager.Dispose();
}
private static void HotKeyManagerPressed(object sender, KeyPressedEventArgs e)
{
var hotkey = e.HotKey;
HotKeyCallBackHandler callback;
if (_keymap.TryGetValue(hotkey, out callback))
callback();
}
public static bool RegHotkey(HotKey hotkey, HotKeyCallBackHandler callback)
{
UnregExistingHotkey(callback);
return Register(hotkey, callback);
}
public static bool UnregExistingHotkey(HotKeys.HotKeyCallBackHandler cb)
{
HotKey existingHotKey;
if (IsCallbackExists(cb, out existingHotKey))
{
// unregister existing one
Unregister(existingHotKey);
return true;
}
else
{
return false;
}
}
public static bool IsHotkeyExists( HotKey hotKey )
{
if (hotKey == null) throw new ArgumentNullException(nameof(hotKey));
return _keymap.Any( v => v.Key.Equals( hotKey ) );
}
public static bool IsCallbackExists( HotKeyCallBackHandler cb, out HotKey hotkey)
{
if (cb == null) throw new ArgumentNullException(nameof(cb));
if (_keymap.Any(v => v.Value == cb))
{
hotkey = _keymap.First(v => v.Value == cb).Key;
return true;
}
else
{
hotkey = null;
return false;
}
}
#region Converters
public static string HotKey2Str( HotKey key )
{
if (key == null) throw new ArgumentNullException(nameof(key));
return HotKey2Str( key.Key, key.Modifiers );
}
public static string HotKey2Str( Key key, ModifierKeys modifier )
{
if (!Enum.IsDefined(typeof(Key), key))
throw new InvalidEnumArgumentException(nameof(key), (int) key, typeof(Key));
try
{
ModifierKeysConverter mkc = new ModifierKeysConverter();
var keyStr = Enum.GetName(typeof(Key), key);
var modifierStr = mkc.ConvertToInvariantString(modifier);
return $"{modifierStr}+{keyStr}";
}
catch (NotSupportedException)
{
// converter exception
return null;
}
}
public static HotKey Str2HotKey(string s)
{
try
{
if (string.IsNullOrEmpty(s)) return null;
int offset = s.LastIndexOf("+", StringComparison.OrdinalIgnoreCase);
if (offset <= 0) return null;
string modifierStr = s.Substring(0, offset).Trim();
string keyStr = s.Substring(offset + 1).Trim();
KeyConverter kc = new KeyConverter();
ModifierKeysConverter mkc = new ModifierKeysConverter();
Key key = (Key) kc.ConvertFrom(keyStr.ToUpper());
ModifierKeys modifier = (ModifierKeys) mkc.ConvertFrom(modifierStr.ToUpper());
return new HotKey(key, modifier);
}
catch (NotSupportedException)
{
// converter exception
return null;
}
catch (NullReferenceException)
{
return null;
}
}
#endregion
private static bool Register(HotKey key, HotKeyCallBackHandler callBack)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (callBack == null)
throw new ArgumentNullException(nameof(callBack));
try
{
_hotKeyManager.Register(key);
_keymap[key] = callBack;
return true;
}
catch (ArgumentException)
{
// already called this method with the specific hotkey
// return success silently
return true;
}
catch (Win32Exception)
{
// this hotkey already registered by other programs
// notify user to change key
return false;
}
}
private static void Unregister(HotKey key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
_hotKeyManager.Unregister(key);
if(_keymap.ContainsKey(key))
_keymap.Remove(key);
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/System/ProtocolHandler.cs
================================================
using Microsoft.Win32;
using NLog;
using Shadowsocks.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shadowsocks.Controller
{
static class ProtocolHandler
{
const string ssURLRegKey = @"SOFTWARE\Classes\ss";
private static Logger logger = LogManager.GetCurrentClassLogger();
public static bool Set(bool enabled)
{
RegistryKey ssURLAssociation = null;
try
{
ssURLAssociation = Registry.CurrentUser.CreateSubKey(ssURLRegKey, RegistryKeyPermissionCheck.ReadWriteSubTree);
if (ssURLAssociation == null)
{
logger.Error(@"Failed to create HKCU\SOFTWARE\Classes\ss to register ss:// association.");
return false;
}
if (enabled)
{
ssURLAssociation.SetValue("", "URL:Shadowsocks");
ssURLAssociation.SetValue("URL Protocol", "");
var shellOpen = ssURLAssociation.CreateSubKey("shell").CreateSubKey("open").CreateSubKey("command");
shellOpen.SetValue("", $"{Program.ExecutablePath} --open-url %1");
logger.Info(@"Successfully added ss:// association.");
}
else
{
Registry.CurrentUser.DeleteSubKeyTree(ssURLRegKey);
logger.Info(@"Successfully removed ss:// association.");
}
return true;
}
catch (Exception e)
{
logger.LogUsefulException(e);
return false;
}
finally
{
if (ssURLAssociation != null)
{
try
{
ssURLAssociation.Close();
ssURLAssociation.Dispose();
}
catch (Exception e)
{ logger.LogUsefulException(e); }
}
}
}
public static bool Check()
{
RegistryKey ssURLAssociation = null;
try
{
ssURLAssociation = Registry.CurrentUser.OpenSubKey(ssURLRegKey, true);
if (ssURLAssociation == null)
{
//logger.Info(@"ss:// links not associated.");
return false;
}
var shellOpen = ssURLAssociation.OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command");
return (string)shellOpen.GetValue("") == $"{Program.ExecutablePath} --open-url %1";
}
catch (Exception e)
{
logger.LogUsefulException(e);
return false;
}
finally
{
if (ssURLAssociation != null)
{
try
{
ssURLAssociation.Close();
ssURLAssociation.Dispose();
}
catch (Exception e)
{ logger.LogUsefulException(e); }
}
}
}
}
}
================================================
FILE: shadowsocks-csharp/Controller/System/SystemProxy.cs
================================================
using System;
using System.Windows.Forms;
using NLog;
using Shadowsocks.Model;
using Shadowsocks.Util.SystemProxy;
namespace Shadowsocks.Controller
{
public static class SystemProxy
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private static string GetTimestamp(DateTime value)
{
return value.ToString("yyyyMMddHHmmssfff");
}
public static void Update(Configuration config, bool forceDisable, PACServer pacSrv, bool noRetry = false)
{
bool global = config.global;
bool enabled = config.enabled;
if (forceDisable)
{
enabled = false;
}
try
{
if (enabled)
{
if (global)
{
Sysproxy.SetIEProxy(true, true, "localhost:" + config.localPort.ToString(), null);
}
else
{
string pacUrl;
if (config.useOnlinePac && !string.IsNullOrEmpty(config.pacUrl))
{
pacUrl = config.pacUrl;
}
else
{
pacUrl = pacSrv.PacUrl;
}
Sysproxy.SetIEProxy(true, false, null, pacUrl);
}
}
else
{
Sysproxy.SetIEProxy(false, false, null, null);
}
}
catch (ProxyException ex)
{
logger.LogUsefulException(ex);
if (ex.Type != ProxyExceptionType.Unspecific && !noRetry)
{
var ret = MessageBox.Show(I18N.GetString("Error occured when process proxy setting, do you want reset current setting and retry?"), I18N.GetString("Shadowsocks"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (ret == DialogResult.Yes)
{
Sysproxy.ResetIEProxy();
Update(config, forceDisable, pacSrv, true);
}
}
else
{
MessageBox.Show(I18N.GetString("Unrecoverable proxy setting error occured, see log for detail"), I18N.GetString("Shadowsocks"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
================================================
FILE: shadowsocks-csharp/Data/NLog.config
================================================
================================================
FILE: shadowsocks-csharp/Data/abp.js
================================================
/* eslint-disable */
// Was generated by gfwlist2pac in precise mode
// https://github.com/clowwindy/gfwlist2pac
// 2019-10-06: More 'javascript' way to interaction with main program
// 2019-02-08: Updated to support shadowsocks-windows user rules.
var proxy = __PROXY__;
var userrules = [];
var rules = [];
// convert to abp grammar
var re = /^(@@)?\|\|.*?[^\^]$/;
for (var i = 0; i < __RULES__.length; i++) {
var s = __RULES__[i];
if (s.match(re)) s += "^";
rules.push(s);
}
for (var i = 0; i < __USERRULES__.length; i++) {
var s = __USERRULES__[i];
if (s.match(re)) s += "^";
userrules.push(s);
}
/*
* This file is part of Adblock Plus ,
* Copyright (C) 2006-2014 Eyeo GmbH
*
* Adblock Plus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* Adblock Plus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Adblock Plus. If not, see .
*/
function createDict()
{
var result = {};
result.__proto__ = null;
return result;
}
function getOwnPropertyDescriptor(obj, key)
{
if (obj.hasOwnProperty(key))
{
return obj[key];
}
return null;
}
function extend(subclass, superclass, definition)
{
if (Object.__proto__)
{
definition.__proto__ = superclass.prototype;
subclass.prototype = definition;
}
else
{
var tmpclass = function(){}, ret;
tmpclass.prototype = superclass.prototype;
subclass.prototype = new tmpclass();
subclass.prototype.constructor = superclass;
for (var i in definition)
{
if (definition.hasOwnProperty(i))
{
subclass.prototype[i] = definition[i];
}
}
}
}
function Filter(text)
{
this.text = text;
this.subscriptions = [];
}
Filter.prototype = {
text: null,
subscriptions: null,
toString: function()
{
return this.text;
}
};
Filter.knownFilters = createDict();
Filter.elemhideRegExp = /^([^\/\*\|\@"!]*?)#(\@)?(?:([\w\-]+|\*)((?:\([\w\-]+(?:[$^*]?=[^\(\)"]*)?\))*)|#([^{}]+))$/;
Filter.regexpRegExp = /^(@@)?\/.*\/(?:\$~?[\w\-]+(?:=[^,\s]+)?(?:,~?[\w\-]+(?:=[^,\s]+)?)*)?$/;
Filter.optionsRegExp = /\$(~?[\w\-]+(?:=[^,\s]+)?(?:,~?[\w\-]+(?:=[^,\s]+)?)*)$/;
Filter.fromText = function(text)
{
if (text in Filter.knownFilters)
{
return Filter.knownFilters[text];
}
var ret;
if (text.charAt(0) == "!")
{
ret = new CommentFilter(text);
}
else
{
ret = RegExpFilter.fromText(text);
}
Filter.knownFilters[ret.text] = ret;
return ret;
};
function InvalidFilter(text, reason)
{
Filter.call(this, text);
this.reason = reason;
}
extend(InvalidFilter, Filter, {
reason: null
});
function CommentFilter(text)
{
Filter.call(this, text);
}
extend(CommentFilter, Filter, {
});
function ActiveFilter(text, domains)
{
Filter.call(this, text);
this.domainSource = domains;
}
extend(ActiveFilter, Filter, {
domainSource: null,
domainSeparator: null,
ignoreTrailingDot: true,
domainSourceIsUpperCase: false,
getDomains: function()
{
var prop = getOwnPropertyDescriptor(this, "domains");
if (prop)
{
return prop;
}
var domains = null;
if (this.domainSource)
{
var source = this.domainSource;
if (!this.domainSourceIsUpperCase)
{
source = source.toUpperCase();
}
var list = source.split(this.domainSeparator);
if (list.length == 1 && (list[0]).charAt(0) != "~")
{
domains = createDict();
domains[""] = false;
if (this.ignoreTrailingDot)
{
list[0] = list[0].replace(/\.+$/, "");
}
domains[list[0]] = true;
}
else
{
var hasIncludes = false;
for (var i = 0; i < list.length; i++)
{
var domain = list[i];
if (this.ignoreTrailingDot)
{
domain = domain.replace(/\.+$/, "");
}
if (domain == "")
{
continue;
}
var include;
if (domain.charAt(0) == "~")
{
include = false;
domain = domain.substr(1);
}
else
{
include = true;
hasIncludes = true;
}
if (!domains)
{
domains = createDict();
}
domains[domain] = include;
}
domains[""] = !hasIncludes;
}
this.domainSource = null;
}
return this.domains;
},
sitekeys: null,
isActiveOnDomain: function(docDomain, sitekey)
{
if (this.getSitekeys() && (!sitekey || this.getSitekeys().indexOf(sitekey.toUpperCase()) < 0))
{
return false;
}
if (!this.getDomains())
{
return true;
}
if (!docDomain)
{
return this.getDomains()[""];
}
if (this.ignoreTrailingDot)
{
docDomain = docDomain.replace(/\.+$/, "");
}
docDomain = docDomain.toUpperCase();
while (true)
{
if (docDomain in this.getDomains())
{
return this.domains[docDomain];
}
var nextDot = docDomain.indexOf(".");
if (nextDot < 0)
{
break;
}
docDomain = docDomain.substr(nextDot + 1);
}
return this.domains[""];
},
isActiveOnlyOnDomain: function(docDomain)
{
if (!docDomain || !this.getDomains() || this.getDomains()[""])
{
return false;
}
if (this.ignoreTrailingDot)
{
docDomain = docDomain.replace(/\.+$/, "");
}
docDomain = docDomain.toUpperCase();
for (var domain in this.getDomains())
{
if (this.domains[domain] && domain != docDomain && (domain.length <= docDomain.length || domain.indexOf("." + docDomain) != domain.length - docDomain.length - 1))
{
return false;
}
}
return true;
}
});
function RegExpFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys)
{
ActiveFilter.call(this, text, domains, sitekeys);
if (contentType != null)
{
this.contentType = contentType;
}
if (matchCase)
{
this.matchCase = matchCase;
}
if (thirdParty != null)
{
this.thirdParty = thirdParty;
}
if (sitekeys != null)
{
this.sitekeySource = sitekeys;
}
if (regexpSource.length >= 2 && regexpSource.charAt(0) == "/" && regexpSource.charAt(regexpSource.length - 1) == "/")
{
var regexp = new RegExp(regexpSource.substr(1, regexpSource.length - 2), this.matchCase ? "" : "i");
this.regexp = regexp;
}
else
{
this.regexpSource = regexpSource;
}
}
extend(RegExpFilter, ActiveFilter, {
domainSourceIsUpperCase: true,
length: 1,
domainSeparator: "|",
regexpSource: null,
getRegexp: function()
{
var prop = getOwnPropertyDescriptor(this, "regexp");
if (prop)
{
return prop;
}
var source = this.regexpSource.replace(/\*+/g, "*").replace(/\^\|$/, "^").replace(/\W/g, "\\$&").replace(/\\\*/g, ".*").replace(/\\\^/g, "(?:[\\x00-\\x24\\x26-\\x2C\\x2F\\x3A-\\x40\\x5B-\\x5E\\x60\\x7B-\\x7F]|$)").replace(/^\\\|\\\|/, "^[\\w\\-]+:\\/+(?!\\/)(?:[^\\/]+\\.)?").replace(/^\\\|/, "^").replace(/\\\|$/, "$").replace(/^(\.\*)/, "").replace(/(\.\*)$/, "");
var regexp = new RegExp(source, this.matchCase ? "" : "i");
this.regexp = regexp;
return regexp;
},
contentType: 2147483647,
matchCase: false,
thirdParty: null,
sitekeySource: null,
getSitekeys: function()
{
var prop = getOwnPropertyDescriptor(this, "sitekeys");
if (prop)
{
return prop;
}
var sitekeys = null;
if (this.sitekeySource)
{
sitekeys = this.sitekeySource.split("|");
this.sitekeySource = null;
}
this.sitekeys = sitekeys;
return this.sitekeys;
},
matches: function(location, contentType, docDomain, thirdParty, sitekey)
{
if (this.getRegexp().test(location) && this.isActiveOnDomain(docDomain, sitekey))
{
return true;
}
return false;
}
});
RegExpFilter.prototype["0"] = "#this";
RegExpFilter.fromText = function(text)
{
var blocking = true;
var origText = text;
if (text.indexOf("@@") == 0)
{
blocking = false;
text = text.substr(2);
}
var contentType = null;
var matchCase = null;
var domains = null;
var sitekeys = null;
var thirdParty = null;
var collapse = null;
var options;
var match = text.indexOf("$") >= 0 ? Filter.optionsRegExp.exec(text) : null;
if (match)
{
options = match[1].toUpperCase().split(",");
text = match.input.substr(0, match.index);
for (var _loopIndex6 = 0; _loopIndex6 < options.length; ++_loopIndex6)
{
var option = options[_loopIndex6];
var value = null;
var separatorIndex = option.indexOf("=");
if (separatorIndex >= 0)
{
value = option.substr(separatorIndex + 1);
option = option.substr(0, separatorIndex);
}
option = option.replace(/-/, "_");
if (option in RegExpFilter.typeMap)
{
if (contentType == null)
{
contentType = 0;
}
contentType |= RegExpFilter.typeMap[option];
}
else if (option.charAt(0) == "~" && option.substr(1) in RegExpFilter.typeMap)
{
if (contentType == null)
{
contentType = RegExpFilter.prototype.contentType;
}
contentType &= ~RegExpFilter.typeMap[option.substr(1)];
}
else if (option == "MATCH_CASE")
{
matchCase = true;
}
else if (option == "~MATCH_CASE")
{
matchCase = false;
}
else if (option == "DOMAIN" && typeof value != "undefined")
{
domains = value;
}
else if (option == "THIRD_PARTY")
{
thirdParty = true;
}
else if (option == "~THIRD_PARTY")
{
thirdParty = false;
}
else if (option == "COLLAPSE")
{
collapse = true;
}
else if (option == "~COLLAPSE")
{
collapse = false;
}
else if (option == "SITEKEY" && typeof value != "undefined")
{
sitekeys = value;
}
else
{
return new InvalidFilter(origText, "Unknown option " + option.toLowerCase());
}
}
}
if (!blocking && (contentType == null || contentType & RegExpFilter.typeMap.DOCUMENT) && (!options || options.indexOf("DOCUMENT") < 0) && !/^\|?[\w\-]+:/.test(text))
{
if (contentType == null)
{
contentType = RegExpFilter.prototype.contentType;
}
contentType &= ~RegExpFilter.typeMap.DOCUMENT;
}
try
{
if (blocking)
{
return new BlockingFilter(origText, text, contentType, matchCase, domains, thirdParty, sitekeys, collapse);
}
else
{
return new WhitelistFilter(origText, text, contentType, matchCase, domains, thirdParty, sitekeys);
}
}
catch (e)
{
return new InvalidFilter(origText, e);
}
};
RegExpFilter.typeMap = {
OTHER: 1,
SCRIPT: 2,
IMAGE: 4,
STYLESHEET: 8,
OBJECT: 16,
SUBDOCUMENT: 32,
DOCUMENT: 64,
XBL: 1,
PING: 1,
XMLHTTPREQUEST: 2048,
OBJECT_SUBREQUEST: 4096,
DTD: 1,
MEDIA: 16384,
FONT: 32768,
BACKGROUND: 4,
POPUP: 268435456,
ELEMHIDE: 1073741824
};
RegExpFilter.prototype.contentType &= ~ (RegExpFilter.typeMap.ELEMHIDE | RegExpFilter.typeMap.POPUP);
function BlockingFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys, collapse)
{
RegExpFilter.call(this, text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys);
this.collapse = collapse;
}
extend(BlockingFilter, RegExpFilter, {
collapse: null
});
function WhitelistFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys)
{
RegExpFilter.call(this, text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys);
}
extend(WhitelistFilter, RegExpFilter, {
});
function Matcher()
{
this.clear();
}
Matcher.prototype = {
filterByKeyword: null,
keywordByFilter: null,
clear: function()
{
this.filterByKeyword = createDict();
this.keywordByFilter = createDict();
},
add: function(filter)
{
if (filter.text in this.keywordByFilter)
{
return;
}
var keyword = this.findKeyword(filter);
var oldEntry = this.filterByKeyword[keyword];
if (typeof oldEntry == "undefined")
{
this.filterByKeyword[keyword] = filter;
}
else if (oldEntry.length == 1)
{
this.filterByKeyword[keyword] = [oldEntry, filter];
}
else
{
oldEntry.push(filter);
}
this.keywordByFilter[filter.text] = keyword;
},
remove: function(filter)
{
if (!(filter.text in this.keywordByFilter))
{
return;
}
var keyword = this.keywordByFilter[filter.text];
var list = this.filterByKeyword[keyword];
if (list.length <= 1)
{
delete this.filterByKeyword[keyword];
}
else
{
var index = list.indexOf(filter);
if (index >= 0)
{
list.splice(index, 1);
if (list.length == 1)
{
this.filterByKeyword[keyword] = list[0];
}
}
}
delete this.keywordByFilter[filter.text];
},
findKeyword: function(filter)
{
var result = "";
var text = filter.text;
if (Filter.regexpRegExp.test(text))
{
return result;
}
var match = Filter.optionsRegExp.exec(text);
if (match)
{
text = match.input.substr(0, match.index);
}
if (text.substr(0, 2) == "@@")
{
text = text.substr(2);
}
var candidates = text.toLowerCase().match(/[^a-z0-9%*][a-z0-9%]{3,}(?=[^a-z0-9%*])/g);
if (!candidates)
{
return result;
}
var hash = this.filterByKeyword;
var resultCount = 16777215;
var resultLength = 0;
for (var i = 0, l = candidates.length; i < l; i++)
{
var candidate = candidates[i].substr(1);
var count = candidate in hash ? hash[candidate].length : 0;
if (count < resultCount || count == resultCount && candidate.length > resultLength)
{
result = candidate;
resultCount = count;
resultLength = candidate.length;
}
}
return result;
},
hasFilter: function(filter)
{
return filter.text in this.keywordByFilter;
},
getKeywordForFilter: function(filter)
{
if (filter.text in this.keywordByFilter)
{
return this.keywordByFilter[filter.text];
}
else
{
return null;
}
},
_checkEntryMatch: function(keyword, location, contentType, docDomain, thirdParty, sitekey)
{
var list = this.filterByKeyword[keyword];
for (var i = 0; i < list.length; i++)
{
var filter = list[i];
if (filter == "#this")
{
filter = list;
}
if (filter.matches(location, contentType, docDomain, thirdParty, sitekey))
{
return filter;
}
}
return null;
},
matchesAny: function(location, contentType, docDomain, thirdParty, sitekey)
{
var candidates = location.toLowerCase().match(/[a-z0-9%]{3,}/g);
if (candidates === null)
{
candidates = [];
}
candidates.push("");
for (var i = 0, l = candidates.length; i < l; i++)
{
var substr = candidates[i];
if (substr in this.filterByKeyword)
{
var result = this._checkEntryMatch(substr, location, contentType, docDomain, thirdParty, sitekey);
if (result)
{
return result;
}
}
}
return null;
}
};
function CombinedMatcher()
{
this.blacklist = new Matcher();
this.whitelist = new Matcher();
this.resultCache = createDict();
}
CombinedMatcher.maxCacheEntries = 1000;
CombinedMatcher.prototype = {
blacklist: null,
whitelist: null,
resultCache: null,
cacheEntries: 0,
clear: function()
{
this.blacklist.clear();
this.whitelist.clear();
this.resultCache = createDict();
this.cacheEntries = 0;
},
add: function(filter)
{
if (filter instanceof WhitelistFilter)
{
this.whitelist.add(filter);
}
else
{
this.blacklist.add(filter);
}
if (this.cacheEntries > 0)
{
this.resultCache = createDict();
this.cacheEntries = 0;
}
},
remove: function(filter)
{
if (filter instanceof WhitelistFilter)
{
this.whitelist.remove(filter);
}
else
{
this.blacklist.remove(filter);
}
if (this.cacheEntries > 0)
{
this.resultCache = createDict();
this.cacheEntries = 0;
}
},
findKeyword: function(filter)
{
if (filter instanceof WhitelistFilter)
{
return this.whitelist.findKeyword(filter);
}
else
{
return this.blacklist.findKeyword(filter);
}
},
hasFilter: function(filter)
{
if (filter instanceof WhitelistFilter)
{
return this.whitelist.hasFilter(filter);
}
else
{
return this.blacklist.hasFilter(filter);
}
},
getKeywordForFilter: function(filter)
{
if (filter instanceof WhitelistFilter)
{
return this.whitelist.getKeywordForFilter(filter);
}
else
{
return this.blacklist.getKeywordForFilter(filter);
}
},
isSlowFilter: function(filter)
{
var matcher = filter instanceof WhitelistFilter ? this.whitelist : this.blacklist;
if (matcher.hasFilter(filter))
{
return !matcher.getKeywordForFilter(filter);
}
else
{
return !matcher.findKeyword(filter);
}
},
matchesAnyInternal: function(location, contentType, docDomain, thirdParty, sitekey)
{
var candidates = location.toLowerCase().match(/[a-z0-9%]{3,}/g);
if (candidates === null)
{
candidates = [];
}
candidates.push("");
var blacklistHit = null;
for (var i = 0, l = candidates.length; i < l; i++)
{
var substr = candidates[i];
if (substr in this.whitelist.filterByKeyword)
{
var result = this.whitelist._checkEntryMatch(substr, location, contentType, docDomain, thirdParty, sitekey);
if (result)
{
return result;
}
}
if (substr in this.blacklist.filterByKeyword && blacklistHit === null)
{
blacklistHit = this.blacklist._checkEntryMatch(substr, location, contentType, docDomain, thirdParty, sitekey);
}
}
return blacklistHit;
},
matchesAny: function(location, docDomain)
{
var key = location + " " + docDomain + " ";
if (key in this.resultCache)
{
return this.resultCache[key];
}
var result = this.matchesAnyInternal(location, 0, docDomain, null, null);
if (this.cacheEntries >= CombinedMatcher.maxCacheEntries)
{
this.resultCache = createDict();
this.cacheEntries = 0;
}
this.resultCache[key] = result;
this.cacheEntries++;
return result;
}
};
var userrulesMatcher = new CombinedMatcher();
var defaultMatcher = new CombinedMatcher();
var direct = 'DIRECT;';
for (var i = 0; i < userrules.length; i++) {
userrulesMatcher.add(Filter.fromText(userrules[i]));
}
for (var i = 0; i < rules.length; i++) {
defaultMatcher.add(Filter.fromText(rules[i]));
}
// PAC has no v6 support, it sucks
var ip4Re = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/
var privateNet = [
["10.0.0.0", "255.0.0.0"],
["127.0.0.0", "255.0.0.0"],
["172.16.0.0", "255.240.0.0"],
["192.168.0.0", "255.255.0.0"],
]
function FindProxyForURL(url, host) {
if (host.match(ip4Re)) {
for (var i = 0; i < privateNet.length; i++) {
if (isInNet(host, privateNet[i][0], privateNet[i][1])) return direct;
}
}
if (userrulesMatcher.matchesAny(url, host) instanceof BlockingFilter) {
return proxy;
}
if (userrulesMatcher.matchesAny(url, host) instanceof WhitelistFilter) {
return direct;
}
// Hack for Geosite, it provides a whitelist...
if (defaultMatcher.matchesAny(url, host) instanceof WhitelistFilter) {
return direct;
}
if (defaultMatcher.matchesAny(url, host) instanceof BlockingFilter) {
return proxy;
}
return direct;
}
================================================
FILE: shadowsocks-csharp/Data/i18n.csv
================================================
en,ru-RU,zh-CN,zh-TW,ja,ko,fr
#Restart program to apply translation,,,,,,
#This is comment line,,,,,,
#Always keep language name at head of file,,,,,,
#Language name is output in log,,,,,,
"#You can find it by search ""Current language is:""",,,,,,
#Please use UTF-8 with BOM encoding so we can edit it in Excel,,,,,,
,,,,,,
Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks
,,,,,,
#Menu,,,,,,
,,,,,,
System Proxy,Системный прокси-сервер,系统代理,系統代理,システムプロキシ,시스템 프록시,Proxy système
Disable,Отключен,禁用,禁用,無効,비활성화,Désactiver
PAC,Сценарий настройки (PAC),PAC 模式,PAC 模式,PACモード,프록시 자동 구성 (PAC),PAC
Global,Для всей системы,全局模式,全局模式,グローバルプロキシ,전역,Global
Servers,Серверы,服务器,伺服器,サーバー,서버,Serveurs
Edit Servers...,Редактировать серверы…,编辑服务器...,編輯伺服器...,サーバーの編集...,서버 수정…,Éditer serveurs…
Online Config...,,在线配置...,線上配置...,,,
Start on Boot,Автозагрузка,开机启动,開機啟動,システム起動時に実行,시스템 시작 시에 시작하기,Démarrage automatique
Associate ss:// Links,Ассоциированный ss:// Ссылки,关联 ss:// 链接,關聯 ss:// 鏈接,ss:// リンクの関連付け,ss:// 링크 연결,
Forward Proxy...,Прямой прокси…,正向代理设置...,正向 Proxy 設定...,フォワードプロキシの設定...,포워드 프록시,Forward-proxy…
Allow other Devices to connect,Общий доступ к подключению,允许其他设备连入,允許其他裝置連入,他のデバイスからの接続を許可する,다른 기기에서 연결 허용,Autoriser d'autres appareils à se connecter
Local PAC,Локальный PAC,使用本地 PAC,使用本機 PAC,ローカル PAC,로컬 프록시 자동 구성,PAC local
Online PAC,Удаленный PAC,使用在线 PAC,使用線上 PAC,オンライン PAC,온라인 프록시 자동 구성,PAC en ligne
Edit Local PAC File...,Редактировать локальный PAC…,编辑本地 PAC 文件...,編輯本機 PAC 檔案...,ローカル PAC ファイルの編集...,로컬 프록시 자동 구성 파일 수정,Modifier le fichier PAC local ...
Update Local PAC from Geosite,Обновить локальный PAC из Geosite,从 Geosite 更新本地 PAC,從 Geosite 更新本機 PAC,Geosite からローカル PAC を更新,Geosite에서 로컬 프록시 자동 구성 파일 업데이트,Mettre à jour le PAC local à partir de Geosite
Edit User Rule for Geosite...,Редактировать свои правила для Geosite,编辑 Geosite 的用户规则...,編輯 Geosite 的使用者規則...,ユーザールールの編集...,Geosite 사용자 수정,Modifier la règle utilisateur pour Geosite ...
Secure Local PAC,Безопасный URL локального PAC,保护本地 PAC,安全本機 PAC,ローカル PAC を保護,로컬 프록시 자동 구성 파일 암호화,Sécuriser PAC local
Regenerate local PAC on version update,,版本更新后重新生成本地 PAC,版本更新後重新生成本地 PAC,,,
Copy Local PAC URL,Копировать URL локального PAC,复制本地 PAC 网址,複製本機 PAC 網址,ローカル PAC URL をコピー,로컬 프록시 자동 구성 파일 URL 복사,Copier l'URL du PAC local
Share Server Config...,Поделиться конфигурацией сервера…,分享服务器配置...,分享伺服器設定檔...,サーバーの設定を共有...,서버 설정 공유,Partager la configuration du serveur ...
Scan QRCode from Screen...,Сканировать QRCode с экрана…,扫描屏幕上的二维码...,掃描螢幕上的 QR 碼...,画面から QR コードをスキャン...,화면에서 QR코드 스캔,Scanner le QRCode à partir de l'écran ...
Import URL from Clipboard...,Импорт адреса из буфера обмена…,从剪贴板导入URL...,從剪貼簿匯入 URL...,クリップボードから URL をインポート...,클립보드에서 URL 가져오기…,Importer l'URL du presse-papiers ...
Availability Statistics,Статистика доступности,统计可用性,統計可用性,可用性の統計,가용성 통계,Statistiques de disponibilité
Show Logs...,Показать журнал…,显示日志...,顯示記錄檔...,ログの表示...,로그 보기…,Afficher les journaux ...
Verbose Logging,Подробный журнал,详细记录日志,詳細資訊記錄,詳細なログを記録,자세한 로깅 사용,Journalisation détaillée
Updates...,Обновления…,更新...,更新...,アップデート...,업데이트…,Mettre à jour…
Check for Updates...,Проверить обновления…,检查更新,檢查更新,アップデートを確認...,업데이트 확인하기…,Vérifier les mises à jour ...
Check for Updates at Startup,Проверять при запуске,启动时检查更新,啟動時檢查更新,起動時にアップデートを確認,시스템 시작 시 업데이트 확인하기,Vérifier les mises à jour au démarrage
Check Pre-release Version,Проверять предрелизные версии,检查测试版更新,檢查發行前版本更新,ベータ版のアップデートも確認,개발 버전 업데이트 확인하기,Vérifier la version préliminaire
Edit Hotkeys...,Горячие клавиши…,编辑快捷键...,編輯快速鍵...,ホットキーの編集...,단축키 수정…,Modifier les raccourcis clavier ...
About...,О программе…,关于...,關於...,Shadowsocks について...,정보…,A propos
Help,Помощь,帮助,說明,ヘルプ,도움말,Aide
Quit,Выход,退出,結束,終了,종료,Quitter
Edit Servers,Редактирование серверов,编辑服务器,編輯伺服器,サーバーの編集,서버 수정,Éditer serveurs
Load Balance,Балансировка нагрузки,负载均衡,負載平衡,サーバーロードバランス,로드밸런싱,Répartition de charge
High Availability,Высокая доступность,高可用,高可用性,高可用性,고가용성,Haute disponibilité
Show Plugin Output,События плагинов в журнале,显示插件输出,,プラグインの出力情報を表示,플러그인 출력 보이기,Afficher la sortie du plugin
Write translation template,Создать шаблон для перевода,写入翻译模板,,翻訳テンプレートファイルを書き込む,번역 템플릿 쓰기,Écrire un modèle de traduction
,,,,,,
# Config Form,,,,,,
,,,,,,
Statistics configuration,Настройки статистики,统计配置,,統計の設定,통계 설정,Configuration des statistiques
&Add,Добавить,添加(&A),新增 (&A),新規 (&A),추가 (&A),Ajouter
&Delete,Удалить,删除(&D),移除 (&D),削除 (&D),삭제 (&D),Supprimer
Dupli&cate,Дублир-ть,复制(&C),複製 (&C),コピー (&C),복제 (&C),Dupliquer
Server,Сервер,服务器,伺服器,サーバー,서버,Serveur
Server IP,IP-адрес,服务器地址,伺服器位址,サーバーアドレス,서버 IP,Serveur IP
Server Port,Порт,服务器端口,伺服器連接埠,サーバーポート,서버 포트,Port de serveur
Password,Пароль,密码,密碼,パスワード,비밀번호,Mot de passe
Show Password,Показать пароль,显示密码,顯示密碼,パスワードを表示する,비밀번호 보이기,Montrer le mot de passe
Encryption,Шифрование,加密,加密,暗号化,암호화,Chiffrement
Plugin Program,Плагин,插件程序,外掛程式,プラグインプログラム,플러그인 프로그램,Programme de plugin
Plugin Options,Опции плагина,插件选项,外掛程式選項,プラグインのオプション,플러그인 설정,Options de plugin
Need Plugin Argument,Требуются аргументы,需要命令行参数,,コマンドライン引数を有効にする,플러그인 인자가 필요함,Besoin d'un argument de plugin
Plugin Arguments,Аргументы,插件参数,外掛程式參數,プラグインの引数,플러그인 인자,Arguments du plugin
Proxy Port,Порт прокси,代理端口,Proxy 連接埠,プロキシポート,프록시 포트,Port proxy
Portable Mode,Переносимый режим,便携模式,便攜模式,ポータブルモード,포터블 모드,Mode portable
Restart required,Требуется перезапуск программы,需要重新启动SS,需要重新啟動SS,再起動が必要,재시작이 필요합니다,Redémarrage nécessaire
Remarks,Примечания,备注,註解,付記,알림,Remarques
Timeout(Sec),Таймаут(сек),超时(秒),逾時 (秒),タイムアウト (秒),시간 초과 (초),Délai d'attente(sec)
OK,ОК,确定,確定,OK,확인,OK
Cancel,Отмена,取消,取消,キャンセル,취소,Annuler
Apply,Применить,应用,應用,適用,적용,Appliquer
New server,Новый сервер,未配置的服务器,新伺服器,新規サーバー,새 서버,Nouveau serveur
Move &Up,Выше,上移(&U),上移 (&U),上に移動 (&U),위로 (&U),Monter
Move D&own,Ниже,下移(&O),下移 (&O),下に移動 (&O),아래로 (&O),Descendre
deprecated,Устаревшее,不推荐,不推薦,非推奨,더 이상 사용되지 않음,Obsolète
"Encryption method {0} not exist, will replace with {1}",,加密方法{0}不存在,将使用{1}代替,,暗号化方式{0}が存在しません,{1}に置換します,{0} 암호화 방식이 존재하지 않으므로 {1}로 대체될 것입니다.,"Méthode de chiffrement {0} n'existe pas, sera remplacée par {1}"
,,,,,,
# Log Form,,,,,,
,,,,,,
&File,Файл,文件(&F),檔案 (&F),ファイル (&F),파일 (&F),Fichier
&Open Location,Расположение файла,在资源管理器中打开(&O),在檔案總管中開啟 (&O),ファイルの場所を開く (&O),위치 열기 (&O),Ouvrier
E&xit,Выход,退出(&X),結束 (&X),終了 (&X),종료 (&X),Quitter
&View,Вид,视图(&V),檢視 (&V),表示 (&V),보기 (&V),Afficher
&Clear Logs,Очистить журнал,清空日志(&C),清除記錄檔 (&C),ログの削除 (&C),로그 초기화 (&C),Effacer les journaux
Change &Font,Шрифт…,设置字体(&F),變更字型 (&F),フォント (&F),글꼴 변경 (&F),Définir la police
&Wrap Text,Перенос строк,自动换行(&W),自動換行 (&W),右端で折り返す (&W),텍스트 감싸기 (&W),Retour à la ligne
&Top Most,Поверх всех окон,置顶(&T),置頂 (&T),常に最前面に表示 (&T),상단 우선 (Top Most) (&T),Metter en haut
&Show Toolbar,Панель инструментов,显示工具栏(&S),顯示工具列 (&S),ツールバーの表示 (&S),툴바 보여주기 (&S),Afficher la barre d'outils
Log Viewer,Просмотр журнала,日志查看器,記錄檔檢視器,ログビューア,로그 뷰어,Visionneuse de journaux
Inbound,Входящая,入站,輸入,受信,"인바운드 (Rx, 다운로드)",Entrant
Outbound,Исходящая,出站,輸出,送信,"아웃바운드 (Tx, 업로드)",Sortant
,,,,,,
# QRCode Form,,,,,,
,,,,,,
QRCode and URL,QRCode и URL,二维码与 URL,QR 碼與 URL,QR コードと URL,QR코드와 URL,QRCode et URL
,,,,,,
# PAC Url Form,,,,,,
,,,,,,
Edit Online PAC URL,Изменение URL удаленного PAC,编辑在线 PAC 网址,編輯線上 PAC 網址,オンライン PAC URL の編集,온라인 프록시 자동 구성 URL 수정,Modifier l'URL du PAC en ligne
Edit Online PAC URL...,Редактировать URL удаленного PAC…,编辑在线 PAC 网址...,編輯線上 PAC 網址...,オンライン PAC URL の編集...,온라인 프록시 자동 구성 URL 수정…,Modifier l'URL du PAC en ligne ...
Please input PAC Url,Введите URL адрес для PAC-файла,请输入 PAC 网址,請輸入 PAC 網址,PAC URLを入力して下さい,프록시 자동 구성 URL을 입력하세요,Veuillez saisir l'URL PAC
,,,,,,
# Messages,,,,,,
,,,,,,
Shadowsocks Error: {0},Ошибка Shadowsocks: {0},Shadowsocks 错误: {0},Shadowsocks 錯誤: {0},Shadowsocks エラー: {0},Shadowsocks 오류: {0},Erreur shadowsocks: {0}
Port {0} already in use,Порт {0} уже используется,端口 {0} 已被占用,連接埠號碼 {0} 已被使用,ポート番号 {0} は既に使用されています。,{0}번 포트는 이미 사용 중입니다.,Port {0} déjà utilisé
Port {0} is reserved by system,Порт {0} зарезервирован системой,端口 {0} 是系统保留端口,連接埠號碼 {0} 由系統保留, ポート番号 {0} はシステムによって予約されています,{0}번 포트는 시스템에서 사용 중입니다.,Port {0} réservé par le système
Invalid server address,Неверный адрес сервера,非法服务器地址,無效伺服器位址,サーバーアドレスが無効です。,올바르지 않은 서버 주소입니다.,Adresse de serveur non valide
Illegal port number format,Неверный числовой формат порта,非法端口格式,無效連接埠號碼格式,ポート番号のフォーマットが無効です。,올바르지 않은 포트 번호 형식입니다.,Format de numéro de port illégal
Illegal timeout format,Неверный формат таймаута,非法超时格式,無效逾時格式,タイムアウト値のフォーマットが無効です。,올바르지 않은 시간 초과 형식입니다.,Format de délai d'attente illégal
Server IP can not be blank,IP-адрес сервера не может быть пустым,服务器 IP 不能为空,伺服器 IP 不能為空,サーバー IP が指定されていません。,서버 IP는 비어있으면 안됩니다.,L'adresse IP du serveur ne peut pas être vide
Password can not be blank,Пароль не может быть пустым,密码不能为空,密碼不能為空,パスワードが指定されていません。,비밀번호는 비어있으면 안됩니다.,Le mot de passe ne peut pas être vide
Port out of range,Порт выходит за допустимый диапазон,端口超出范围,連接埠號碼超出範圍,ポート番号は範囲外です。,올바른 포트 범위가 아닙니다.,Port hors de portée
Port can't be 8123,Адрес порта 8123 не может быть использован,端口不能为 8123,連接埠號碼不能為 8123,8123 番以外のポート番号を指定して下さい。,8123번 포트는 사용할 수 없습니다.,Le port ne peut pas être 8123
No update is available,Обновлений не обнаружено,没有可用的更新,沒有可用的更新,お使いのバージョンは最新です。,사용 가능한 업데이트가 없습니다.,Aucune mise à jour n'est disponible
Shadowsocks is here,Shadowsocks находится здесь,Shadowsocks 在这里,Shadowsocks 在這裡,Shadowsocks はここです。,Shadowsocks는 여기에 있습니다,Veuillez trouver Shadowsocks ici
You can turn on/off Shadowsocks in the context menu,Вы можете управлять Shadowsocks из контекстного меню,可以在右键菜单中开关 Shadowsocks,可以在右鍵選項單中開關 Shadowsocks,コンテキストメニューを使って、Shadowsocks を有効または無効にすることができます。,프로그램 메뉴에서 Shadowsocks를 끄고 켤 수 있습니다.,Vous pouvez activer / désactiver Shadowsocks dans le menu contextuel
System Proxy Enabled,Системный прокси включен,系统代理已启用,系統 Proxy 已啟用,システム プロキシが有効です。,시스템 프록시가 활성화되었습니다.,Proxy système activé
System Proxy Disabled,Системный прокси отключен,系统代理未启用,系統 Proxy 未啟用,システム プロキシが無効です。,시스템 프록시가 비활성화되었습니다.,Proxy système désactivé
Failed to update PAC file ,Не удалось обновить PAC файл,更新 PAC 文件失败,更新 PAC 檔案失敗,PAC の更新に失敗しました。,프록시 자동 구성 파일을 업데이트하는데 실패했습니다.,Impossible de mettre à jour le fichier PAC
PAC updated,PAC файл обновлен,更新 PAC 成功,更新 PAC 成功,PAC を更新しました。,프록시 자동 구성 파일이 업데이트되었습니다.,PAC mis à jour
No updates found. Please report to Geosite if you have problems with it.,Обновлений не найдено. Сообщите авторам Geosite если у вас возникли проблемы.,未发现更新。如有问题请提交给 Geosite。,未發現更新。如有問題請報告至 Geosite。,お使いのバージョンは最新です。問題がある場合は、GFWList に報告して下さい。,사용 가능한 업데이트를 찾지 못했습니다. 문제가 있다면 Geosite로 전송해주세요.,Aucune mise à jour trouvée. Veuillez signaler à Geosite si vous avez des problèmes concernant.
No QRCode found. Try to zoom in or move it to the center of the screen.,QRCode не обнаружен. Попробуйте увеличить изображение или переместить его в центр экрана.,未发现二维码,尝试把它放大或移动到靠近屏幕中间的位置,未發現 QR 碼,嘗試把它放大或移動到靠近熒幕中間的位置,QR コードが見つかりませんでした。コードを大きくするか、画面の中央に移動して下さい。,QR코드를 찾을 수 없습니다. 가운데로 화면을 이동시키거나 확대해보세요.,Aucun QRCode trouvé. Essayez de zoomer ou de le déplacer vers le centre de l'écran.
Shadowsocks is already running.,Shadowsocks уже запущен.,Shadowsocks 已经在运行。,Shadowsocks 已經在執行。,Shadowsocks 実行中,Shadowsocks가 이미 실행 중입니다.,Shadowsocks est déjà en cours d'exécution.
Find Shadowsocks icon in your notify tray.,Значок Shadowsocks можно найти в области уведомлений.,请在任务栏里寻找 Shadowsocks 图标。,請在工作列裡尋找 Shadowsocks 圖示。,通知領域には Shadowsocks のアイコンがあります。,트레이에서 Shadowsocks를 찾아주세요.,Trouvez l'icône Shadowsocks dans votre barre de notification.
"If you want to start multiple Shadowsocks, make a copy in another directory.","Если вы хотите запустить несколько копий Shadowsocks одновременно, создайте отдельную папку на каждую копию.",如果想同时启动多个,可以另外复制一份到别的目录。,如果想同時啟動多個,可以另外複製一份至別的目錄。,複数起動したい場合は、プログラムファイルを別のフォルダーにコピーしてから、もう一度実行して下さい。,"만약 여러 개의 Shadowsocks를 사용하고 싶으시다면, 파일을 다른 곳에 복사해주세요.","Si vous souhaitez démarrer plusieurs Shadowsocks, faites une copie dans un autre répertoire."
Invalid QR Code content: {0},,无效二维码内容: {0},無效二維碼內容: {0},,,
Failed to update registry,Не удалось обновить запись в реестре,无法修改注册表,無法修改登錄檔,レジストリの更新に失敗しました。,레지스트리를 업데이트하는데에 실패했습니다.,Impossible de mettre à jour de la base de registre
Import from URL: {0} ?,импортировать из адреса: {0} ?,从URL导入: {0} ?,從URL匯入: {0} ?,{0}:このURLからインポートしますか?,,
Successfully imported from {0},Успешно импортировано из {0},导入成功:{0},導入成功:{0},{0}:インポートしました。,,
Failed to import. Please check if the link is valid.,,导入失败,请检查链接是否有效。,導入失敗,請檢查鏈接是否有效。,インポートに失敗しました。リンクの有効性を確認してください。,,
Warning: importing {0} from a legacy ss:// link. Support for legacy ss:// links will be dropped in version 5. Make sure to update your ss:// links.,,警告: 正在从旧版 ss:// 链接导入 {0}。对旧版 ss:// 链接的支持将于 v5 移除,请及时更新你的链接。,,,,
System Proxy On: ,Системный прокси:,系统代理已启用:,系統 Proxy 已啟用:,システム プロキシが有効:,시스템 프록시 활성화됨: ,Proxy système activé:
Running: Port {0},Запущен на порту {0},正在运行:端口 {0},正在執行:連接埠號碼 {0},実行中:ポート {0},실행 중: 포트 {0}번,En cours d'exécution: port {0}
"Unexpected error, shadowsocks will exit. Please report to","Непредвиденная ошибка, пожалуйста сообщите на",非预期错误,Shadowsocks将退出。请提交此错误到,非預期錯誤,Shadowsocks 將結束。請報告此錯誤至,予想外のエラーが発生したため、Shadowsocks を終了します。詳しくは下記までお問い合わせ下さい:,알 수 없는 오류로 Shadowsocks가 종료될 것입니다. 오류를 여기로 제보해주세요:,Shadowsocks va quitter en présence d/érreur inattendue. Veuillez signaler à
"Unsupported operating system, use Windows Vista at least.","Операционная система не поддерживается, минимальные системные требования: Windows Vista или выше.",不支持的操作系统版本,最低需求为Windows Vista。,不支援的作業系統版本,最低需求為 Windows Vista。,お使いの OS はサポートされていません。Windows Vista 以降の OS で実行して下さい。,지원하지 않는 운영체제입니다. 최소 Windows Vista가 필요합니다.,"Système d'exploitation incompatible, veuillez utiliser Windows Vista ou ultérieure."
"Unsupported .NET Framework, please update to {0} or later.","Версия .NET Framework не поддерживается, минимальные системные требования: {0} или выше.",当前 .NET Framework 版本过低,请升级至{0}或更新版本。,目前 .NET Framework 版本過低,最低需求為{0}。,お使いの .NET Framework はサポートされていません。{0} 以降のバンジョーをインストールして下さい。,지원하지 않는 .NET 프레임워크입니다. {0} 또는 상위 버전으로 업데이트해주세요.,".NET Framework incompatible, veuillez mettre à jour vers {0} ou ultérieure."
Proxy request failed,Не удалось выполнить запрос,代理请求失败,Proxy 要求失敗,プロキシリクエストが失敗しました。,프록시 요청에 실패했습니다.,Échec de la demande de proxy
Proxy handshake failed,Не удалось выполнить хэндшейк,代理握手失败,Proxy 交握失敗,プロキシ ハンドシェイクに失敗しました。,프록시 핸드쉐이크에 실패했습니다.,Échec de la prise de contact par proxy
Register hotkey failed,Не удалось применить настройки горячих клавиш,注册快捷键失败,註冊快速鍵失敗,ホットキーの登錄に失敗しました。,단축키 등록에 실패했습니다.,Échec de l'enregistrement du raccourci clavier
Cannot parse hotkey: {0},Не удалось распознать следующие горячие клавиши: {0},解析快捷键失败: {0},剖析快速鍵失敗: {0},ホットキーを解析できません: {0},단축키를 해석할 수 없습니다: {0},Impossible d'analyser le raccourci clavier: {0}
"Timeout is invalid, it should not exceed {0}",Таймаут не может превышать значение {0},超时无效,不应超过 {0},逾時無效,不應超過 {0},タイムアウト値が無効です。{0} 以下の値を指定して下さい。,올바르지 않은 시간 초과 설정입니다. {0}을 초과하지 않아야 합니다.,"Le délai d'attente invalide, il ne doit pas dépasser {0}"
Cannot find the plugin program file,Файл плагина не найден,找不到插件程序文件,找不到外掛程式文件,プラグインプログラムが見つかりません,플러그인 프로그램 파일을 찾을 수 없습니다.,Impossible de trouver le fichier du programme du plugin
,,,,,,
Operation failure,Операция завершилась неудачей,操作失败,,操作に失敗しました,작업에 실패했습니다.,Operation failure
Auto save failed,Автоматическое сохранение не удалось,自动保存失败,,オートセーブに失敗しました,자동 저장에 실패했습니다.,Échec de l'enregistrement automatique
Whether to discard unconfigured servers,Внесенные изменения будут утеряны,是否丢弃未配置的服务器,,未設定のサーバーを破棄しますか,구성되지 않은 서버 설정 변경 사항을 폐기하시겠습니까?,Eliminer les serveurs non configurés ou non
"Invalid server address, Cannot automatically save or discard changes",Неверный адрес сервера. Невозможно сохранить или отменить изменения,非法服务器地址,无法自动保存,是否丢弃修改,,サーバーアドレスが無効なため、オートセーブできません。変更を破棄しますか,"서버 주소가 올바르지 않아 자동 저장 할 수 없습니다, 변경 사항을 폐기하시겠습니까?","Adresse de serveur invalide, impossible d'enregistrer ou d'annuler automatiquement les modifications"
"Illegal port number format, Cannot automatically save or discard changes",Неверный числовой адрес порта. Невозможно сохранить или отменить изменения,非法端口格式,无法自动保存,是否丢弃修改,,ポート番号のフォーマットが無効なため、オートセーブできません。変更を破棄しますか,"포트 번호가 올바르지 않아 자동 저장 할 수 없습니다, 변경 사항을 폐기하시겠습니까?","Format de numéro de port illégal, impossible d'enregistrer ou d'annuler automatiquement les modifications"
"Password can not be blank, Cannot automatically save or discard changes",Пароль не может быть пустым. Невозможно сохранить или отменить изменения,密码不能为空,无法自动保存,是否丢弃修改,,サーバーアドレスが無効なため、オートセーブできません。変更を破棄しますか,"비밀번호를 입력하지 않아 자동 저장 할 수 없습니다, 변경 사항을 폐기하시겠습니까?","Le mot de passe ne peut pas être vide, impossible d'enregistrer ou d'annuler automatiquement les modifications"
"Illegal timeout format, Cannot automatically save or discard changes",Неверный формат таймаута. Невозможно сохранить или отменить изменения,非法超时格式,无法自动保存,是否丢弃修改,,パスワードが指定されていないため、オートセーブできません。変更を破棄しますか,시간 초과 형식이 올바르지 않아 자동 저장 할 수 없습니다. 변경 사항을 폐기하시겠습니까?,"Format de délai d'attente illégal, impossible d'enregistrer ou d'annuler automatiquement les modifications"
,,,,タイムアウト値のフォーマットが無効なため、オートセーブできません。変更を破棄しますか,,
"Error occured when process proxy setting, do you want reset current setting and retry?",Произошла ошибка при обработке настроек. Хотите сбросить текущие настройки и попробовать снова?,处理代理设置时发生错误,是否重置当前代理设置并重试?,,プロキシ設定の処理にエラーが発生しました、現在のプロキシ設定をリセットし、再試行してもいいですか,프록시 설정을 처리하는데에 오류가 발생했습니다. 현재 설정을 폐기하고 다시 시도하시겠습니까?,Une erreur s'est produite lors du processus de configuration du proxy. Voulez-vous réinitialiser le paramètre actuel et réessayer?
"Unrecoverable proxy setting error occured, see log for detail","Произошла серьезная ошибка, подробности можно узнать в журналах",发生不可恢复的代理设置错误,查看日志以取得详情,,プロキシ設定に回復不能なエラーが発生しました、ログで詳細をご確認ください,복구 불가능한 프록시 설정 오류가 발생했습니다. 자세한 정보는 로그를 참조하세요.,"Une erreur de paramètre de proxy irrécupérable s'est produite, consultez le journal pour plus de détails"
================================================
FILE: shadowsocks-csharp/Data/privoxy_conf.txt
================================================
listen-address __PRIVOXY_BIND_IP__:__PRIVOXY_BIND_PORT__
toggle 0
logfile ss_privoxy.log
show-on-task-bar 0
activity-animation 0
forward-socks5 / __SOCKS_HOST__:__SOCKS_PORT__ .
max-client-connections 2048
hide-console
================================================
FILE: shadowsocks-csharp/Data/user-rule.txt
================================================
! Put user rules line by line in this file.
! See https://adblockplus.org/en/filter-cheatsheet
================================================
FILE: shadowsocks-csharp/Encryption/AEAD/AEADEncryptor.cs
================================================
using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Text;
using Shadowsocks.Encryption.CircularBuffer;
using Shadowsocks.Controller;
using Shadowsocks.Encryption.Exception;
namespace Shadowsocks.Encryption.AEAD
{
public abstract class AEADEncryptor
: EncryptorBase
{
private static Logger logger = LogManager.GetCurrentClassLogger();
// We are using the same saltLen and keyLen
private const string Info = "ss-subkey";
private static readonly byte[] InfoBytes = Encoding.ASCII.GetBytes(Info);
// for UDP only
protected static byte[] _udpTmpBuf = new byte[65536];
// every connection should create its own buffer
private ByteCircularBuffer _encCircularBuffer = new ByteCircularBuffer(MAX_INPUT_SIZE * 2);
private ByteCircularBuffer _decCircularBuffer = new ByteCircularBuffer(MAX_INPUT_SIZE * 2);
public const int CHUNK_LEN_BYTES = 2;
public const uint CHUNK_LEN_MASK = 0x3FFFu;
protected Dictionary ciphers;
protected string _method;
protected int _cipher;
// internal name in the crypto library
protected string _innerLibName;
protected EncryptorInfo CipherInfo;
protected static byte[] _Masterkey = null;
protected byte[] _sessionKey;
protected int keyLen;
protected int saltLen;
protected int tagLen;
protected int nonceLen;
protected byte[] _encryptSalt;
protected byte[] _decryptSalt;
protected object _nonceIncrementLock = new object();
protected byte[] _encNonce;
protected byte[] _decNonce;
// Is first packet
protected bool _decryptSaltReceived;
protected bool _encryptSaltSent;
// Is first chunk(tcp request)
protected bool _tcpRequestSent;
public AEADEncryptor(string method, string password)
: base(method, password)
{
InitEncryptorInfo(method);
InitKey(password);
// Initialize all-zero nonce for each connection
_encNonce = new byte[nonceLen];
_decNonce = new byte[nonceLen];
}
protected abstract Dictionary getCiphers();
protected void InitEncryptorInfo(string method)
{
method = method.ToLower();
_method = method;
ciphers = getCiphers();
CipherInfo = ciphers[_method];
_innerLibName = CipherInfo.InnerLibName;
_cipher = CipherInfo.Type;
if (_cipher == 0) {
throw new System.Exception("method not found");
}
keyLen = CipherInfo.KeySize;
saltLen = CipherInfo.SaltSize;
tagLen = CipherInfo.TagSize;
nonceLen = CipherInfo.NonceSize;
}
protected void InitKey(string password)
{
byte[] passbuf = Encoding.UTF8.GetBytes(password);
// init master key
if (_Masterkey == null) _Masterkey = new byte[keyLen];
if (_Masterkey.Length != keyLen) Array.Resize(ref _Masterkey, keyLen);
DeriveKey(passbuf, _Masterkey, keyLen);
// init session key
if (_sessionKey == null) _sessionKey = new byte[keyLen];
}
public void DeriveKey(byte[] password, byte[] key, int keylen)
{
byte[] result = new byte[password.Length + MD5_LEN];
int i = 0;
byte[] md5sum = null;
while (i < keylen)
{
if (i == 0)
{
md5sum = MbedTLS.MD5(password);
}
else
{
Array.Copy(md5sum, 0, result, 0, MD5_LEN);
Array.Copy(password, 0, result, MD5_LEN, password.Length);
md5sum = MbedTLS.MD5(result);
}
Array.Copy(md5sum, 0, key, i, Math.Min(MD5_LEN, keylen - i));
i += MD5_LEN;
}
}
public void DeriveSessionKey(byte[] salt, byte[] masterKey, byte[] sessionKey)
{
int ret = MbedTLS.hkdf(salt, saltLen, masterKey, keyLen, InfoBytes, InfoBytes.Length, sessionKey,
keyLen);
if (ret != 0) throw new System.Exception("failed to generate session key");
}
protected void IncrementNonce(bool isEncrypt)
{
lock (_nonceIncrementLock) {
Sodium.sodium_increment(isEncrypt ? _encNonce : _decNonce, nonceLen);
}
}
public virtual void InitCipher(byte[] salt, bool isEncrypt, bool isUdp)
{
if (isEncrypt) {
_encryptSalt = new byte[saltLen];
Array.Copy(salt, _encryptSalt, saltLen);
} else {
_decryptSalt = new byte[saltLen];
Array.Copy(salt, _decryptSalt, saltLen);
}
logger.Dump("Salt", salt, saltLen);
}
public static void randBytes(byte[] buf, int length) { RNG.GetBytes(buf, length); }
public abstract void cipherEncrypt(byte[] plaintext, uint plen, byte[] ciphertext, ref uint clen);
public abstract void cipherDecrypt(byte[] ciphertext, uint clen, byte[] plaintext, ref uint plen);
#region TCP
public override void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength)
{
Debug.Assert(_encCircularBuffer != null, "_encCircularBuffer != null");
_encCircularBuffer.Put(buf, 0, length);
outlength = 0;
logger.Trace("---Start Encryption");
if (! _encryptSaltSent) {
_encryptSaltSent = true;
// Generate salt
byte[] saltBytes = new byte[saltLen];
randBytes(saltBytes, saltLen);
InitCipher(saltBytes, true, false);
Array.Copy(saltBytes, 0, outbuf, 0, saltLen);
outlength = saltLen;
logger.Trace($"_encryptSaltSent outlength {outlength}");
}
if (! _tcpRequestSent) {
_tcpRequestSent = true;
// The first TCP request
int encAddrBufLength;
byte[] encAddrBufBytes = new byte[AddrBufLength + tagLen * 2 + CHUNK_LEN_BYTES];
byte[] addrBytes = _encCircularBuffer.Get(AddrBufLength);
ChunkEncrypt(addrBytes, AddrBufLength, encAddrBufBytes, out encAddrBufLength);
Debug.Assert(encAddrBufLength == AddrBufLength + tagLen * 2 + CHUNK_LEN_BYTES);
Array.Copy(encAddrBufBytes, 0, outbuf, outlength, encAddrBufLength);
outlength += encAddrBufLength;
logger.Trace($"_tcpRequestSent outlength {outlength}");
}
// handle other chunks
while (true) {
uint bufSize = (uint)_encCircularBuffer.Size;
if (bufSize <= 0) return;
var chunklength = (int)Math.Min(bufSize, CHUNK_LEN_MASK);
byte[] chunkBytes = _encCircularBuffer.Get(chunklength);
int encChunkLength;
byte[] encChunkBytes = new byte[chunklength + tagLen * 2 + CHUNK_LEN_BYTES];
ChunkEncrypt(chunkBytes, chunklength, encChunkBytes, out encChunkLength);
Debug.Assert(encChunkLength == chunklength + tagLen * 2 + CHUNK_LEN_BYTES);
Buffer.BlockCopy(encChunkBytes, 0, outbuf, outlength, encChunkLength);
outlength += encChunkLength;
logger.Trace("chunks enc outlength " + outlength);
// check if we have enough space for outbuf
if (outlength + TCPHandler.ChunkOverheadSize > TCPHandler.BufferSize) {
logger.Trace("enc outbuf almost full, giving up");
return;
}
bufSize = (uint)_encCircularBuffer.Size;
if (bufSize <= 0) {
logger.Trace("No more data to encrypt, leaving");
return;
}
}
}
public override void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength)
{
Debug.Assert(_decCircularBuffer != null, "_decCircularBuffer != null");
int bufSize;
outlength = 0;
// drop all into buffer
_decCircularBuffer.Put(buf, 0, length);
logger.Trace("---Start Decryption");
if (! _decryptSaltReceived) {
bufSize = _decCircularBuffer.Size;
// check if we get the leading salt
if (bufSize <= saltLen) {
// need more
return;
}
_decryptSaltReceived = true;
byte[] salt = _decCircularBuffer.Get(saltLen);
InitCipher(salt, false, false);
logger.Trace("get salt len " + saltLen);
}
// handle chunks
while (true) {
bufSize = _decCircularBuffer.Size;
// check if we have any data
if (bufSize <= 0) {
logger.Trace("No data in _decCircularBuffer");
return;
}
// first get chunk length
if (bufSize <= CHUNK_LEN_BYTES + tagLen) {
// so we only have chunk length and its tag?
return;
}
#region Chunk Decryption
byte[] encLenBytes = _decCircularBuffer.Peek(CHUNK_LEN_BYTES + tagLen);
uint decChunkLenLength = 0;
byte[] decChunkLenBytes = new byte[CHUNK_LEN_BYTES];
// try to dec chunk len
cipherDecrypt(encLenBytes, CHUNK_LEN_BYTES + (uint)tagLen, decChunkLenBytes, ref decChunkLenLength);
Debug.Assert(decChunkLenLength == CHUNK_LEN_BYTES);
// finally we get the real chunk len
ushort chunkLen = (ushort) IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(decChunkLenBytes, 0));
if (chunkLen > CHUNK_LEN_MASK)
{
// we get invalid chunk
logger.Error($"Invalid chunk length: {chunkLen}");
throw new CryptoErrorException();
}
logger.Trace("Get the real chunk len:" + chunkLen);
bufSize = _decCircularBuffer.Size;
if (bufSize < CHUNK_LEN_BYTES + tagLen /* we haven't remove them */+ chunkLen + tagLen) {
logger.Trace("No more data to decrypt one chunk");
return;
}
IncrementNonce(false);
// we have enough data to decrypt one chunk
// drop chunk len and its tag from buffer
_decCircularBuffer.Skip(CHUNK_LEN_BYTES + tagLen);
byte[] encChunkBytes = _decCircularBuffer.Get(chunkLen + tagLen);
byte[] decChunkBytes = new byte[chunkLen];
uint decChunkLen = 0;
cipherDecrypt(encChunkBytes, chunkLen + (uint)tagLen, decChunkBytes, ref decChunkLen);
Debug.Assert(decChunkLen == chunkLen);
IncrementNonce(false);
#endregion
// output to outbuf
Buffer.BlockCopy(decChunkBytes, 0, outbuf, outlength, (int) decChunkLen);
outlength += (int)decChunkLen;
logger.Trace("aead dec outlength " + outlength);
if (outlength + 100 > TCPHandler.BufferSize)
{
logger.Trace("dec outbuf almost full, giving up");
return;
}
bufSize = _decCircularBuffer.Size;
// check if we already done all of them
if (bufSize <= 0) {
logger.Trace("No data in _decCircularBuffer, already all done");
return;
}
}
}
#endregion
#region UDP
public override void EncryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)
{
// Generate salt
randBytes(outbuf, saltLen);
InitCipher(outbuf, true, true);
uint olen = 0;
lock (_udpTmpBuf) {
cipherEncrypt(buf, (uint) length, _udpTmpBuf, ref olen);
Debug.Assert(olen == length + tagLen);
Buffer.BlockCopy(_udpTmpBuf, 0, outbuf, saltLen, (int) olen);
outlength = (int) (saltLen + olen);
}
}
public override void DecryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)
{
InitCipher(buf, false, true);
uint olen = 0;
lock (_udpTmpBuf) {
// copy remaining data to first pos
Buffer.BlockCopy(buf, saltLen, buf, 0, length - saltLen);
cipherDecrypt(buf, (uint) (length - saltLen), _udpTmpBuf, ref olen);
Buffer.BlockCopy(_udpTmpBuf, 0, outbuf, 0, (int) olen);
outlength = (int) olen;
}
}
#endregion
// we know the plaintext length before encryption, so we can do it in one operation
private void ChunkEncrypt(byte[] plaintext, int plainLen, byte[] ciphertext, out int cipherLen)
{
if (plainLen > CHUNK_LEN_MASK) {
logger.Error("enc chunk too big");
throw new CryptoErrorException();
}
// encrypt len
byte[] encLenBytes = new byte[CHUNK_LEN_BYTES + tagLen];
uint encChunkLenLength = 0;
byte[] lenbuf = BitConverter.GetBytes((ushort) IPAddress.HostToNetworkOrder((short)plainLen));
cipherEncrypt(lenbuf, CHUNK_LEN_BYTES, encLenBytes, ref encChunkLenLength);
Debug.Assert(encChunkLenLength == CHUNK_LEN_BYTES + tagLen);
IncrementNonce(true);
// encrypt corresponding data
byte[] encBytes = new byte[plainLen + tagLen];
uint encBufLength = 0;
cipherEncrypt(plaintext, (uint) plainLen, encBytes, ref encBufLength);
Debug.Assert(encBufLength == plainLen + tagLen);
IncrementNonce(true);
// construct outbuf
Array.Copy(encLenBytes, 0, ciphertext, 0, (int) encChunkLenLength);
Buffer.BlockCopy(encBytes, 0, ciphertext, (int) encChunkLenLength, (int) encBufLength);
cipherLen = (int) (encChunkLenLength + encBufLength);
}
}
}
================================================
FILE: shadowsocks-csharp/Encryption/AEAD/AEADMbedTLSEncryptor.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Shadowsocks.Encryption.Exception;
namespace Shadowsocks.Encryption.AEAD
{
public class AEADMbedTLSEncryptor
: AEADEncryptor, IDisposable
{
const int CIPHER_AES = 1;
private IntPtr _encryptCtx = IntPtr.Zero;
private IntPtr _decryptCtx = IntPtr.Zero;
public AEADMbedTLSEncryptor(string method, string password)
: base(method, password)
{
}
private static readonly Dictionary _ciphers = new Dictionary
{
{"aes-128-gcm", new EncryptorInfo("AES-128-GCM", 16, 16, 12, 16, CIPHER_AES)},
{"aes-192-gcm", new EncryptorInfo("AES-192-GCM", 24, 24, 12, 16, CIPHER_AES)},
{"aes-256-gcm", new EncryptorInfo("AES-256-GCM", 32, 32, 12, 16, CIPHER_AES)},
};
public static List SupportedCiphers()
{
return new List(_ciphers.Keys);
}
protected override Dictionary getCiphers()
{
return _ciphers;
}
public override void InitCipher(byte[] salt, bool isEncrypt, bool isUdp)
{
base.InitCipher(salt, isEncrypt, isUdp);
IntPtr ctx = Marshal.AllocHGlobal(MbedTLS.cipher_get_size_ex());
if (isEncrypt)
{
_encryptCtx = ctx;
}
else
{
_decryptCtx = ctx;
}
MbedTLS.cipher_init(ctx);
if (MbedTLS.cipher_setup(ctx, MbedTLS.cipher_info_from_string(_innerLibName)) != 0)
throw new System.Exception("Cannot initialize mbed TLS cipher context");
DeriveSessionKey(isEncrypt ? _encryptSalt : _decryptSalt,
_Masterkey, _sessionKey);
CipherSetKey(isEncrypt, _sessionKey);
}
private void CipherSetKey(bool isEncrypt, byte[] key)
{
IntPtr ctx = isEncrypt ? _encryptCtx : _decryptCtx;
int ret = MbedTLS.cipher_setkey(ctx, key, keyLen * 8,
isEncrypt ? MbedTLS.MBEDTLS_ENCRYPT : MbedTLS.MBEDTLS_DECRYPT);
if (ret != 0) throw new System.Exception("failed to set key");
ret = MbedTLS.cipher_reset(ctx);
if (ret != 0) throw new System.Exception("failed to finish preparation");
}
public override void cipherEncrypt(byte[] plaintext, uint plen, byte[] ciphertext, ref uint clen)
{
// buf: all plaintext
// outbuf: ciphertext + tag
int ret;
byte[] tagbuf = new byte[tagLen];
uint olen = 0;
switch (_cipher)
{
case CIPHER_AES:
ret = MbedTLS.cipher_auth_encrypt(_encryptCtx,
/* nonce */
_encNonce, (uint) nonceLen,
/* AD */
IntPtr.Zero, 0,
/* plain */
plaintext, plen,
/* cipher */
ciphertext, ref olen,
tagbuf, (uint) tagLen);
if (ret != 0) throw new CryptoErrorException(String.Format("ret is {0}", ret));
Debug.Assert(olen == plen);
// attach tag to ciphertext
Array.Copy(tagbuf, 0, ciphertext, (int) plen, tagLen);
clen = olen + (uint) tagLen;
break;
default:
throw new System.Exception("not implemented");
}
}
public override void cipherDecrypt(byte[] ciphertext, uint clen, byte[] plaintext, ref uint plen)
{
// buf: ciphertext + tag
// outbuf: plaintext
int ret;
uint olen = 0;
// split tag
byte[] tagbuf = new byte[tagLen];
Array.Copy(ciphertext, (int) (clen - tagLen), tagbuf, 0, tagLen);
switch (_cipher)
{
case CIPHER_AES:
ret = MbedTLS.cipher_auth_decrypt(_decryptCtx,
_decNonce, (uint) nonceLen,
IntPtr.Zero, 0,
ciphertext, (uint) (clen - tagLen),
plaintext, ref olen,
tagbuf, (uint) tagLen);
if (ret != 0) throw new CryptoErrorException(String.Format("ret is {0}", ret));
Debug.Assert(olen == clen - tagLen);
plen = olen;
break;
default:
throw new System.Exception("not implemented");
}
}
#region IDisposable
private bool _disposed;
// instance based lock
private readonly object _lock = new object();
public override void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~AEADMbedTLSEncryptor()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
lock (_lock)
{
if (_disposed) return;
_disposed = true;
}
if (disposing)
{
// free managed objects
}
// free unmanaged objects
if (_encryptCtx != IntPtr.Zero)
{
MbedTLS.cipher_free(_encryptCtx);
Marshal.FreeHGlobal(_encryptCtx);
_encryptCtx = IntPtr.Zero;
}
if (_decryptCtx != IntPtr.Zero)
{
MbedTLS.cipher_free(_decryptCtx);
Marshal.FreeHGlobal(_decryptCtx);
_decryptCtx = IntPtr.Zero;
}
}
#endregion
}
}
================================================
FILE: shadowsocks-csharp/Encryption/AEAD/AEADOpenSSLEncryptor.cs
================================================
using System;
using System.Collections.Generic;
using Shadowsocks.Encryption.Exception;
namespace Shadowsocks.Encryption.AEAD
{
public class AEADOpenSSLEncryptor
: AEADEncryptor, IDisposable
{
const int CIPHER_AES = 1;
const int CIPHER_CHACHA20IETFPOLY1305 = 2;
private byte[] _opensslEncSubkey;
private byte[] _opensslDecSubkey;
private IntPtr _encryptCtx = IntPtr.Zero;
private IntPtr _decryptCtx = IntPtr.Zero;
private IntPtr _cipherInfoPtr = IntPtr.Zero;
public AEADOpenSSLEncryptor(string method, string password)
: base(method, password)
{
_opensslEncSubkey = new byte[keyLen];
_opensslDecSubkey = new byte[keyLen];
}
private static readonly Dictionary _ciphers = new Dictionary
{
{"aes-128-gcm", new EncryptorInfo("aes-128-gcm", 16, 16, 12, 16, CIPHER_AES)},
{"aes-192-gcm", new EncryptorInfo("aes-192-gcm", 24, 24, 12, 16, CIPHER_AES)},
{"aes-256-gcm", new EncryptorInfo("aes-256-gcm", 32, 32, 12, 16, CIPHER_AES)},
{"chacha20-ietf-poly1305", new EncryptorInfo("chacha20-poly1305", 32, 32, 12, 16, CIPHER_CHACHA20IETFPOLY1305)}
};
public static List SupportedCiphers()
{
return new List(_ciphers.Keys);
}
protected override Dictionary getCiphers()
{
return _ciphers;
}
public override void InitCipher(byte[] salt, bool isEncrypt, bool isUdp)
{
base.InitCipher(salt, isEncrypt, isUdp);
_cipherInfoPtr = OpenSSL.GetCipherInfo(_innerLibName);
if (_cipherInfoPtr == IntPtr.Zero) throw new System.Exception("openssl: cipher not found");
IntPtr ctx = OpenSSL.EVP_CIPHER_CTX_new();
if (ctx == IntPtr.Zero) throw new System.Exception("openssl: fail to create ctx");
if (isEncrypt)
{
_encryptCtx = ctx;
}
else
{
_decryptCtx = ctx;
}
DeriveSessionKey(isEncrypt ? _encryptSalt : _decryptSalt, _Masterkey,
isEncrypt ? _opensslEncSubkey : _opensslDecSubkey);
var ret = OpenSSL.EVP_CipherInit_ex(ctx, _cipherInfoPtr, IntPtr.Zero, null, null,
isEncrypt ? OpenSSL.OPENSSL_ENCRYPT : OpenSSL.OPENSSL_DECRYPT);
if (ret != 1) throw new System.Exception("openssl: fail to init ctx");
ret = OpenSSL.EVP_CIPHER_CTX_set_key_length(ctx, keyLen);
if (ret != 1) throw new System.Exception("openssl: fail to set key length");
ret = OpenSSL.EVP_CIPHER_CTX_ctrl(ctx, OpenSSL.EVP_CTRL_AEAD_SET_IVLEN,
nonceLen, IntPtr.Zero);
if (ret != 1) throw new System.Exception("openssl: fail to set AEAD nonce length");
ret = OpenSSL.EVP_CipherInit_ex(ctx, IntPtr.Zero, IntPtr.Zero,
isEncrypt ? _opensslEncSubkey : _opensslDecSubkey,
null,
isEncrypt ? OpenSSL.OPENSSL_ENCRYPT : OpenSSL.OPENSSL_DECRYPT);
if (ret != 1) throw new System.Exception("openssl: cannot set key");
OpenSSL.EVP_CIPHER_CTX_set_padding(ctx, 0);
}
public override void cipherEncrypt(byte[] plaintext, uint plen, byte[] ciphertext, ref uint clen)
{
OpenSSL.SetCtxNonce(_encryptCtx, _encNonce, true);
// buf: all plaintext
// outbuf: ciphertext + tag
int ret;
int tmpLen = 0;
clen = 0;
var tagBuf = new byte[tagLen];
ret = OpenSSL.EVP_CipherUpdate(_encryptCtx, ciphertext, out tmpLen,
plaintext, (int) plen);
if (ret != 1) throw new CryptoErrorException("openssl: fail to encrypt AEAD");
clen += (uint) tmpLen;
// For AEAD cipher, it should not output anything
ret = OpenSSL.EVP_CipherFinal_ex(_encryptCtx, ciphertext, ref tmpLen);
if (ret != 1) throw new CryptoErrorException("openssl: fail to finalize AEAD");
if (tmpLen > 0)
{
throw new System.Exception("openssl: fail to finish AEAD");
}
OpenSSL.AEADGetTag(_encryptCtx, tagBuf, tagLen);
Array.Copy(tagBuf, 0, ciphertext, clen, tagLen);
clen += (uint) tagLen;
}
public override void cipherDecrypt(byte[] ciphertext, uint clen, byte[] plaintext, ref uint plen)
{
OpenSSL.SetCtxNonce(_decryptCtx, _decNonce, false);
// buf: ciphertext + tag
// outbuf: plaintext
int ret;
int tmpLen = 0;
plen = 0;
// split tag
byte[] tagbuf = new byte[tagLen];
Array.Copy(ciphertext, (int) (clen - tagLen), tagbuf, 0, tagLen);
OpenSSL.AEADSetTag(_decryptCtx, tagbuf, tagLen);
ret = OpenSSL.EVP_CipherUpdate(_decryptCtx,
plaintext, out tmpLen, ciphertext, (int) (clen - tagLen));
if (ret != 1) throw new CryptoErrorException("openssl: fail to decrypt AEAD");
plen += (uint) tmpLen;
// For AEAD cipher, it should not output anything
ret = OpenSSL.EVP_CipherFinal_ex(_decryptCtx, plaintext, ref tmpLen);
if (ret <= 0)
{
// If this is not successful authenticated
throw new CryptoErrorException(String.Format("ret is {0}", ret));
}
if (tmpLen > 0)
{
throw new System.Exception("openssl: fail to finish AEAD");
}
}
#region IDisposable
private bool _disposed;
// instance based lock
private readonly object _lock = new object();
public override void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~AEADOpenSSLEncryptor()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
lock (_lock)
{
if (_disposed) return;
_disposed = true;
}
if (disposing)
{
// free managed objects
}
// free unmanaged objects
if (_encryptCtx != IntPtr.Zero)
{
OpenSSL.EVP_CIPHER_CTX_free(_encryptCtx);
_encryptCtx = IntPtr.Zero;
}
if (_decryptCtx != IntPtr.Zero)
{
OpenSSL.EVP_CIPHER_CTX_free(_decryptCtx);
_decryptCtx = IntPtr.Zero;
}
}
#endregion
}
}
================================================
FILE: shadowsocks-csharp/Encryption/AEAD/AEADSodiumEncryptor.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using NLog;
using Shadowsocks.Controller;
using Shadowsocks.Encryption.Exception;
namespace Shadowsocks.Encryption.AEAD
{
public class AEADSodiumEncryptor
: AEADEncryptor, IDisposable
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private const int CIPHER_CHACHA20IETFPOLY1305 = 1;
private const int CIPHER_XCHACHA20IETFPOLY1305 = 2;
private const int CIPHER_AES256GCM = 3;
private byte[] _sodiumEncSubkey;
private byte[] _sodiumDecSubkey;
public AEADSodiumEncryptor(string method, string password)
: base(method, password)
{
_sodiumEncSubkey = new byte[keyLen];
_sodiumDecSubkey = new byte[keyLen];
}
private static readonly Dictionary _ciphers = new Dictionary
{
{"chacha20-ietf-poly1305", new EncryptorInfo(32, 32, 12, 16, CIPHER_CHACHA20IETFPOLY1305)},
{"xchacha20-ietf-poly1305", new EncryptorInfo(32, 32, 24, 16, CIPHER_XCHACHA20IETFPOLY1305)},
{"aes-256-gcm", new EncryptorInfo(32, 32, 12, 16, CIPHER_AES256GCM)},
};
public static List SupportedCiphers()
{
return new List(_ciphers.Keys);
}
protected override Dictionary getCiphers()
{
return _ciphers;
}
public override void InitCipher(byte[] salt, bool isEncrypt, bool isUdp)
{
base.InitCipher(salt, isEncrypt, isUdp);
DeriveSessionKey(isEncrypt ? _encryptSalt : _decryptSalt, _Masterkey,
isEncrypt ? _sodiumEncSubkey : _sodiumDecSubkey);
}
public override void cipherEncrypt(byte[] plaintext, uint plen, byte[] ciphertext, ref uint clen)
{
Debug.Assert(_sodiumEncSubkey != null);
// buf: all plaintext
// outbuf: ciphertext + tag
int ret;
ulong encClen = 0;
logger.Dump("_encNonce before enc", _encNonce, nonceLen);
logger.Dump("_sodiumEncSubkey", _sodiumEncSubkey, keyLen);
logger.Dump("before cipherEncrypt: plain", plaintext, (int) plen);
switch (_cipher)
{
case CIPHER_CHACHA20IETFPOLY1305:
ret = Sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, ref encClen,
plaintext, (ulong) plen,
null, 0,
null, _encNonce,
_sodiumEncSubkey);
break;
case CIPHER_XCHACHA20IETFPOLY1305:
ret = Sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(ciphertext, ref encClen,
plaintext, (ulong)plen,
null, 0,
null, _encNonce,
_sodiumEncSubkey);
break;
case CIPHER_AES256GCM:
ret = Sodium.crypto_aead_aes256gcm_encrypt(ciphertext, ref encClen,
plaintext, (ulong)plen,
null, 0,
null, _encNonce,
_sodiumEncSubkey);
break;
default:
throw new System.Exception("not implemented");
}
if (ret != 0) throw new CryptoErrorException(String.Format("ret is {0}", ret));
logger.Dump("after cipherEncrypt: cipher", ciphertext, (int) encClen);
clen = (uint) encClen;
}
public override void cipherDecrypt(byte[] ciphertext, uint clen, byte[] plaintext, ref uint plen)
{
Debug.Assert(_sodiumDecSubkey != null);
// buf: ciphertext + tag
// outbuf: plaintext
int ret;
ulong decPlen = 0;
logger.Dump("_decNonce before dec", _decNonce, nonceLen);
logger.Dump("_sodiumDecSubkey", _sodiumDecSubkey, keyLen);
logger.Dump("before cipherDecrypt: cipher", ciphertext, (int) clen);
switch (_cipher)
{
case CIPHER_CHACHA20IETFPOLY1305:
ret = Sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, ref decPlen,
null,
ciphertext, (ulong) clen,
null, 0,
_decNonce, _sodiumDecSubkey);
break;
case CIPHER_XCHACHA20IETFPOLY1305:
ret = Sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(plaintext, ref decPlen,
null,
ciphertext, (ulong)clen,
null, 0,
_decNonce, _sodiumDecSubkey);
break;
case CIPHER_AES256GCM:
ret = Sodium.crypto_aead_aes256gcm_decrypt(plaintext, ref decPlen,
null,
ciphertext, (ulong)clen,
null, 0,
_decNonce, _sodiumDecSubkey);
break;
default:
throw new System.Exception("not implemented");
}
if (ret != 0) throw new CryptoErrorException(String.Format("ret is {0}", ret));
logger.Dump("after cipherDecrypt: plain", plaintext, (int) decPlen);
plen = (uint) decPlen;
}
public override void Dispose()
{
}
}
}
================================================
FILE: shadowsocks-csharp/Encryption/CircularBuffer/ByteCircularBuffer.cs
================================================
#region Original License
//New BSD License(BSD)
//
//Copyright(c) 2014-2015 Cyotek Ltd
//Copyright(c) 2012, Alex Regueiro
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Cyotek nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED.IN NO EVENT SHALL BE LIABLE FOR ANY
//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
namespace Shadowsocks.Encryption.CircularBuffer
{
///
/// Represents a first-in, first-out collection of objects using a fixed buffer.
///
///
/// The capacity of a is the number of elements the can hold.
/// ByteCircularBuffer accepts null as a valid value for reference types and allows duplicate elements.
/// The methods will remove the items that are returned from the ByteCircularBuffer. To view the contents of the ByteCircularBuffer without removing items, use the or methods.
///
public class ByteCircularBuffer
{
// based on http://circularbuffer.codeplex.com/
// http://en.wikipedia.org/wiki/Circular_buffer
// modified from https://github.com/cyotek/Cyotek.Collections.Generic.CircularBuffer
// some code taken from https://github.com/xorxornop/RingBuffer
// and https://github.com/xorxornop/PerfCopy
#region Instance Fields
private byte[] _buffer;
private int _capacity;
#endregion
#region Public Constructors
///
/// Initializes a new instance of the class that is empty and has the specified initial capacity.
///
/// The maximum capcity of the buffer.
/// Thown if the is less than zero.
public ByteCircularBuffer(int capacity)
{
if (capacity < 0)
{
throw new ArgumentException("The buffer capacity must be greater than or equal to zero.",
nameof(capacity));
}
_buffer = new byte[capacity];
this.Capacity = capacity;
this.Size = 0;
this.Head = 0;
this.Tail = 0;
}
#endregion
#region Public Properties
///
/// Gets or sets the total number of elements the internal data structure can hold.
///
/// The total number of elements that the can contain.
/// Thrown if the specified new capacity is smaller than the current contents of the buffer.
public int Capacity
{
get { return _capacity; }
set
{
if (value != _capacity)
{
if (value < this.Size)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
"The new capacity must be greater than or equal to the buffer size.");
}
var newBuffer = new byte[value];
if (this.Size > 0)
{
this.CopyTo(newBuffer);
}
_buffer = newBuffer;
_capacity = value;
}
}
}
///
/// Gets the index of the beginning of the buffer data.
///
/// The index of the first element in the buffer.
public int Head { get; protected set; }
///
/// Gets a value indicating whether the buffer is empty.
///
/// true if buffer is empty; otherwise, false.
public virtual bool IsEmpty => this.Size == 0;
///
/// Gets a value indicating whether the buffer is full.
///
/// true if the buffer is full; otherwise, false.
/// The property always returns false if the property is set to true.
public virtual bool IsFull => this.Size == this.Capacity;
///
/// Gets the number of elements contained in the .
///
/// The number of elements contained in the .
public int Size { get; protected set; }
///
/// Gets the index of the end of the buffer data.
///
/// The index of the last element in the buffer.
public int Tail { get; protected set; }
#endregion
#region Public Members
///
/// Removes all items from the .
///
public void Clear()
{
this.Size = 0;
this.Head = 0;
this.Tail = 0;
_buffer = new byte[this.Capacity];
}
///
/// Determines whether the contains a specific value.
///
/// The object to locate in the .
/// true if is found in the ; otherwise, false.
public bool Contains(byte item)
{
var bufferIndex = this.Head;
var comparer = EqualityComparer.Default;
var result = false;
for (int i = 0; i < this.Size; i++, bufferIndex++)
{
if (bufferIndex == this.Capacity)
{
bufferIndex = 0;
}
if (comparer.Equals(_buffer[bufferIndex], item))
{
result = true;
break;
}
}
return result;
}
///
/// Copies the entire to a compatible one-dimensional array, starting at the beginning of the target array.
///
/// The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing.
public void CopyTo(byte[] array)
{
this.CopyTo(array, 0);
}
///
/// Copies the entire to a compatible one-dimensional array, starting at the specified index of the target array.
///
/// The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing.
/// The zero-based index in at which copying begins.
public void CopyTo(byte[] array, int arrayIndex)
{
this.CopyTo(this.Head, array, arrayIndex, Math.Min(this.Size, array.Length - arrayIndex));
}
///
/// Copies a range of elements from the to a compatible one-dimensional array, starting at the specified index of the target array.
///
/// The zero-based index in the source at which copying begins.
/// The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing.
/// The zero-based index in at which copying begins.
/// The number of elements to copy.
public virtual void CopyTo(int index, byte[] array, int arrayIndex, int count)
{
if (count > this.Size)
{
throw new ArgumentOutOfRangeException(nameof(count), count,
"The read count cannot be greater than the buffer size.");
}
var startAnchor = index;
var dstIndex = arrayIndex;
while (count > 0)
{
int chunk = Math.Min(Capacity - startAnchor, count);
Buffer.BlockCopy(_buffer, startAnchor, array, dstIndex, chunk);
startAnchor = (startAnchor + chunk == Capacity) ? 0 : startAnchor + chunk;
dstIndex += chunk;
count -= chunk;
}
}
///
/// Removes and returns the specified number of objects from the beginning of the .
///
/// The number of elements to remove and return from the .
/// The objects that are removed from the beginning of the .
public byte[] Get(int count)
{
if (count <= 0) throw new ArgumentOutOfRangeException("should greater than 0");
var result = new byte[count];
this.Get(result);
return result;
}
///
/// Copies and removes the specified number elements from the to a compatible one-dimensional array, starting at the beginning of the target array.
///
/// The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing.
/// The actual number of elements copied into .
public int Get(byte[] array)
{
if (array.Length <= 0) throw new ArgumentOutOfRangeException("should greater than 0");
return this.Get(array, 0, array.Length);
}
///
/// Copies and removes the specified number elements from the to a compatible one-dimensional array, starting at the specified index of the target array.
///
/// The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing.
/// The zero-based index in at which copying begins.
/// The number of elements to copy.
/// The actual number of elements copied into .
public virtual int Get(byte[] array, int arrayIndex, int count)
{
if (arrayIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), "Negative offset specified. Offsets must be positive.");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), "Negative count specified. Count must be positive.");
}
if (count > this.Size)
{
throw new ArgumentException("Ringbuffer contents insufficient for take/read operation.", nameof(count));
}
if (array.Length < arrayIndex + count)
{
throw new ArgumentException("Destination array too small for requested output.");
}
var bytesCopied = 0;
var dstIndex = arrayIndex;
while (count > 0)
{
int chunk = Math.Min(Capacity - this.Head, count);
Buffer.BlockCopy(_buffer, this.Head, array, dstIndex, chunk);
this.Head = (this.Head + chunk == Capacity) ? 0 : this.Head + chunk;
this.Size -= chunk;
dstIndex += chunk;
bytesCopied += chunk;
count -= chunk;
}
return bytesCopied;
}
///
/// Removes and returns the object at the beginning of the .
///
/// The object that is removed from the beginning of the .
/// Thrown if the buffer is empty.
/// This method is similar to the method, but Peek does not modify the .
public virtual byte Get()
{
if (this.IsEmpty)
{
throw new InvalidOperationException("The buffer is empty.");
}
var item = _buffer[this.Head];
if (++this.Head == this.Capacity)
{
this.Head = 0;
}
this.Size--;
return item;
}
///
/// Returns the object at the beginning of the without removing it.
///
/// The object at the beginning of the .
/// Thrown if the buffer is empty.
public virtual byte Peek()
{
if (this.IsEmpty)
{
throw new InvalidOperationException("The buffer is empty.");
}
var item = _buffer[this.Head];
return item;
}
///
/// Returns the specified number of objects from the beginning of the .
///
/// The number of elements to return from the .
/// The objects that from the beginning of the .
/// Thrown if the buffer is empty.
public virtual byte[] Peek(int count)
{
if (this.IsEmpty)
{
throw new InvalidOperationException("The buffer is empty.");
}
var items = new byte[count];
this.CopyTo(items);
return items;
}
///
/// Returns the object at the end of the without removing it.
///
/// The object at the end of the .
/// Thrown if the buffer is empty.
public virtual byte PeekLast()
{
int bufferIndex;
if (this.IsEmpty)
{
throw new InvalidOperationException("The buffer is empty.");
}
if (this.Tail == 0)
{
bufferIndex = this.Size - 1;
}
else
{
bufferIndex = this.Tail - 1;
}
var item = _buffer[bufferIndex];
return item;
}
///
/// Copies an entire compatible one-dimensional array to the .
///
/// The one-dimensional that is the source of the elements copied to . The must have zero-based indexing.
/// Thrown if buffer does not have sufficient capacity to put in new items.
/// If plus the size of exceeds the capacity of the and the property is true, the oldest items in the are overwritten with .
public int Put(byte[] array)
{
return this.Put(array, 0, array.Length);
}
///
/// Copies a range of elements from a compatible one-dimensional array to the .
///
/// The one-dimensional that is the source of the elements copied to . The must have zero-based indexing.
/// The zero-based index in at which copying begins.
/// The number of elements to copy.
/// Thrown if buffer does not have sufficient capacity to put in new items.
/// If plus exceeds the capacity of the and the property is true, the oldest items in the are overwritten with .
public virtual int Put(byte[] array, int arrayIndex, int count)
{
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count), "Count must be positive.");
if (this.Size + count > this.Capacity)
{
throw new InvalidOperationException("The buffer does not have sufficient capacity to put new items.");
}
if (array.Length < arrayIndex + count)
{
throw new ArgumentException("Source array too small for requested input.");
}
var srcIndex = arrayIndex;
var bytesToProcess = count;
while (bytesToProcess > 0)
{
int chunk = Math.Min(Capacity - Tail, bytesToProcess);
Buffer.BlockCopy(array, srcIndex, _buffer, Tail, chunk);
Tail = (Tail + chunk == Capacity) ? 0 : Tail + chunk;
this.Size += chunk;
srcIndex += chunk;
bytesToProcess -= chunk;
}
return count;
}
///
/// Adds a byte to the end of the .
///
/// The byte to add to the .
/// Thrown if buffer does not have sufficient capacity to put in new items.
public virtual void Put(byte item)
{
if (IsFull)
{
throw new InvalidOperationException("The buffer does not have sufficient capacity to put new items.");
}
_buffer[this.Tail] = item;
this.Tail++;
if (this.Size == this.Capacity)
{
this.Head++;
if (this.Head >= this.Capacity)
{
this.Head -= this.Capacity;
}
}
if (this.Tail == this.Capacity)
{
this.Tail = 0;
}
if (this.Size != this.Capacity)
{
this.Size++;
}
}
///
/// Increments the starting index of the data buffer in the .
///
/// The number of elements to increment the data buffer start index by.
public void Skip(int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), "Negative count specified. Count must be positive.");
}
if (count > this.Size)
{
throw new ArgumentException("Ringbuffer contents insufficient for operation.", nameof(count));
}
// Modular division gives new offset position
this.Head = (this.Head + count) % Capacity;
this.Size -= count;
}
///
/// Copies the elements to a new array.
///
/// A new array containing elements copied from the .
/// The is not modified. The order of the elements in the new array is the same as the order of the elements from the beginning of the to its end.
public byte[] ToArray()
{
var result = new byte[this.Size];
this.CopyTo(result);
return result;
}
#endregion
}
}
================================================
FILE: shadowsocks-csharp/Encryption/EncryptorBase.cs
================================================
namespace Shadowsocks.Encryption
{
public class EncryptorInfo
{
public int KeySize;
public int IvSize;
public int SaltSize;
public int TagSize;
public int NonceSize;
public int Type;
public string InnerLibName;
// For those who make use of internal crypto method name
// e.g. mbed TLS
#region Stream ciphers
public EncryptorInfo(string innerLibName, int keySize, int ivSize, int type)
{
this.KeySize = keySize;
this.IvSize = ivSize;
this.Type = type;
this.InnerLibName = innerLibName;
}
public EncryptorInfo(int keySize, int ivSize, int type)
{
this.KeySize = keySize;
this.IvSize = ivSize;
this.Type = type;
this.InnerLibName = string.Empty;
}
#endregion
#region AEAD ciphers
public EncryptorInfo(string innerLibName, int keySize, int saltSize, int nonceSize, int tagSize, int type)
{
this.KeySize = keySize;
this.SaltSize = saltSize;
this.NonceSize = nonceSize;
this.TagSize = tagSize;
this.Type = type;
this.InnerLibName = innerLibName;
}
public EncryptorInfo(int keySize, int saltSize, int nonceSize, int tagSize, int type)
{
this.KeySize = keySize;
this.SaltSize = saltSize;
this.NonceSize = nonceSize;
this.TagSize = tagSize;
this.Type = type;
this.InnerLibName = string.Empty;
}
#endregion
}
public abstract class EncryptorBase
: IEncryptor
{
public const int MAX_INPUT_SIZE = 32768;
public const int MAX_DOMAIN_LEN = 255;
public const int ADDR_PORT_LEN = 2;
public const int ADDR_ATYP_LEN = 1;
public const int ATYP_IPv4 = 0x01;
public const int ATYP_DOMAIN = 0x03;
public const int ATYP_IPv6 = 0x04;
public const int MD5_LEN = 16;
protected EncryptorBase(string method, string password)
{
Method = method;
Password = password;
}
protected string Method;
protected string Password;
public abstract void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength);
public abstract void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength);
public abstract void EncryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength);
public abstract void DecryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength);
public abstract void Dispose();
public int AddrBufLength { get; set; } = - 1;
}
}
================================================
FILE: shadowsocks-csharp/Encryption/EncryptorFactory.cs
================================================
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Shadowsocks.Encryption.AEAD;
using Shadowsocks.Encryption.Stream;
namespace Shadowsocks.Encryption
{
public static class EncryptorFactory
{
private static Dictionary _registeredEncryptors = new Dictionary();
private static readonly Type[] ConstructorTypes = {typeof(string), typeof(string)};
static EncryptorFactory()
{
var AEADMbedTLSEncryptorSupportedCiphers = AEADMbedTLSEncryptor.SupportedCiphers();
var AEADSodiumEncryptorSupportedCiphers = AEADSodiumEncryptor.SupportedCiphers();
var PlainEncryptorSupportedCiphers = PlainEncryptor.SupportedCiphers();
if (Sodium.AES256GCMAvailable)
{
// prefer to aes-256-gcm in libsodium
AEADMbedTLSEncryptorSupportedCiphers.Remove("aes-256-gcm");
}
else
{
AEADSodiumEncryptorSupportedCiphers.Remove("aes-256-gcm");
}
foreach (string method in AEADOpenSSLEncryptor.SupportedCiphers())
{
if (!_registeredEncryptors.ContainsKey(method))
_registeredEncryptors.Add(method, typeof(AEADOpenSSLEncryptor));
}
foreach (string method in AEADSodiumEncryptorSupportedCiphers)
{
if (!_registeredEncryptors.ContainsKey(method))
_registeredEncryptors.Add(method, typeof(AEADSodiumEncryptor));
}
foreach (string method in AEADMbedTLSEncryptorSupportedCiphers)
{
if (!_registeredEncryptors.ContainsKey(method))
_registeredEncryptors.Add(method, typeof(AEADMbedTLSEncryptor));
}
foreach (string method in PlainEncryptorSupportedCiphers)
{
if (!_registeredEncryptors.ContainsKey(method))
_registeredEncryptors.Add(method, typeof(PlainEncryptor));
}
}
public static IEncryptor GetEncryptor(string method, string password)
{
if (string.IsNullOrEmpty(method))
{
method = Model.Server.DefaultMethod;
}
method = method.ToLowerInvariant();
Type t = _registeredEncryptors[method];
ConstructorInfo c = t.GetConstructor(ConstructorTypes);
if (c == null) throw new System.Exception("Invalid ctor");
IEncryptor result = (IEncryptor) c.Invoke(new object[] {method, password});
return result;
}
public static string DumpRegisteredEncryptor()
{
var sb = new StringBuilder();
sb.Append(Environment.NewLine);
sb.AppendLine("=========================");
sb.AppendLine("Registered Encryptor Info");
foreach (var encryptor in _registeredEncryptors)
{
sb.AppendLine(String.Format("{0}=>{1}", encryptor.Key, encryptor.Value.Name));
}
sb.AppendLine("=========================");
return sb.ToString();
}
}
}
================================================
FILE: shadowsocks-csharp/Encryption/Exception/CryptoException.cs
================================================
namespace Shadowsocks.Encryption.Exception
{
public class CryptoErrorException : System.Exception
{
public CryptoErrorException()
{
}
public CryptoErrorException(string msg) : base(msg)
{
}
public CryptoErrorException(string message, System.Exception innerException) : base(message, innerException)
{
}
}
}
================================================
FILE: shadowsocks-csharp/Encryption/IEncryptor.cs
================================================
using System;
namespace Shadowsocks.Encryption
{
public interface IEncryptor : IDisposable
{
/* length == -1 means not used */
int AddrBufLength { set; get; }
void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength);
void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength);
void EncryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength);
void DecryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength);
}
}
================================================
FILE: shadowsocks-csharp/Encryption/MbedTLS.cs
================================================
using System;
using System.IO;
using System.Runtime.InteropServices;
using NLog;
using Shadowsocks.Controller;
using Shadowsocks.Properties;
using Shadowsocks.Util;
namespace Shadowsocks.Encryption
{
public static class MbedTLS
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private const string DLLNAME = "libsscrypto.dll";
public const int MBEDTLS_ENCRYPT = 1;
public const int MBEDTLS_DECRYPT = 0;
static MbedTLS()
{
string dllPath = Utils.GetTempPath(DLLNAME);
try
{
FileManager.UncompressFile(dllPath, Resources.libsscrypto_dll);
}
catch (IOException)
{
}
catch (System.Exception e)
{
logger.LogUsefulException(e);
}
LoadLibrary(dllPath);
}
public static byte[] MD5(byte[] input)
{
byte[] output = new byte[16];
if (md5_ret(input, (uint) input.Length, output) != 0)
throw new System.Exception("mbedtls: MD5 failure");
return output;
}
[DllImport("Kernel32.dll")]
private static extern IntPtr LoadLibrary(string path);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int md5_ret(byte[] input, uint ilen, byte[] output);
///
/// Get cipher ctx size for unmanaged memory allocation
///
///
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int cipher_get_size_ex();
#region Cipher layer wrappers
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr cipher_info_from_string(string cipher_name);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern void cipher_init(IntPtr ctx);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int cipher_setup(IntPtr ctx, IntPtr cipher_info);
// XXX: Check operation before using it
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int cipher_setkey(IntPtr ctx, byte[] key, int key_bitlen, int operation);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int cipher_set_iv(IntPtr ctx, byte[] iv, int iv_len);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int cipher_reset(IntPtr ctx);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int cipher_update(IntPtr ctx, byte[] input, int ilen, byte[] output, ref int olen);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern void cipher_free(IntPtr ctx);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int cipher_auth_encrypt(IntPtr ctx,
byte[] iv, uint iv_len,
IntPtr ad, uint ad_len,
byte[] input, uint ilen,
byte[] output, ref uint olen,
byte[] tag, uint tag_len);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int cipher_auth_decrypt(IntPtr ctx,
byte[] iv, uint iv_len,
IntPtr ad, uint ad_len,
byte[] input, uint ilen,
byte[] output, ref uint olen,
byte[] tag, uint tag_len);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int hkdf(byte[] salt,
int salt_len, byte[] ikm, int ikm_len,
byte[] info, int info_len, byte[] okm,
int okm_len);
#endregion
}
}
================================================
FILE: shadowsocks-csharp/Encryption/OpenSSL.cs
================================================
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using NLog;
using Shadowsocks.Controller;
using Shadowsocks.Encryption.Exception;
using Shadowsocks.Properties;
using Shadowsocks.Util;
namespace Shadowsocks.Encryption
{
// XXX: only for OpenSSL 1.1.0 and higher
public static class OpenSSL
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private const string DLLNAME = "libsscrypto.dll";
public const int OPENSSL_ENCRYPT = 1;
public const int OPENSSL_DECRYPT = 0;
public const int EVP_CTRL_AEAD_SET_IVLEN = 0x9;
public const int EVP_CTRL_AEAD_GET_TAG = 0x10;
public const int EVP_CTRL_AEAD_SET_TAG = 0x11;
static OpenSSL()
{
string dllPath = Utils.GetTempPath(DLLNAME);
try
{
FileManager.UncompressFile(dllPath, Resources.libsscrypto_dll);
}
catch (IOException)
{
}
catch (System.Exception e)
{
logger.LogUsefulException(e);
}
LoadLibrary(dllPath);
}
public static IntPtr GetCipherInfo(string cipherName)
{
var name = Encoding.ASCII.GetBytes(cipherName);
Array.Resize(ref name, name.Length + 1);
return EVP_get_cipherbyname(name);
}
///
/// Need init cipher context after EVP_CipherFinal_ex to reuse context
///
///
///
///
public static void SetCtxNonce(IntPtr ctx, byte[] nonce, bool isEncrypt)
{
var ret = EVP_CipherInit_ex(ctx, IntPtr.Zero,
IntPtr.Zero, null,
nonce,
isEncrypt ? OPENSSL_ENCRYPT : OPENSSL_DECRYPT);
if (ret != 1) throw new System.Exception("openssl: fail to set AEAD nonce");
}
public static void AEADGetTag(IntPtr ctx, byte[] tagbuf, int taglen)
{
IntPtr tagBufIntPtr = IntPtr.Zero;
try
{
tagBufIntPtr = Marshal.AllocHGlobal(taglen);
var ret = EVP_CIPHER_CTX_ctrl(ctx,
EVP_CTRL_AEAD_GET_TAG, taglen, tagBufIntPtr);
if (ret != 1) throw new CryptoErrorException("openssl: fail to get AEAD tag");
// take tag from unmanaged memory
Marshal.Copy(tagBufIntPtr, tagbuf, 0, taglen);
}
finally
{
if (tagBufIntPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(tagBufIntPtr);
}
}
}
public static void AEADSetTag(IntPtr ctx, byte[] tagbuf, int taglen)
{
IntPtr tagBufIntPtr = IntPtr.Zero;
try
{
// allocate unmanaged memory for tag
tagBufIntPtr = Marshal.AllocHGlobal(taglen);
// copy tag to unmanaged memory
Marshal.Copy(tagbuf, 0, tagBufIntPtr, taglen);
var ret = EVP_CIPHER_CTX_ctrl(ctx,
EVP_CTRL_AEAD_SET_TAG, taglen, tagBufIntPtr);
if (ret != 1) throw new CryptoErrorException("openssl: fail to set AEAD tag");
}
finally
{
if (tagBufIntPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(tagBufIntPtr);
}
}
}
[DllImport("Kernel32.dll")]
private static extern IntPtr LoadLibrary(string path);
[SuppressUnmanagedCodeSecurity]
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr EVP_CIPHER_CTX_new();
[SuppressUnmanagedCodeSecurity]
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern void EVP_CIPHER_CTX_free(IntPtr ctx);
[SuppressUnmanagedCodeSecurity]
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int EVP_CIPHER_CTX_reset(IntPtr ctx);
[SuppressUnmanagedCodeSecurity]
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int EVP_CipherInit_ex(IntPtr ctx, IntPtr type,
IntPtr impl, byte[] key, byte[] iv, int enc);
[SuppressUnmanagedCodeSecurity]
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int EVP_CipherUpdate(IntPtr ctx, byte[] outb,
out int outl, byte[] inb, int inl);
[SuppressUnmanagedCodeSecurity]
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int EVP_CipherFinal_ex(IntPtr ctx, byte[] outm, ref int outl);
[SuppressUnmanagedCodeSecurity]
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int EVP_CIPHER_CTX_set_padding(IntPtr x, int padding);
[SuppressUnmanagedCodeSecurity]
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int EVP_CIPHER_CTX_set_key_length(IntPtr x, int keylen);
[SuppressUnmanagedCodeSecurity]
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int EVP_CIPHER_CTX_ctrl(IntPtr ctx, int type, int arg, IntPtr ptr);
///
/// simulate NUL-terminated string
///
///
///
[SuppressUnmanagedCodeSecurity]
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr EVP_get_cipherbyname(byte[] name);
}
}
================================================
FILE: shadowsocks-csharp/Encryption/RNG.cs
================================================
using System;
using System.Security.Cryptography;
namespace Shadowsocks.Encryption
{
public static class RNG
{
private static RNGCryptoServiceProvider _rng = null;
public static void Init()
{
_rng = _rng ?? new RNGCryptoServiceProvider();
}
public static void Close()
{
_rng?.Dispose();
_rng = null;
}
public static void Reload()
{
Close();
Init();
}
public static void GetBytes(byte[] buf)
{
GetBytes(buf, buf.Length);
}
public static void GetBytes(byte[] buf, int len)
{
if (_rng == null) Init();
try
{
_rng.GetBytes(buf, 0, len);
}
catch
{
// the backup way
byte[] tmp = new byte[len];
_rng.GetBytes(tmp);
Buffer.BlockCopy(tmp, 0, buf, 0, len);
}
}
}
}
================================================
FILE: shadowsocks-csharp/Encryption/Sodium.cs
================================================
using System;
using System.IO;
using System.Runtime.InteropServices;
using NLog;
using Shadowsocks.Controller;
using Shadowsocks.Properties;
using Shadowsocks.Util;
namespace Shadowsocks.Encryption
{
public static class Sodium
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private const string DLLNAME = "libsscrypto.dll";
private static bool _initialized = false;
private static readonly object _initLock = new object();
public static bool AES256GCMAvailable { get; private set; } = false;
static Sodium()
{
string dllPath = Utils.GetTempPath(DLLNAME);
try
{
FileManager.UncompressFile(dllPath, Resources.libsscrypto_dll);
}
catch (IOException)
{
}
catch (System.Exception e)
{
logger.LogUsefulException(e);
}
LoadLibrary(dllPath);
lock (_initLock)
{
if (!_initialized)
{
if (sodium_init() == -1)
{
throw new System.Exception("Failed to initialize sodium");
}
else /* 1 means already initialized; 0 means success */
{
_initialized = true;
}
AES256GCMAvailable = crypto_aead_aes256gcm_is_available() == 1;
logger.Debug($"sodium: AES256GCMAvailable is {AES256GCMAvailable}");
}
}
}
[DllImport("Kernel32.dll")]
private static extern IntPtr LoadLibrary(string path);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
private static extern int sodium_init();
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
private static extern int crypto_aead_aes256gcm_is_available();
#region AEAD
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int sodium_increment(byte[] n, int nlen);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int crypto_aead_chacha20poly1305_ietf_encrypt(byte[] c, ref ulong clen_p, byte[] m,
ulong mlen, byte[] ad, ulong adlen, byte[] nsec, byte[] npub, byte[] k);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int crypto_aead_chacha20poly1305_ietf_decrypt(byte[] m, ref ulong mlen_p,
byte[] nsec, byte[] c, ulong clen, byte[] ad, ulong adlen, byte[] npub, byte[] k);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int crypto_aead_xchacha20poly1305_ietf_encrypt(byte[] c, ref ulong clen_p, byte[] m, ulong mlen,
byte[] ad, ulong adlen, byte[] nsec, byte[] npub, byte[] k);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int crypto_aead_xchacha20poly1305_ietf_decrypt(byte[] m, ref ulong mlen_p, byte[] nsec, byte[] c,
ulong clen, byte[] ad, ulong adlen, byte[] npub, byte[] k);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int crypto_aead_aes256gcm_encrypt(byte[] c, ref ulong clen_p, byte[] m, ulong mlen,
byte[] ad, ulong adlen, byte[] nsec, byte[] npub, byte[] k);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int crypto_aead_aes256gcm_decrypt(byte[] m, ref ulong mlen_p, byte[] nsec, byte[] c,
ulong clen, byte[] ad, ulong adlen, byte[] npub, byte[] k);
#endregion
#region Stream
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int crypto_stream_salsa20_xor_ic(byte[] c, byte[] m, ulong mlen, byte[] n, ulong ic,
byte[] k);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int crypto_stream_chacha20_xor_ic(byte[] c, byte[] m, ulong mlen, byte[] n, ulong ic,
byte[] k);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int crypto_stream_chacha20_ietf_xor_ic(byte[] c, byte[] m, ulong mlen, byte[] n, uint ic,
byte[] k);
#endregion
}
}
================================================
FILE: shadowsocks-csharp/Encryption/Stream/PlainEncryptor.cs
================================================
using System;
using System.Collections.Generic;
namespace Shadowsocks.Encryption.Stream
{
class PlainEncryptor
: EncryptorBase, IDisposable
{
const int CIPHER_NONE = 1;
private static Dictionary _ciphers = new Dictionary {
{ "plain", new EncryptorInfo("PLAIN", 0, 0, CIPHER_NONE) },
{ "none", new EncryptorInfo("PLAIN", 0, 0, CIPHER_NONE) }
};
public PlainEncryptor(string method, string password) : base(method, password)
{
}
public static List SupportedCiphers()
{
return new List(_ciphers.Keys);
}
protected Dictionary getCiphers()
{
return _ciphers;
}
#region TCP
public override void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength)
{
Buffer.BlockCopy(buf, 0, outbuf, 0, length);
outlength = length;
}
public override void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength)
{
Buffer.BlockCopy(buf, 0, outbuf, 0, length);
outlength = length;
}
#endregion
#region UDP
public override void EncryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)
{
Buffer.BlockCopy(buf, 0, outbuf, 0, length);
outlength = length;
}
public override void DecryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)
{
Buffer.BlockCopy(buf, 0, outbuf, 0, length);
outlength = length;
}
#endregion
#region IDisposable
private bool _disposed;
// instance based lock
private readonly object _lock = new object();
public override void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~PlainEncryptor()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
lock (_lock)
{
if (_disposed) return;
_disposed = true;
}
if (disposing)
{
// free managed objects
}
}
#endregion
}
}
================================================
FILE: shadowsocks-csharp/FodyWeavers.xml
================================================
================================================
FILE: shadowsocks-csharp/FodyWeavers.xsd
================================================
A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks
A list of assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks.
A list of unmanaged 32 bit assembly names to include, delimited with line breaks.
A list of unmanaged 64 bit assembly names to include, delimited with line breaks.
The order of preloaded assemblies, delimited with line breaks.
This will copy embedded files to disk before loading them into memory. This is helpful for some scenarios that expected an assembly to be loaded from a physical file.
Controls if .pdbs for reference assemblies are also embedded.
Embedded assemblies are compressed by default, and uncompressed when they are loaded. You can turn compression off with this option.
As part of Costura, embedded assemblies are no longer included as part of the build. This cleanup can be turned off.
Costura by default will load as part of the module initialization. This flag disables that behavior. Make sure you call CosturaUtility.Initialize() somewhere in your code.
Costura will by default use assemblies with a name like 'resources.dll' as a satellite resource and prepend the output path. This flag disables that behavior.
A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with |
A list of assembly names to include from the default action of "embed all Copy Local references", delimited with |.
A list of unmanaged 32 bit assembly names to include, delimited with |.
A list of unmanaged 64 bit assembly names to include, delimited with |.
The order of preloaded assemblies, delimited with |.
'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.
A comma-separated list of error codes that can be safely ignored in assembly verification.
'false' to turn off automatic generation of the XML Schema file.
================================================
FILE: shadowsocks-csharp/Localization/LocalizationProvider.cs
================================================
using System.Reflection;
using WPFLocalizeExtension.Extensions;
namespace Shadowsocks.Localization
{
public static class LocalizationProvider
{
public static T GetLocalizedValue(string key)
{
return LocExtension.GetLocalizedValue(Assembly.GetCallingAssembly().GetName().Name + ":Strings:" + key);
}
}
}
================================================
FILE: shadowsocks-csharp/Localization/Strings.Designer.cs
================================================
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
namespace Shadowsocks.Localization {
using System;
///
/// A strongly-typed resource class, for looking up localized strings, etc.
///
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Strings {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Strings() {
}
///
/// Returns the cached ResourceManager instance used by this class.
///
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Shadowsocks.Localization.Strings", typeof(Strings).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
///
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
///
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
///
/// Looks up a localized string similar to _Add.
///
internal static string addButton_Content {
get {
return ResourceManager.GetString("addButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to Address.
///
internal static string Address {
get {
return ResourceManager.GetString("Address", resourceCulture);
}
}
///
/// Looks up a localized string similar to Allow clients from LAN.
///
internal static string AllowClientsFromLAN {
get {
return ResourceManager.GetString("AllowClientsFromLAN", resourceCulture);
}
}
///
/// Looks up a localized string similar to _Cancel.
///
internal static string cancelButton_Content {
get {
return ResourceManager.GetString("cancelButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to _Copy.
///
internal static string Copy {
get {
return ResourceManager.GetString("Copy", resourceCulture);
}
}
///
/// Looks up a localized string similar to _Copy link.
///
internal static string copyLinkButton_Content {
get {
return ResourceManager.GetString("copyLinkButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to Credentials (optional).
///
internal static string CredentialsOptional {
get {
return ResourceManager.GetString("CredentialsOptional", resourceCulture);
}
}
///
/// Looks up a localized string similar to Details.
///
internal static string Details {
get {
return ResourceManager.GetString("Details", resourceCulture);
}
}
///
/// Looks up a localized string similar to Forward Proxy.
///
internal static string ForwardProxy {
get {
return ResourceManager.GetString("ForwardProxy", resourceCulture);
}
}
///
/// Looks up a localized string similar to Hotkeys.
///
internal static string Hotkeys {
get {
return ResourceManager.GetString("Hotkeys", resourceCulture);
}
}
///
/// Looks up a localized string similar to HTTP.
///
internal static string HTTP {
get {
return ResourceManager.GetString("HTTP", resourceCulture);
}
}
///
/// Looks up a localized string similar to No proxy.
///
internal static string NoProxy {
get {
return ResourceManager.GetString("NoProxy", resourceCulture);
}
}
///
/// Looks up a localized string similar to _Not now.
///
internal static string notNowButton_Content {
get {
return ResourceManager.GetString("notNowButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to _OK.
///
internal static string okButton_Content {
get {
return ResourceManager.GetString("okButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to Online Configuration Delivery.
///
internal static string OnlineConfigDelivery {
get {
return ResourceManager.GetString("OnlineConfigDelivery", resourceCulture);
}
}
///
/// Looks up a localized string similar to Open logs window.
///
internal static string OpenLogsWindow {
get {
return ResourceManager.GetString("OpenLogsWindow", resourceCulture);
}
}
///
/// Looks up a localized string similar to Password.
///
internal static string Password {
get {
return ResourceManager.GetString("Password", resourceCulture);
}
}
///
/// Looks up a localized string similar to Port.
///
internal static string Port {
get {
return ResourceManager.GetString("Port", resourceCulture);
}
}
///
/// Looks up a localized string similar to _Register all.
///
internal static string registerAllButton_Content {
get {
return ResourceManager.GetString("registerAllButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to Register hotkeys at startup.
///
internal static string RegisterHotkeysAtStartup {
get {
return ResourceManager.GetString("RegisterHotkeysAtStartup", resourceCulture);
}
}
///
/// Looks up a localized string similar to Remove.
///
internal static string removeButton_Content {
get {
return ResourceManager.GetString("removeButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to _Save.
///
internal static string saveButton_Content {
get {
return ResourceManager.GetString("saveButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to Server Sharing.
///
internal static string ServerSharing {
get {
return ResourceManager.GetString("ServerSharing", resourceCulture);
}
}
///
/// Looks up a localized string similar to The following sources failed to update:\n\n.
///
internal static string sip008UpdateAllFailure {
get {
return ResourceManager.GetString("sip008UpdateAllFailure", resourceCulture);
}
}
///
/// Looks up a localized string similar to Successfully updated all sources!.
///
internal static string sip008UpdateAllSuccess {
get {
return ResourceManager.GetString("sip008UpdateAllSuccess", resourceCulture);
}
}
///
/// Looks up a localized string similar to Update failed. See the logs for more information..
///
internal static string sip008UpdateFailure {
get {
return ResourceManager.GetString("sip008UpdateFailure", resourceCulture);
}
}
///
/// Looks up a localized string similar to Successfully updated the selected source!.
///
internal static string sip008UpdateSuccess {
get {
return ResourceManager.GetString("sip008UpdateSuccess", resourceCulture);
}
}
///
/// Looks up a localized string similar to _Skip version.
///
internal static string skipVersionButton_Content {
get {
return ResourceManager.GetString("skipVersionButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to SOCKS5.
///
internal static string SOCKS5 {
get {
return ResourceManager.GetString("SOCKS5", resourceCulture);
}
}
///
/// Looks up a localized string similar to Switch to next server.
///
internal static string SwitchToNextServer {
get {
return ResourceManager.GetString("SwitchToNextServer", resourceCulture);
}
}
///
/// Looks up a localized string similar to Switch to previous server.
///
internal static string SwitchToPreviousServer {
get {
return ResourceManager.GetString("SwitchToPreviousServer", resourceCulture);
}
}
///
/// Looks up a localized string similar to Timeout (sec).
///
internal static string Timeout {
get {
return ResourceManager.GetString("Timeout", resourceCulture);
}
}
///
/// Looks up a localized string similar to Toggle proxy mode.
///
internal static string ToggleProxyMode {
get {
return ResourceManager.GetString("ToggleProxyMode", resourceCulture);
}
}
///
/// Looks up a localized string similar to Toggle system proxy.
///
internal static string ToggleSystemProxy {
get {
return ResourceManager.GetString("ToggleSystemProxy", resourceCulture);
}
}
///
/// Looks up a localized string similar to Type.
///
internal static string Type {
get {
return ResourceManager.GetString("Type", resourceCulture);
}
}
///
/// Looks up a localized string similar to Update all.
///
internal static string updateAllButton_Content {
get {
return ResourceManager.GetString("updateAllButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to _Update.
///
internal static string updateButton_Content {
get {
return ResourceManager.GetString("updateButton_Content", resourceCulture);
}
}
///
/// Looks up a localized string similar to Please read the release notes carefully. Then decide whether to update..
///
internal static string updatePromptBody {
get {
return ResourceManager.GetString("updatePromptBody", resourceCulture);
}
}
///
/// Looks up a localized string similar to An update is available..
///
internal static string updatePromptTitle {
get {
return ResourceManager.GetString("updatePromptTitle", resourceCulture);
}
}
///
/// Looks up a localized string similar to Username.
///
internal static string Username {
get {
return ResourceManager.GetString("Username", resourceCulture);
}
}
///
/// Looks up a localized string similar to VersionUpdate.
///
internal static string VersionUpdate {
get {
return ResourceManager.GetString("VersionUpdate", resourceCulture);
}
}
}
}
================================================
FILE: shadowsocks-csharp/Localization/Strings.fr.resx
================================================
text/microsoft-resx
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Mot de passe
Port
Type
adresse
Délai d'attente (sec)
Annuler
OK
Changer l'état de proxy système
Changer le mode de proxy système
Autoriser les clients du LAN
Afficher les journaux
Passer au serveur précédent
Passer au serveur suivant
Enregistrer tout
Enregistrer tout au démarrage
Ajouter
sauter la version
Copier le lien
retirer
mise à jour
copie
================================================
FILE: shadowsocks-csharp/Localization/Strings.ja.resx
================================================
text/microsoft-resx
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
パスワード
タイプ
アドレス
ポート
タイムアウト (秒)
キャンセル
OK
システム プロキシの状態を切り替える
プロキシモードを切り替える
LAN からのアクセスの許可を切り替える
ログの表示
前のサーバーに切り替える
次のサーバーに切り替える
全部登録する
起動時にホットキーを登録する
新規
バージョンをスキップ
リンクをコピーする
更新
コピー
================================================
FILE: shadowsocks-csharp/Localization/Strings.ko.resx
================================================
text/microsoft-resx
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
비밀번호
유형
주소
포트
시간 초과 (초)
취소
확인
시스템 프록시 전환
시스템 프록시 모드 전환
LAN으로부터 클라이언트 허용
로그 보기…
이전 서버로 전환
다음 서버로 전환
모두 등록
시스템 시작 시 단축키 등록
추가
버전 건너 뛰기
링크 복사
새롭게 함
부
================================================
FILE: shadowsocks-csharp/Localization/Strings.resx
================================================
text/microsoft-resx
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Type
No proxy
SOCKS5
HTTP
Details
Address
Port
Timeout (sec)
Credentials (optional)
Username
Password
_Save
_Cancel
_OK
Toggle system proxy
Toggle proxy mode
Allow clients from LAN
Open logs window
Switch to previous server
Switch to next server
Register hotkeys at startup
_Register all
_Update
Update all
_Copy link
Remove
_Add
An update is available.
Please read the release notes carefully. Then decide whether to update.
_Skip version
_Not now
_Copy
Forward Proxy
Server Sharing
Hotkeys
Online Configuration Delivery
VersionUpdate
Successfully updated the selected source!
Update failed. See the logs for more information.
Successfully updated all sources!
The following sources failed to update:\n\n
================================================
FILE: shadowsocks-csharp/Localization/Strings.ru.resx
================================================
text/microsoft-resx
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Пароль
тип
адрес
порт
Таймаут (сек)
Отмена
ОК
ВКЛ/ВЫКЛ системный прокси-сервер
Переключение режима прокси-сервера
Общий доступ к подключению
Просмотр журналов
Переключить на пред. сервер
Переключить на след. сервер
Применить все
Применять при запуске программы
Добавить
пропустить версию
копировать ссылку
Удалить
Обновить
копировать
================================================
FILE: shadowsocks-csharp/Localization/Strings.zh-Hans.resx
================================================
text/microsoft-resx
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
不使用代理
类型
认证 (可选)
详细设置
地址
保存
取消
用户名
密码
端口
超时 (秒)
确定
全部注册
切换系统代理
切换代理模式
允许内网客户端连接
打开日志窗口
切换到上一个服务器
切换到下一个服务器
启动时注册快捷键
更新
全部更新
复制链接
移除
添加
跳过版本
暂不更新
发现可用更新
请仔细阅读发布信息,然后决定是否更新。
复制
前置代理
在线配置下发
热键
服务器分享
版本更新
成功更新选定来源!
更新失败,请查看日志获取更多信息。
成功更新所有来源!
下列来源更新失败:\n\n
================================================
FILE: shadowsocks-csharp/Localization/Strings.zh-Hant.resx
================================================
text/microsoft-resx
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
密碼
Port
類型
位址
逾時 (秒)
取消
確定
切換系統 Proxy 狀態
切換系統 Proxy 模式
切換區域網路共用
顯示記錄檔
切換上一個伺服器
切換下一個伺服器
註冊所有快速鍵
啟動時註冊快速鍵
更新
全部更新
新增
跳過版本
暫不更新
發現可用更新
複製鏈接
複製
================================================
FILE: shadowsocks-csharp/Model/Configuration.cs
================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using Newtonsoft.Json;
using NLog;
using Shadowsocks.Controller;
namespace Shadowsocks.Model
{
[Serializable]
public class Configuration
{
[JsonIgnore]
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public string version;
public List configs;
public List onlineConfigSource;
// when strategy is set, index is ignored
public string strategy;
public int index;
public bool global;
public bool enabled;
public bool shareOverLan;
public bool firstRun;
public int localPort;
public bool portableMode;
public bool showPluginOutput;
public string pacUrl;
public bool useOnlinePac;
public bool secureLocalPac; // enable secret for PAC server
public bool regeneratePacOnUpdate; // regenerate pac.txt on version update
public bool autoCheckUpdate;
public bool checkPreRelease;
public string skippedUpdateVersion; // skip the update with this version number
public bool isVerboseLogging;
// hidden options
public bool isIPv6Enabled; // for experimental ipv6 support
public bool generateLegacyUrl; // for pre-sip002 url compatibility
public string geositeUrl; // for custom geosite source (and rule group)
public string geositeSha256sumUrl; // optional custom sha256sum url, leave empty to disable checksum verification for your custom geosite source
public List geositeDirectGroups; // groups of domains that we connect without the proxy
public List geositeProxiedGroups; // groups of domains that we connect via the proxy
public bool geositePreferDirect; // a.k.a blacklist mode
public string userAgent;
//public NLogConfig.LogLevel logLevel;
public LogViewerConfig logViewer;
public ForwardProxyConfig proxy;
public HotkeyConfig hotkey;
[JsonIgnore]
public bool firstRunOnNewVersion;
public Configuration()
{
version = UpdateChecker.Version;
strategy = "";
index = 0;
global = false;
enabled = false;
shareOverLan = false;
firstRun = true;
localPort = 1080;
portableMode = true;
showPluginOutput = false;
pacUrl = "";
useOnlinePac = false;
secureLocalPac = true;
regeneratePacOnUpdate = true;
autoCheckUpdate = false;
checkPreRelease = false;
skippedUpdateVersion = "";
isVerboseLogging = false;
// hidden options
isIPv6Enabled = false;
generateLegacyUrl = false;
geositeUrl = "";
geositeSha256sumUrl = "";
geositeDirectGroups = new List()
{
"private",
"cn",
"geolocation-!cn@cn",
};
geositeProxiedGroups = new List()
{
"geolocation-!cn",
};
geositePreferDirect = false;
userAgent = "ShadowsocksWindows/$version";
logViewer = new LogViewerConfig();
proxy = new ForwardProxyConfig();
hotkey = new HotkeyConfig();
firstRunOnNewVersion = false;
configs = new List();
onlineConfigSource = new List();
}
[JsonIgnore]
public string userAgentString; // $version substituted with numeral version in it
[JsonIgnore]
NLogConfig nLogConfig;
private static readonly string CONFIG_FILE = "gui-config.json";
#if DEBUG
private static readonly NLogConfig.LogLevel verboseLogLevel = NLogConfig.LogLevel.Trace;
#else
private static readonly NLogConfig.LogLevel verboseLogLevel = NLogConfig.LogLevel.Debug;
#endif
[JsonIgnore]
public string LocalHost => isIPv6Enabled ? "[::1]" : "127.0.0.1";
public Server GetCurrentServer()
{
if (index >= 0 && index < configs.Count)
return configs[index];
else
return GetDefaultServer();
}
public WebProxy WebProxy => enabled
? new WebProxy(
isIPv6Enabled
? $"[{IPAddress.IPv6Loopback}]"
: IPAddress.Loopback.ToString(),
localPort)
: null;
///
/// Used by multiple forms to validate a server.
/// Communication is done by throwing exceptions.
///
///
public static void CheckServer(Server server)
{
CheckServer(server.server);
CheckPort(server.server_port);
CheckPassword(server.password);
CheckTimeout(server.timeout, Server.MaxServerTimeoutSec);
}
///
/// Loads the configuration from file.
///
/// An Configuration object.
public static Configuration Load()
{
Configuration config;
if (File.Exists(CONFIG_FILE))
{
try
{
string configContent = File.ReadAllText(CONFIG_FILE);
config = JsonConvert.DeserializeObject(configContent, new JsonSerializerSettings()
{
ObjectCreationHandling = ObjectCreationHandling.Replace
});
return config;
}
catch (Exception e)
{
if (!(e is FileNotFoundException))
logger.LogUsefulException(e);
}
}
config = new Configuration();
return config;
}
///
/// Process the loaded configurations and set up things.
///
/// A reference of Configuration object.
public static void Process(ref Configuration config)
{
// Verify if the configured geosite groups exist.
// Reset to default if ANY one of the configured group doesn't exist.
if (!ValidateGeositeGroupList(config.geositeDirectGroups))
ResetGeositeDirectGroup(ref config.geositeDirectGroups);
if (!ValidateGeositeGroupList(config.geositeProxiedGroups))
ResetGeositeProxiedGroup(ref config.geositeProxiedGroups);
// Mark the first run of a new version.
var appVersion = new Version(UpdateChecker.Version);
var configVersion = new Version(config.version);
if (appVersion.CompareTo(configVersion) > 0)
{
config.firstRunOnNewVersion = true;
}
// Add an empty server configuration
if (config.configs.Count == 0)
config.configs.Add(GetDefaultServer());
// Selected server
if (config.index == -1 && string.IsNullOrEmpty(config.strategy))
config.index = 0;
if (config.index >= config.configs.Count)
config.index = config.configs.Count - 1;
// Check OS IPv6 support
if (!System.Net.Sockets.Socket.OSSupportsIPv6)
config.isIPv6Enabled = false;
config.proxy.CheckConfig();
// Replace $version with the version number.
config.userAgentString = config.userAgent.Replace("$version", config.version);
// NLog log level
try
{
config.nLogConfig = NLogConfig.LoadXML();
switch (config.nLogConfig.GetLogLevel())
{
case NLogConfig.LogLevel.Fatal:
case NLogConfig.LogLevel.Error:
case NLogConfig.LogLevel.Warn:
case NLogConfig.LogLevel.Info:
config.isVerboseLogging = false;
break;
case NLogConfig.LogLevel.Debug:
case NLogConfig.LogLevel.Trace:
config.isVerboseLogging = true;
break;
}
}
catch (Exception e)
{
MessageBox.Show($"Cannot get the log level from NLog config file. Please check if the nlog config file exists with corresponding XML nodes.\n{e.Message}");
}
}
///
/// Saves the Configuration object to file.
///
/// A Configuration object.
public static void Save(Configuration config)
{
config.configs = SortByOnlineConfig(config.configs);
FileStream configFileStream = null;
StreamWriter configStreamWriter = null;
try
{
configFileStream = File.Open(CONFIG_FILE, FileMode.Create);
configStreamWriter = new StreamWriter(configFileStream);
var jsonString = JsonConvert.SerializeObject(config, Formatting.Indented);
configStreamWriter.Write(jsonString);
configStreamWriter.Flush();
// NLog
config.nLogConfig.SetLogLevel(config.isVerboseLogging ? verboseLogLevel : NLogConfig.LogLevel.Info);
NLogConfig.SaveXML(config.nLogConfig);
}
catch (Exception e)
{
logger.LogUsefulException(e);
}
finally
{
if (configStreamWriter != null)
configStreamWriter.Dispose();
if (configFileStream != null)
configFileStream.Dispose();
}
}
public static List SortByOnlineConfig(IEnumerable servers)
{
var groups = servers.GroupBy(s => s.group);
List ret = new List();
ret.AddRange(groups.Where(g => string.IsNullOrEmpty(g.Key)).SelectMany(g => g));
ret.AddRange(groups.Where(g => !string.IsNullOrEmpty(g.Key)).SelectMany(g => g));
return ret;
}
///
/// Validates if the groups in the list are all valid.
///
/// The list of groups to validate.
///
/// True if all groups are valid.
/// False if any one of them is invalid.
///
public static bool ValidateGeositeGroupList(List groups)
{
foreach (var geositeGroup in groups)
if (!GeositeUpdater.CheckGeositeGroup(geositeGroup)) // found invalid group
{
#if DEBUG
logger.Debug($"Available groups:");
foreach (var group in GeositeUpdater.Geosites.Keys)
logger.Debug($"{group}");
#endif
logger.Warn($"The Geosite group {geositeGroup} doesn't exist. Resetting to default groups.");
return false;
}
return true;
}
public static void ResetGeositeDirectGroup(ref List geositeDirectGroups)
{
geositeDirectGroups.Clear();
geositeDirectGroups.Add("private");
geositeDirectGroups.Add("cn");
geositeDirectGroups.Add("geolocation-!cn@cn");
}
public static void ResetGeositeProxiedGroup(ref List geositeProxiedGroups)
{
geositeProxiedGroups.Clear();
geositeProxiedGroups.Add("geolocation-!cn");
}
public static void ResetUserAgent(Configuration config)
{
config.userAgent = "ShadowsocksWindows/$version";
config.userAgentString = config.userAgent.Replace("$version", config.version);
}
public static Server AddDefaultServerOrServer(Configuration config, Server server = null, int? index = null)
{
if (config?.configs != null)
{
server = (server ?? GetDefaultServer());
config.configs.Insert(index.GetValueOrDefault(config.configs.Count), server);
//if (index.HasValue)
// config.configs.Insert(index.Value, server);
//else
// config.configs.Add(server);
}
return server;
}
public static Server GetDefaultServer()
{
return new Server();
}
public static void CheckPort(int port)
{
if (port <= 0 || port > 65535)
throw new ArgumentException(I18N.GetString("Port out of range"));
}
public static void CheckLocalPort(int port)
{
CheckPort(port);
if (port == 8123)
throw new ArgumentException(I18N.GetString("Port can't be 8123"));
}
private static void CheckPassword(string password)
{
if (string.IsNullOrEmpty(password))
throw new ArgumentException(I18N.GetString("Password can not be blank"));
}
public static void CheckServer(string server)
{
if (string.IsNullOrEmpty(server))
throw new ArgumentException(I18N.GetString("Server IP can not be blank"));
}
public static void CheckTimeout(int timeout, int maxTimeout)
{
if (timeout <= 0 || timeout > maxTimeout)
throw new ArgumentException(
I18N.GetString("Timeout is invalid, it should not exceed {0}", maxTimeout));
}
}
}
================================================
FILE: shadowsocks-csharp/Model/ForwardProxyConfig.cs
================================================
using System;
namespace Shadowsocks.Model
{
[Serializable]
public class ForwardProxyConfig
{
public const int PROXY_SOCKS5 = 0;
public const int PROXY_HTTP = 1;
public const int MaxProxyTimeoutSec = 10;
private const int DefaultProxyTimeoutSec = 3;
public bool useProxy;
public int proxyType;
public string proxyServer;
public int proxyPort;
public int proxyTimeout;
public bool useAuth;
public string authUser;
public string authPwd;
public ForwardProxyConfig()
{
useProxy = false;
proxyType = PROXY_SOCKS5;
proxyServer = "";
proxyPort = 0;
proxyTimeout = DefaultProxyTimeoutSec;
useAuth = false;
authUser = "";
authPwd = "";
}
public void CheckConfig()
{
if (proxyType < PROXY_SOCKS5 || proxyType > PROXY_HTTP)
{
proxyType = PROXY_SOCKS5;
}
}
}
}
================================================
FILE: shadowsocks-csharp/Model/Geosite/Geosite.cs
================================================
//
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: geosite.proto
//
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
/// Holder for reflection information generated from geosite.proto
public static partial class GeositeReflection {
#region Descriptor
/// File descriptor for geosite.proto
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static GeositeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cg1nZW9zaXRlLnByb3RvIvMBCgxEb21haW5PYmplY3QSIAoEdHlwZRgBIAEo",
"DjISLkRvbWFpbk9iamVjdC5UeXBlEg0KBXZhbHVlGAIgASgJEioKCWF0dHJp",
"YnV0ZRgDIAMoCzIXLkRvbWFpbk9iamVjdC5BdHRyaWJ1dGUaUgoJQXR0cmli",
"dXRlEgsKA2tleRgBIAEoCRIUCgpib29sX3ZhbHVlGAIgASgISAASEwoJaW50",
"X3ZhbHVlGAMgASgDSABCDQoLdHlwZWRfdmFsdWUiMgoEVHlwZRIJCgVQbGFp",
"bhAAEgkKBVJlZ2V4EAESCgoGRG9tYWluEAISCAoERnVsbBADIj0KB0dlb3Np",
"dGUSEgoKZ3JvdXBfbmFtZRgBIAEoCRIeCgdkb21haW5zGAIgAygLMg0uRG9t",
"YWluT2JqZWN0IigKC0dlb3NpdGVMaXN0EhkKB2VudHJpZXMYASADKAsyCC5H",
"ZW9zaXRlYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::DomainObject), global::DomainObject.Parser, new[]{ "Type", "Value", "Attribute" }, null, new[]{ typeof(global::DomainObject.Types.Type) }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::DomainObject.Types.Attribute), global::DomainObject.Types.Attribute.Parser, new[]{ "Key", "BoolValue", "IntValue" }, new[]{ "TypedValue" }, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Geosite), global::Geosite.Parser, new[]{ "GroupName", "Domains" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::GeositeList), global::GeositeList.Parser, new[]{ "Entries" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
///
/// DomainObject for routing decision.
///
public sealed partial class DomainObject : pb::IMessage {
private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DomainObject());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::GeositeReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DomainObject() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DomainObject(DomainObject other) : this() {
type_ = other.type_;
value_ = other.value_;
attribute_ = other.attribute_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DomainObject Clone() {
return new DomainObject(this);
}
/// Field number for the "type" field.
public const int TypeFieldNumber = 1;
private global::DomainObject.Types.Type type_ = global::DomainObject.Types.Type.Plain;
///
/// DomainObject matching type.
///
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::DomainObject.Types.Type Type {
get { return type_; }
set {
type_ = value;
}
}
/// Field number for the "value" field.
public const int ValueFieldNumber = 2;
private string value_ = "";
///
/// DomainObject value.
///
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Value {
get { return value_; }
set {
value_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// Field number for the "attribute" field.
public const int AttributeFieldNumber = 3;
private static readonly pb::FieldCodec _repeated_attribute_codec
= pb::FieldCodec.ForMessage(26, global::DomainObject.Types.Attribute.Parser);
private readonly pbc::RepeatedField attribute_ = new pbc::RepeatedField();
///
/// Attributes of this domain. May be used for filtering.
///
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField Attribute {
get { return attribute_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DomainObject);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DomainObject other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Type != other.Type) return false;
if (Value != other.Value) return false;
if(!attribute_.Equals(other.attribute_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Type != global::DomainObject.Types.Type.Plain) hash ^= Type.GetHashCode();
if (Value.Length != 0) hash ^= Value.GetHashCode();
hash ^= attribute_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Type != global::DomainObject.Types.Type.Plain) {
output.WriteRawTag(8);
output.WriteEnum((int) Type);
}
if (Value.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Value);
}
attribute_.WriteTo(output, _repeated_attribute_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Type != global::DomainObject.Types.Type.Plain) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
}
if (Value.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Value);
}
size += attribute_.CalculateSize(_repeated_attribute_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DomainObject other) {
if (other == null) {
return;
}
if (other.Type != global::DomainObject.Types.Type.Plain) {
Type = other.Type;
}
if (other.Value.Length != 0) {
Value = other.Value;
}
attribute_.Add(other.attribute_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Type = (global::DomainObject.Types.Type) input.ReadEnum();
break;
}
case 18: {
Value = input.ReadString();
break;
}
case 26: {
attribute_.AddEntriesFrom(input, _repeated_attribute_codec);
break;
}
}
}
}
#region Nested types
/// Container for nested types declared in the DomainObject message type.
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
///
/// Type of domain value.
///
public enum Type {
///
/// The value is used as is.
///
[pbr::OriginalName("Plain")] Plain = 0,
///
/// The value is used as a regular expression.
///
[pbr::OriginalName("Regex")] Regex = 1,
///
/// The value is a root domain.
///
[pbr::OriginalName("Domain")] Domain = 2,
///
/// The value is a domain.
///
[pbr::OriginalName("Full")] Full = 3,
}
public sealed partial class Attribute : pb::IMessage {
private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Attribute());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::DomainObject.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Attribute() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Attribute(Attribute other) : this() {
key_ = other.key_;
switch (other.TypedValueCase) {
case TypedValueOneofCase.BoolValue:
BoolValue = other.BoolValue;
break;
case TypedValueOneofCase.IntValue:
IntValue = other.IntValue;
break;
}
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Attribute Clone() {
return new Attribute(this);
}
/// Field number for the "key" field.
public const int KeyFieldNumber = 1;
private string key_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Key {
get { return key_; }
set {
key_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// Field number for the "bool_value" field.
public const int BoolValueFieldNumber = 2;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool BoolValue {
get { return typedValueCase_ == TypedValueOneofCase.BoolValue ? (bool) typedValue_ : false; }
set {
typedValue_ = value;
typedValueCase_ = TypedValueOneofCase.BoolValue;
}
}
/// Field number for the "int_value" field.
public const int IntValueFieldNumber = 3;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long IntValue {
get { return typedValueCase_ == TypedValueOneofCase.IntValue ? (long) typedValue_ : 0L; }
set {
typedValue_ = value;
typedValueCase_ = TypedValueOneofCase.IntValue;
}
}
private object typedValue_;
/// Enum of possible cases for the "typed_value" oneof.
public enum TypedValueOneofCase {
None = 0,
BoolValue = 2,
IntValue = 3,
}
private TypedValueOneofCase typedValueCase_ = TypedValueOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TypedValueOneofCase TypedValueCase {
get { return typedValueCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearTypedValue() {
typedValueCase_ = TypedValueOneofCase.None;
typedValue_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Attribute);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Attribute other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Key != other.Key) return false;
if (BoolValue != other.BoolValue) return false;
if (IntValue != other.IntValue) return false;
if (TypedValueCase != other.TypedValueCase) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Key.Length != 0) hash ^= Key.GetHashCode();
if (typedValueCase_ == TypedValueOneofCase.BoolValue) hash ^= BoolValue.GetHashCode();
if (typedValueCase_ == TypedValueOneofCase.IntValue) hash ^= IntValue.GetHashCode();
hash ^= (int) typedValueCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Key.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Key);
}
if (typedValueCase_ == TypedValueOneofCase.BoolValue) {
output.WriteRawTag(16);
output.WriteBool(BoolValue);
}
if (typedValueCase_ == TypedValueOneofCase.IntValue) {
output.WriteRawTag(24);
output.WriteInt64(IntValue);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Key.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Key);
}
if (typedValueCase_ == TypedValueOneofCase.BoolValue) {
size += 1 + 1;
}
if (typedValueCase_ == TypedValueOneofCase.IntValue) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(IntValue);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Attribute other) {
if (other == null) {
return;
}
if (other.Key.Length != 0) {
Key = other.Key;
}
switch (other.TypedValueCase) {
case TypedValueOneofCase.BoolValue:
BoolValue = other.BoolValue;
break;
case TypedValueOneofCase.IntValue:
IntValue = other.IntValue;
break;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Key = input.ReadString();
break;
}
case 16: {
BoolValue = input.ReadBool();
break;
}
case 24: {
IntValue = input.ReadInt64();
break;
}
}
}
}
}
}
#endregion
}
public sealed partial class Geosite : pb::IMessage {
private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Geosite());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::GeositeReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Geosite() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Geosite(Geosite other) : this() {
groupName_ = other.groupName_;
domains_ = other.domains_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Geosite Clone() {
return new Geosite(this);
}
/// Field number for the "group_name" field.
public const int GroupNameFieldNumber = 1;
private string groupName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GroupName {
get { return groupName_; }
set {
groupName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// Field number for the "domains" field.
public const int DomainsFieldNumber = 2;
private static readonly pb::FieldCodec _repeated_domains_codec
= pb::FieldCodec.ForMessage(18, global::DomainObject.Parser);
private readonly pbc::RepeatedField domains_ = new pbc::RepeatedField();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField Domains {
get { return domains_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Geosite);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Geosite other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (GroupName != other.GroupName) return false;
if(!domains_.Equals(other.domains_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (GroupName.Length != 0) hash ^= GroupName.GetHashCode();
hash ^= domains_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (GroupName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(GroupName);
}
domains_.WriteTo(output, _repeated_domains_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (GroupName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GroupName);
}
size += domains_.CalculateSize(_repeated_domains_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Geosite other) {
if (other == null) {
return;
}
if (other.GroupName.Length != 0) {
GroupName = other.GroupName;
}
domains_.Add(other.domains_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
GroupName = input.ReadString();
break;
}
case 18: {
domains_.AddEntriesFrom(input, _repeated_domains_codec);
break;
}
}
}
}
}
public sealed partial class GeositeList : pb::IMessage {
private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new GeositeList());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::GeositeReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GeositeList() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GeositeList(GeositeList other) : this() {
entries_ = other.entries_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GeositeList Clone() {
return new GeositeList(this);
}
/// Field number for the "entries" field.
public const int EntriesFieldNumber = 1;
private static readonly pb::FieldCodec _repeated_entries_codec
= pb::FieldCodec.ForMessage(10, global::Geosite.Parser);
private readonly pbc::RepeatedField entries_ = new pbc::RepeatedField();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField Entries {
get { return entries_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GeositeList);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GeositeList other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!entries_.Equals(other.entries_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= entries_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
entries_.WriteTo(output, _repeated_entries_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += entries_.CalculateSize(_repeated_entries_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GeositeList other) {
if (other == null) {
return;
}
entries_.Add(other.entries_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
entries_.AddEntriesFrom(input, _repeated_entries_codec);
break;
}
}
}
}
}
#endregion
#endregion Designer generated code
================================================
FILE: shadowsocks-csharp/Model/Geosite/geosite.proto
================================================
syntax = "proto3";
// DomainObject for routing decision.
message DomainObject {
// Type of domain value.
enum Type {
// The value is used as is.
Plain = 0;
// The value is used as a regular expression.
Regex = 1;
// The value is a root domain.
Domain = 2;
// The value is a domain.
Full = 3;
}
// DomainObject matching type.
Type type = 1;
// DomainObject value.
string value = 2;
message Attribute {
string key = 1;
oneof typed_value {
bool bool_value = 2;
int64 int_value = 3;
}
}
// Attributes of this domain. May be used for filtering.
repeated Attribute attribute = 3;
}
message Geosite {
string group_name = 1;
repeated DomainObject domains = 2;
}
message GeositeList{
repeated Geosite entries = 1;
}
================================================
FILE: shadowsocks-csharp/Model/HotKeyConfig.cs
================================================
using System;
namespace Shadowsocks.Model
{
/*
* Format:
* +
*
*/
[Serializable]
public class HotkeyConfig
{
public string SwitchSystemProxy;
public string SwitchSystemProxyMode;
public string SwitchAllowLan;
public string ShowLogs;
public string ServerMoveUp;
public string ServerMoveDown;
public bool RegHotkeysAtStartup;
public HotkeyConfig()
{
SwitchSystemProxy = "";
SwitchSystemProxyMode = "";
SwitchAllowLan = "";
ShowLogs = "";
ServerMoveUp = "";
ServerMoveDown = "";
RegHotkeysAtStartup = false;
}
}
}
================================================
FILE: shadowsocks-csharp/Model/LogViewerConfig.cs
================================================
using System;
using System.Drawing;
using System.Windows.Forms;
using Newtonsoft.Json;
namespace Shadowsocks.Model
{
[Serializable]
public class LogViewerConfig
{
public bool topMost;
public bool wrapText;
public bool toolbarShown;
public Font Font { get; set; } = new Font("Consolas", 8F);
public Color BackgroundColor { get; set; } = Color.Black;
public Color TextColor { get; set; } = Color.White;
public LogViewerConfig()
{
topMost = false;
wrapText = false;
toolbarShown = false;
}
#region Size
public void SaveSize()
{
Properties.Settings.Default.Save();
}
[JsonIgnore]
public int Width
{
get { return Properties.Settings.Default.LogViewerWidth; }
set { Properties.Settings.Default.LogViewerWidth = value; }
}
[JsonIgnore]
public int Height
{
get { return Properties.Settings.Default.LogViewerHeight; }
set { Properties.Settings.Default.LogViewerHeight = value; }
}
[JsonIgnore]
public int Top
{
get { return Properties.Settings.Default.LogViewerTop; }
set { Properties.Settings.Default.LogViewerTop = value; }
}
[JsonIgnore]
public int Left
{
get { return Properties.Settings.Default.LogViewerLeft; }
set { Properties.Settings.Default.LogViewerLeft = value; }
}
[JsonIgnore]
public bool Maximized
{
get { return Properties.Settings.Default.LogViewerMaximized; }
set { Properties.Settings.Default.LogViewerMaximized = value; }
}
[JsonIgnore]
// Use GetBestTop() and GetBestLeft() to ensure the log viwer form can be always display IN screen.
public int BestLeft
{
get
{
int width = Width;
width = (width >= 400) ? width : 400; // set up the minimum size
return Screen.PrimaryScreen.WorkingArea.Width - width;
}
}
[JsonIgnore]
public int BestTop
{
get
{
int height = Height;
height = (height >= 200) ? height : 200; // set up the minimum size
return Screen.PrimaryScreen.WorkingArea.Height - height;
}
}
#endregion
}
}
================================================
FILE: shadowsocks-csharp/Model/NlogConfig.cs
================================================
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Shadowsocks.Model
{
public class NLogConfig
{
public enum LogLevel
{
Fatal,
Error,
Warn,
Info,
Debug,
Trace,
}
const string NLOG_CONFIG_FILE_NAME = "NLog.config";
const string TARGET_MIN_LEVEL_ATTRIBUTE = "minlevel";
const string LOGGER_FILE_NAME_ATTRIBUTE = "fileName";
XmlDocument doc = new XmlDocument();
XmlElement logFileNameElement;
XmlElement logLevelElement;
///
/// Load the NLog config xml file content
///
public static NLogConfig LoadXML()
{
NLogConfig config = new NLogConfig();
config.doc.Load(NLOG_CONFIG_FILE_NAME);
config.logLevelElement = (XmlElement)SelectSingleNode(config.doc, "//nlog:logger[@name='*']");
config.logFileNameElement = (XmlElement)SelectSingleNode(config.doc, "//nlog:target[@name='file']");
return config;
}
///
/// Save the content to NLog config xml file
///
public static void SaveXML(NLogConfig nLogConfig)
{
nLogConfig.doc.Save(NLOG_CONFIG_FILE_NAME);
}
///
/// Get the current minLogLevel from xml file
///
///
public LogLevel GetLogLevel()
{
LogLevel level = LogLevel.Warn;
string levelStr = logLevelElement.GetAttribute(TARGET_MIN_LEVEL_ATTRIBUTE);
Enum.TryParse(levelStr, out level);
return level;
}
///
/// Get the target fileName from xml file
///
///
public string GetLogFileName()
{
return logFileNameElement.GetAttribute(LOGGER_FILE_NAME_ATTRIBUTE);
}
///
/// Set the minLogLevel to xml file
///
///
public void SetLogLevel(LogLevel logLevel)
{
logLevelElement.SetAttribute(TARGET_MIN_LEVEL_ATTRIBUTE, logLevel.ToString("G"));
}
///
/// Set the target fileName to xml file
///
///
public void SetLogFileName(string fileName)
{
logFileNameElement.SetAttribute(LOGGER_FILE_NAME_ATTRIBUTE, fileName);
}
///
/// Select a single XML node/elemant
///
///
///
///
private static XmlNode SelectSingleNode(XmlDocument doc, string xpath)
{
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("nlog", "http://www.nlog-project.org/schemas/NLog.xsd");
//return doc.SelectSingleNode("//nlog:logger[(@shadowsocks='managed') and (@name='*')]", manager);
return doc.SelectSingleNode(xpath, manager);
}
///
/// Extract the pre-defined NLog configuration file is does not exist. Then reload the Nlog configuration.
///
public static void TouchAndApplyNLogConfig()
{
try
{
if (File.Exists(NLOG_CONFIG_FILE_NAME))
return; // NLog.config exists, and has already been loaded
File.WriteAllText(NLOG_CONFIG_FILE_NAME, Properties.Resources.NLog_config);
}
catch (Exception ex)
{
NLog.Common.InternalLogger.Error(ex, "[shadowsocks] Failed to setup default NLog.config: {0}", NLOG_CONFIG_FILE_NAME);
return;
}
LoadConfiguration(); // Load the new config-file
}
///
/// NLog reload the config file and apply to current LogManager
///
public static void LoadConfiguration()
{
LogManager.LoadConfiguration(NLOG_CONFIG_FILE_NAME);
}
}
}
================================================
FILE: shadowsocks-csharp/Model/Server.cs
================================================
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using Shadowsocks.Controller;
using System.Text.RegularExpressions;
using System.Linq;
using Newtonsoft.Json;
using System.ComponentModel;
namespace Shadowsocks.Model
{
[Serializable]
public class Server
{
public const string DefaultMethod = "chacha20-ietf-poly1305";
public const int DefaultPort = 8388;
#region ParseLegacyURL
private static readonly Regex UrlFinder = new Regex(@"ss://(?[A-Za-z0-9+-/=_]+)(?:#(?\S+))?", RegexOptions.IgnoreCase);
private static readonly Regex DetailsParser = new Regex(@"^((?.+?):(?.*)@(?.+?):(?\d+?))$", RegexOptions.IgnoreCase);
#endregion ParseLegacyURL
private const int DefaultServerTimeoutSec = 5;
public const int MaxServerTimeoutSec = 20;
public string server;
public int server_port;
public string password;
public string method;
// optional fields
[DefaultValue("")]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public string plugin;
[DefaultValue("")]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public string plugin_opts;
[DefaultValue("")]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public string plugin_args;
[DefaultValue("")]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public string remarks;
[DefaultValue("")]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public string group;
public int timeout;
// Set to true when imported from a legacy ss:// URL.
public bool warnLegacyUrl;
public override int GetHashCode()
{
return server.GetHashCode() ^ server_port;
}
public override bool Equals(object obj) => obj is Server o2 && server == o2.server && server_port == o2.server_port;
public override string ToString()
{
if (string.IsNullOrEmpty(server))
{
return I18N.GetString("New server");
}
string serverStr = $"{FormalHostName}:{server_port}";
return string.IsNullOrEmpty(remarks)
? serverStr
: $"{remarks} ({serverStr})";
}
public string GetURL(bool legacyUrl = false)
{
string tag = string.Empty;
string url = string.Empty;
if (legacyUrl && string.IsNullOrWhiteSpace(plugin))
{
// For backwards compatiblity, if no plugin, use old url format
string parts = $"{method}:{password}@{server}:{server_port}";
string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
url = base64;
}
else
{
// SIP002
string parts = $"{method}:{password}";
string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
string websafeBase64 = base64.Replace('+', '-').Replace('/', '_').TrimEnd('=');
url = string.Format(
"{0}@{1}:{2}/",
websafeBase64,
FormalHostName,
server_port
);
if (!string.IsNullOrWhiteSpace(plugin))
{
string pluginPart = plugin;
if (!string.IsNullOrWhiteSpace(plugin_opts))
{
pluginPart += ";" + plugin_opts;
}
string pluginQuery = "?plugin=" + HttpUtility.UrlEncode(pluginPart, Encoding.UTF8);
url += pluginQuery;
}
}
if (!string.IsNullOrEmpty(remarks))
{
tag = $"#{HttpUtility.UrlEncode(remarks, Encoding.UTF8)}";
}
return $"ss://{url}{tag}";
}
[JsonIgnore]
public string FormalHostName
{
get
{
// CheckHostName() won't do a real DNS lookup
switch (Uri.CheckHostName(server))
{
case UriHostNameType.IPv6: // Add square bracket when IPv6 (RFC3986)
return $"[{server}]";
default: // IPv4 or domain name
return server;
}
}
}
public Server()
{
server = "";
server_port = DefaultPort;
method = DefaultMethod;
plugin = "";
plugin_opts = "";
plugin_args = "";
password = "";
remarks = "";
timeout = DefaultServerTimeoutSec;
}
private static Server ParseLegacyURL(string ssURL)
{
var match = UrlFinder.Match(ssURL);
if (!match.Success)
return null;
Server server = new Server();
var base64 = match.Groups["base64"].Value.TrimEnd('/');
var tag = match.Groups["tag"].Value;
if (!string.IsNullOrEmpty(tag))
{
server.remarks = HttpUtility.UrlDecode(tag, Encoding.UTF8);
}
Match details = null;
try
{
details = DetailsParser.Match(Encoding.UTF8.GetString(Convert.FromBase64String(
base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '='))));
}
catch (FormatException)
{
return null;
}
if (!details.Success)
return null;
server.method = details.Groups["method"].Value;
server.password = details.Groups["password"].Value;
server.server = details.Groups["hostname"].Value;
server.server_port = int.Parse(details.Groups["port"].Value);
server.warnLegacyUrl = true;
return server;
}
public static Server ParseURL(string serverUrl)
{
string _serverUrl = serverUrl.Trim();
if (!_serverUrl.StartsWith("ss://", StringComparison.InvariantCultureIgnoreCase))
{
return null;
}
Server legacyServer = ParseLegacyURL(serverUrl);
if (legacyServer != null) //legacy
{
return legacyServer;
}
else //SIP002
{
Uri parsedUrl;
try
{
parsedUrl = new Uri(serverUrl);
}
catch (UriFormatException)
{
return null;
}
Server server = new Server
{
remarks = HttpUtility.UrlDecode(parsedUrl.GetComponents(
UriComponents.Fragment, UriFormat.Unescaped), Encoding.UTF8),
server = parsedUrl.IdnHost,
server_port = parsedUrl.Port,
};
// parse base64 UserInfo
string rawUserInfo = parsedUrl.GetComponents(UriComponents.UserInfo, UriFormat.Unescaped);
string base64 = rawUserInfo.Replace('-', '+').Replace('_', '/'); // Web-safe base64 to normal base64
string userInfo = "";
try
{
userInfo = Encoding.UTF8.GetString(Convert.FromBase64String(
base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=')));
}
catch (FormatException)
{
return null;
}
string[] userInfoParts = userInfo.Split(new char[] { ':' }, 2);
if (userInfoParts.Length != 2)
{
return null;
}
server.method = userInfoParts[0];
server.password = userInfoParts[1];
NameValueCollection queryParameters = HttpUtility.ParseQueryString(parsedUrl.Query);
string[] pluginParts = (queryParameters["plugin"] ?? "").Split(new[] { ';' }, 2);
if (pluginParts.Length > 0)
{
server.plugin = pluginParts[0] ?? "";
}
if (pluginParts.Length > 1)
{
server.plugin_opts = pluginParts[1] ?? "";
}
return server;
}
}
public static List GetServers(string ssURL)
{
return ssURL
.Split('\r', '\n', ' ')
.Select(u => ParseURL(u))
.Where(s => s != null)
.ToList();
}
public string Identifier()
{
return server + ':' + server_port;
}
}
}
================================================
FILE: shadowsocks-csharp/Model/SysproxyConfig.cs
================================================
using System;
namespace Shadowsocks.Model
{
/*
* Data come from WinINET
*/
[Serializable]
public class SysproxyConfig
{
public bool UserSettingsRecorded;
public string Flags;
public string ProxyServer;
public string BypassList;
public string PacUrl;
public SysproxyConfig()
{
UserSettingsRecorded = false;
Flags = "1";
// Watchout, Nullable! See #2100
ProxyServer = "";
BypassList = "";
PacUrl = "";
}
}
}
================================================
FILE: shadowsocks-csharp/Program.cs
================================================
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CommandLine;
using Microsoft.Win32;
using NLog;
using ReactiveUI;
using Shadowsocks.Controller;
using Shadowsocks.Controller.Hotkeys;
using Shadowsocks.Util;
using Shadowsocks.View;
using Splat;
using WPFLocalizeExtension.Engine;
namespace Shadowsocks
{
internal static class Program
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public static ShadowsocksController MainController { get; private set; }
public static MenuViewController MenuController { get; private set; }
public static CommandLineOption Options { get; private set; }
public static string[] Args { get; private set; }
// https://github.com/dotnet/runtime/issues/13051#issuecomment-510267727
public static readonly string ExecutablePath = Process.GetCurrentProcess().MainModule?.FileName;
public static readonly string WorkingDirectory = Path.GetDirectoryName(ExecutablePath);
private static readonly Mutex mutex = new Mutex(true, $"Shadowsocks_{ExecutablePath.GetHashCode()}");
///
/// 应用程序的主入口点。
///
///
[STAThread]
private static void Main(string[] args)
{
#region Single Instance and IPC
bool hasAnotherInstance = !mutex.WaitOne(TimeSpan.Zero, true);
// store args for further use
Args = args;
Parser.Default.ParseArguments(args)
.WithParsed(opt => Options = opt)
.WithNotParsed(e => e.Output());
if (hasAnotherInstance)
{
if (!string.IsNullOrWhiteSpace(Options.OpenUrl))
{
IPCService.RequestOpenUrl(Options.OpenUrl);
}
else
{
MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
+ Environment.NewLine
+ I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
I18N.GetString("Shadowsocks is already running."));
}
return;
}
#endregion
#region Enviroment Setup
Directory.SetCurrentDirectory(WorkingDirectory);
// todo: initialize the NLog configuartion
Model.NLogConfig.TouchAndApplyNLogConfig();
// .NET Framework 4.7.2 on Win7 compatibility
ServicePointManager.SecurityProtocol |=
SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
#endregion
#region Compactibility Check
// Check OS since we are using dual-mode socket
if (!Utils.IsWinVistaOrHigher())
{
MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
"Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Check .NET Framework version
if (!Utils.IsSupportedRuntimeVersion())
{
if (DialogResult.OK == MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to {0} or later.", "4.8"),
"Shadowsocks Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error))
{
Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net48");
}
return;
}
#endregion
#region Event Handlers Setup
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// handle UI exceptions
Application.ThreadException += Application_ThreadException;
// handle non-UI exceptions
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.ApplicationExit += Application_ApplicationExit;
SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AutoStartup.RegisterForRestart(true);
#endregion
// We would use this in v5.
// Parameters would have to be dropped from views' constructors (VersionUpdatePromptView)
//Locator.CurrentMutable.RegisterViewsForViewModels(Assembly.GetCallingAssembly());
// Workaround for hosting WPF controls in a WinForms app.
// We have to manually set the culture for the LocalizeDictionary instance.
// https://stackoverflow.com/questions/374518/localizing-a-winforms-application-with-embedded-wpf-user-controls
// https://stackoverflow.com/questions/14668640/wpf-localize-extension-translate-window-at-run-time
LocalizeDictionary.Instance.Culture = Thread.CurrentThread.CurrentCulture;
#if DEBUG
// truncate privoxy log file while debugging
string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
if (File.Exists(privoxyLogFilename))
using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
#endif
MainController = new ShadowsocksController();
MenuController = new MenuViewController(MainController);
HotKeys.Init(MainController);
MainController.Start();
// Update online config
Task.Run(async () =>
{
await Task.Delay(10 * 1000);
await MainController.UpdateAllOnlineConfig();
});
#region IPC Handler and Arguement Process
IPCService ipcService = new IPCService();
Task.Run(() => ipcService.RunServer());
ipcService.OpenUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url);
if (!string.IsNullOrWhiteSpace(Options.OpenUrl))
{
MainController.AskAddServerBySSURL(Options.OpenUrl);
}
#endregion
Application.Run();
}
private static int exited = 0;
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (Interlocked.Increment(ref exited) == 1)
{
string errMsg = e.ExceptionObject.ToString();
logger.Error(errMsg);
MessageBox.Show(
$"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errMsg}",
"Shadowsocks non-UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
if (Interlocked.Increment(ref exited) == 1)
{
string errorMsg = $"Exception Detail: {Environment.NewLine}{e.Exception}";
logger.Error(errorMsg);
MessageBox.Show(
$"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errorMsg}",
"Shadowsocks UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
}
private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
switch (e.Mode)
{
case PowerModes.Resume:
logger.Info("os wake up");
if (MainController != null)
{
Task.Factory.StartNew(() =>
{
Thread.Sleep(10 * 1000);
try
{
MainController.Start(true);
logger.Info("controller started");
}
catch (Exception ex)
{
logger.LogUsefulException(ex);
}
});
}
break;
case PowerModes.Suspend:
if (MainController != null)
{
MainController.Stop();
logger.Info("controller stopped");
}
logger.Info("os suspend");
break;
}
}
private static void Application_ApplicationExit(object sender, EventArgs e)
{
// detach static event handlers
Application.ApplicationExit -= Application_ApplicationExit;
SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
Application.ThreadException -= Application_ThreadException;
HotKeys.Destroy();
if (MainController != null)
{
MainController.Stop();
MainController = null;
}
}
}
}
================================================
FILE: shadowsocks-csharp/Properties/AssemblyInfo.cs
================================================
using Shadowsocks.Controller;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过下列属性集
// 控制。更改这些属性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Shadowsocks")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Shadowsocks")]
[assembly: AssemblyCopyright("clowwindy & community 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 属性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("f8334709-4309-436a-8bbd-6165dcf4a660")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion(UpdateChecker.Version)]
// [assembly: AssemblyFileVersion("2.0.0")]
================================================
FILE: shadowsocks-csharp/Properties/Resources.Designer.cs
================================================
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
namespace Shadowsocks.Properties {
using System;
///
/// A strongly-typed resource class, for looking up localized strings, etc.
///
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
///
/// Returns the cached ResourceManager instance used by this class.
///
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Shadowsocks.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
///
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
///
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
///
/// Looks up a localized string similar to /* eslint-disable */
///// Was generated by gfwlist2pac in precise mode
///// https://github.com/clowwindy/gfwlist2pac
///
///// 2019-10-06: More 'javascript' way to interaction with main program
///// 2019-02-08: Updated to support shadowsocks-windows user rules.
///
///var proxy = __PROXY__;
///var userrules = [];
///var rules = [];
///
///// convert to abp grammar
///var re = /^(@@)?\|\|.*?[^\^]$/;
///for (var i = 0; i < __RULES__.length; i++) {
/// var s = __RULES__[i];
/// if (s.match(re)) s += "^";
/// rules.push(s);
///}
///
/// [rest of string was truncated]";.
///
public static string abp_js {
get {
return ResourceManager.GetString("abp_js", resourceCulture);
}
}
///
/// Looks up a localized resource of type System.Byte[].
///
public static byte[] dlc_dat {
get {
object obj = ResourceManager.GetObject("dlc_dat", resourceCulture);
return ((byte[])(obj));
}
}
///
/// Looks up a localized string similar to en,ru-RU,zh-CN,zh-TW,ja,ko,fr
///#Restart program to apply translation,,,,,,
///#This is comment line,,,,,,
///#Always keep language name at head of file,,,,,,
///#Language name is output in log,,,,,,
///"#You can find it by search ""Current language is:""",,,,,,
///#Please use UTF-8 with BOM encoding so we can edit it in Excel,,,,,,
///,,,,,,
///Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks
///,,,,,,
///#Menu,,,,,,
///,,,,,,
///System Proxy,Системный прокси-сервер,系统代理,系統代理,システムプロキシ,시스템 프록시,P [rest of string was truncated]";.
///
public static string i18n_csv {
get {
return ResourceManager.GetString("i18n_csv", resourceCulture);
}
}
///
/// Looks up a localized resource of type System.Byte[].
///
public static byte[] libsscrypto_dll {
get {
object obj = ResourceManager.GetObject("libsscrypto_dll", resourceCulture);
return ((byte[])(obj));
}
}
///
/// Looks up a localized string similar to <?xml version="1.0" encoding="utf-8" ?>
///<!-- Warning: Configuration may reset after shadowsocks upgrade. -->
///<!-- If you messed it up, delete this file and Shadowsocks will create a new one. -->
///<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
/// <targets>
/// <!-- This line is managed by Shadowsocks. Do not modify it unless you know what you are doing.-->
/// <target name="file" xsi:type="File" fileName="ss_win_temp\shadowsocks.log" writ [rest of string was truncated]";.
///
public static string NLog_config {
get {
return ResourceManager.GetString("NLog_config", resourceCulture);
}
}
///
/// Looks up a localized string similar to listen-address __PRIVOXY_BIND_IP__:__PRIVOXY_BIND_PORT__
///toggle 0
///logfile ss_privoxy.log
///show-on-task-bar 0
///activity-animation 0
///forward-socks5 / __SOCKS_HOST__:__SOCKS_PORT__ .
///max-client-connections 2048
///hide-console
///.
///
public static string privoxy_conf {
get {
return ResourceManager.GetString("privoxy_conf", resourceCulture);
}
}
///
/// Looks up a localized resource of type System.Byte[].
///
public static byte[] privoxy_exe {
get {
object obj = ResourceManager.GetObject("privoxy_exe", resourceCulture);
return ((byte[])(obj));
}
}
///
/// Looks up a localized resource of type System.Drawing.Bitmap.
///
public static System.Drawing.Bitmap ss32Fill {
get {
object obj = ResourceManager.GetObject("ss32Fill", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
///
/// Looks up a localized resource of type System.Drawing.Bitmap.
///
public static System.Drawing.Bitmap ss32In {
get {
object obj = ResourceManager.GetObject("ss32In", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
///
/// Looks up a localized resource of type System.Drawing.Bitmap.
///
public static System.Drawing.Bitmap ss32Out {
get {
object obj = ResourceManager.GetObject("ss32Out", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
///
/// Looks up a localized resource of type System.Drawing.Bitmap.
///
public static System.Drawing.Bitmap ss32Outline {
get {
object obj = ResourceManager.GetObject("ss32Outline", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
///
/// Looks up a localized resource of type System.Drawing.Bitmap.
///
public static System.Drawing.Bitmap ssw128 {
get {
object obj = ResourceManager.GetObject("ssw128", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
///
/// Looks up a localized resource of type System.Byte[].
///
public static byte[] sysproxy_exe {
get {
object obj = ResourceManager.GetObject("sysproxy_exe", resourceCulture);
return ((byte[])(obj));
}
}
///
/// Looks up a localized resource of type System.Byte[].
///
public static byte[] sysproxy64_exe {
get {
object obj = ResourceManager.GetObject("sysproxy64_exe", resourceCulture);
return ((byte[])(obj));
}
}
///
/// Looks up a localized string similar to ! Put user rules line by line in this file.
///! See https://adblockplus.org/en/filter-cheatsheet
///.
///
public static string user_rule {
get {
return ResourceManager.GetString("user_rule", resourceCulture);
}
}
}
}
================================================
FILE: shadowsocks-csharp/Properties/Resources.resx
================================================
text/microsoft-resx
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
..\Data\abp.js;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;gb2312
..\data\dlc.dat;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
..\Data\i18n.csv;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8
..\Data\libsscrypto.dll.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
..\data\nlog.config;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8
..\data\privoxy_conf.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8
..\data\privoxy.exe.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
..\Resources\ss32Fill.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
..\Resources\ss32In.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
..\Resources\ss32Out.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
..\Resources\ss32Outline.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
..\Resources\ssw128.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
..\Data\sysproxy64.exe.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
..\Data\sysproxy.exe.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
..\data\user-rule.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8
================================================
FILE: shadowsocks-csharp/Properties/Settings.Designer.cs
================================================
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
namespace Shadowsocks.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("600")]
public int LogViewerWidth {
get {
return ((int)(this["LogViewerWidth"]));
}
set {
this["LogViewerWidth"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("400")]
public int LogViewerHeight {
get {
return ((int)(this["LogViewerHeight"]));
}
set {
this["LogViewerHeight"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool LogViewerMaximized {
get {
return ((bool)(this["LogViewerMaximized"]));
}
set {
this["LogViewerMaximized"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("0")]
public int LogViewerTop {
get {
return ((int)(this["LogViewerTop"]));
}
set {
this["LogViewerTop"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("0")]
public int LogViewerLeft {
get {
return ((int)(this["LogViewerLeft"]));
}
set {
this["LogViewerLeft"] = value;
}
}
}
}
================================================
FILE: shadowsocks-csharp/Properties/Settings.settings
================================================
600
400
True
0
0
================================================
FILE: shadowsocks-csharp/Proxy/DirectConnect.cs
================================================
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Shadowsocks.Util.Sockets;
namespace Shadowsocks.Proxy
{
public class DirectConnect : IProxy
{
private class FakeAsyncResult : IAsyncResult
{
public FakeAsyncResult(object state)
{
AsyncState = state;
}
public bool IsCompleted { get; } = true;
public WaitHandle AsyncWaitHandle { get; } = null;
public object AsyncState { get; }
public bool CompletedSynchronously { get; } = true;
}
private class FakeEndPoint : EndPoint
{
public override AddressFamily AddressFamily { get; } = AddressFamily.Unspecified;
public override string ToString()
{
return "null proxy";
}
}
private WrappedSocket _remote = new WrappedSocket();
public EndPoint LocalEndPoint => _remote.LocalEndPoint;
public EndPoint ProxyEndPoint { get; } = new FakeEndPoint();
public EndPoint DestEndPoint { get; private set; }
public void BeginConnectProxy(EndPoint remoteEP, AsyncCallback callback, object state)
{
// do nothing
var r = new FakeAsyncResult(state);
callback?.Invoke(r);
}
public void EndConnectProxy(IAsyncResult asyncResult)
{
// do nothing
}
public void BeginConnectDest(EndPoint destEndPoint, AsyncCallback callback, object state, NetworkCredential auth = null)
{
DestEndPoint = destEndPoint;
_remote.BeginConnect(destEndPoint, callback, state);
}
public void EndConnectDest(IAsyncResult asyncResult)
{
_remote.EndConnect(asyncResult);
_remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
}
public void BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,
object state)
{
_remote.BeginSend(buffer, offset, size, socketFlags, callback, state);
}
public int EndSend(IAsyncResult asyncResult)
{
return _remote.EndSend(asyncResult);
}
public void BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,
object state)
{
_remote.BeginReceive(buffer, offset, size, socketFlags, callback, state);
}
public int EndReceive(IAsyncResult asyncResult)
{
return _remote.EndReceive(asyncResult);
}
public void Shutdown(SocketShutdown how)
{
_remote.Shutdown(how);
}
public void Close()
{
_remote.Dispose();
}
}
}
================================================
FILE: shadowsocks-csharp/Proxy/HttpProxy.cs
================================================
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NLog;
using Shadowsocks.Controller;
using Shadowsocks.Util.Sockets;
namespace Shadowsocks.Proxy
{
public class HttpProxy : IProxy
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private class FakeAsyncResult : IAsyncResult
{
public readonly HttpState innerState;
private readonly IAsyncResult r;
public FakeAsyncResult(IAsyncResult orig, HttpState state)
{
r = orig;
innerState = state;
}
public bool IsCompleted => r.IsCompleted;
public WaitHandle AsyncWaitHandle => r.AsyncWaitHandle;
public object AsyncState => innerState.AsyncState;
public bool CompletedSynchronously => r.CompletedSynchronously;
}
private class HttpState
{
public AsyncCallback Callback { get; set; }
public object AsyncState { get; set; }
public Exception ex { get; set; }
}
public EndPoint LocalEndPoint => _remote.LocalEndPoint;
public EndPoint ProxyEndPoint { get; private set; }
public EndPoint DestEndPoint { get; private set; }
private readonly WrappedSocket _remote = new WrappedSocket();
public void BeginConnectProxy(EndPoint remoteEP, AsyncCallback callback, object state)
{
ProxyEndPoint = remoteEP;
_remote.BeginConnect(remoteEP, callback, state);
}
public void EndConnectProxy(IAsyncResult asyncResult)
{
_remote.EndConnect(asyncResult);
_remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
}
private const string HTTP_CRLF = "\r\n";
private const string HTTP_CONNECT_TEMPLATE =
"CONNECT {0} HTTP/1.1" + HTTP_CRLF +
"Host: {0}" + HTTP_CRLF +
"Proxy-Connection: keep-alive" + HTTP_CRLF +
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36" + HTTP_CRLF +
"{1}" + // Proxy-Authorization if any
"" + HTTP_CRLF; // End with an empty line
private const string PROXY_AUTH_TEMPLATE = "Proxy-Authorization: Basic {0}" + HTTP_CRLF;
public void BeginConnectDest(EndPoint destEndPoint, AsyncCallback callback, object state, NetworkCredential auth = null)
{
DestEndPoint = destEndPoint;
String authInfo = "";
if (auth != null)
{
string authKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(auth.UserName + ":" + auth.Password));
authInfo = string.Format(PROXY_AUTH_TEMPLATE, authKey);
}
string request = string.Format(HTTP_CONNECT_TEMPLATE, destEndPoint, authInfo);
var b = Encoding.UTF8.GetBytes(request);
var st = new HttpState();
st.Callback = callback;
st.AsyncState = state;
_remote.BeginSend(b, 0, b.Length, 0, HttpRequestSendCallback, st);
}
public void EndConnectDest(IAsyncResult asyncResult)
{
var state = ((FakeAsyncResult)asyncResult).innerState;
if (state.ex != null)
{
throw state.ex;
}
}
public void BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,
object state)
{
_remote.BeginSend(buffer, offset, size, socketFlags, callback, state);
}
public int EndSend(IAsyncResult asyncResult)
{
return _remote.EndSend(asyncResult);
}
public void BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,
object state)
{
_remote.BeginReceive(buffer, offset, size, socketFlags, callback, state);
}
public int EndReceive(IAsyncResult asyncResult)
{
return _remote.EndReceive(asyncResult);
}
public void Shutdown(SocketShutdown how)
{
_remote.Shutdown(how);
}
public void Close()
{
_remote.Dispose();
}
private void HttpRequestSendCallback(IAsyncResult ar)
{
var state = (HttpState) ar.AsyncState;
try
{
_remote.EndSend(ar);
// start line read
new LineReader(_remote, OnLineRead, OnException, OnFinish, Encoding.UTF8, HTTP_CRLF, 1024, new FakeAsyncResult(ar, state));
}
catch (Exception ex)
{
state.ex = ex;
state.Callback?.Invoke(new FakeAsyncResult(ar, state));
}
}
private void OnFinish(byte[] lastBytes, int index, int length, object state)
{
var st = (FakeAsyncResult)state;
if (st.innerState.ex == null)
{
if (!_established)
{
st.innerState.ex = new Exception(I18N.GetString("Proxy request failed"));
}
// TODO: save last bytes
}
st.innerState.Callback?.Invoke(st);
}
private void OnException(Exception ex, object state)
{
var st = (FakeAsyncResult) state;
st.innerState.ex = ex;
}
private static readonly Regex HttpRespondHeaderRegex = new Regex(@"^(HTTP/1\.\d) (\d{3}) (.+)$", RegexOptions.Compiled);
private int _respondLineCount = 0;
private bool _established = false;
private bool OnLineRead(string line, object state)
{
logger.Trace(line);
if (_respondLineCount == 0)
{
var m = HttpRespondHeaderRegex.Match(line);
if (m.Success)
{
var resultCode = m.Groups[2].Value;
if ("200" != resultCode)
{
return true;
}
_established = true;
}
}
else
{
if (string.IsNullOrEmpty(line))
{
return true;
}
}
_respondLineCount++;
return false;
}
}
}
================================================
FILE: shadowsocks-csharp/Proxy/IProxy.cs
================================================
using System;
using System.Net;
using System.Net.Sockets;
namespace Shadowsocks.Proxy
{
public interface IProxy
{
EndPoint LocalEndPoint { get; }
EndPoint ProxyEndPoint { get; }
EndPoint DestEndPoint { get; }
void BeginConnectProxy(EndPoint remoteEP, AsyncCallback callback, object state);
void EndConnectProxy(IAsyncResult asyncResult);
void BeginConnectDest(EndPoint destEndPoint, AsyncCallback callback, object state, NetworkCredential auth = null);
void EndConnectDest(IAsyncResult asyncResult);
void BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,
object state);
int EndSend(IAsyncResult asyncResult);
void BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,
object state);
int EndReceive(IAsyncResult asyncResult);
void Shutdown(SocketShutdown how);
void Close();
}
}
================================================
FILE: shadowsocks-csharp/Proxy/Socks5Proxy.cs
================================================
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Shadowsocks.Controller;
using Shadowsocks.Util.Sockets;
namespace Shadowsocks.Proxy
{
public class Socks5Proxy : IProxy
{
private class FakeAsyncResult : IAsyncResult
{
public readonly Socks5State innerState;
private readonly IAsyncResult r;
public FakeAsyncResult(IAsyncResult orig, Socks5State state)
{
r = orig;
innerState = state;
}
public bool IsCompleted => r.IsCompleted;
public WaitHandle AsyncWaitHandle => r.AsyncWaitHandle;
public object AsyncState => innerState.AsyncState;
public bool CompletedSynchronously => r.CompletedSynchronously;
}
private class Socks5State
{
public AsyncCallback Callback { get; set; }
public object AsyncState { get; set; }
public int BytesToRead;
public Exception ex { get; set; }
}
private readonly WrappedSocket _remote = new WrappedSocket();
private const int Socks5PktMaxSize = 4 + 16 + 2;
private readonly byte[] _receiveBuffer = new byte[Socks5PktMaxSize];
public EndPoint LocalEndPoint => _remote.LocalEndPoint;
public EndPoint ProxyEndPoint { get; private set; }
public EndPoint DestEndPoint { get; private set; }
public void BeginConnectProxy(EndPoint remoteEP, AsyncCallback callback, object state)
{
var st = new Socks5State();
st.Callback = callback;
st.AsyncState = state;
ProxyEndPoint = remoteEP;
_remote.BeginConnect(remoteEP, ConnectCallback, st);
}
public void EndConnectProxy(IAsyncResult asyncResult)
{
var state = ((FakeAsyncResult)asyncResult).innerState;
if (state.ex != null)
{
throw state.ex;
}
}
public void BeginConnectDest(EndPoint destEndPoint, AsyncCallback callback, object state, NetworkCredential auth = null)
{
// TODO: support SOCKS5 auth
DestEndPoint = destEndPoint;
byte[] request = null;
byte atyp = 0;
int port;
var dep = destEndPoint as DnsEndPoint;
if (dep != null)
{
// is a domain name, we will leave it to server
atyp = 3; // DOMAINNAME
var enc = Encoding.UTF8;
var hostByteCount = enc.GetByteCount(dep.Host);
request = new byte[4 + 1/*length byte*/ + hostByteCount + 2];
request[4] = (byte)hostByteCount;
enc.GetBytes(dep.Host, 0, dep.Host.Length, request, 5);
port = dep.Port;
}
else
{
switch (DestEndPoint.AddressFamily)
{
case AddressFamily.InterNetwork:
request = new byte[4 + 4 + 2];
atyp = 1; // IP V4 address
break;
case AddressFamily.InterNetworkV6:
request = new byte[4 + 16 + 2];
atyp = 4; // IP V6 address
break;
default:
throw new Exception(I18N.GetString("Proxy request failed"));
}
port = ((IPEndPoint) DestEndPoint).Port;
var addr = ((IPEndPoint)DestEndPoint).Address.GetAddressBytes();
Array.Copy(addr, 0, request, 4, request.Length - 4 - 2);
}
// 构造request包剩余部分
request[0] = 5;
request[1] = 1;
request[2] = 0;
request[3] = atyp;
request[request.Length - 2] = (byte) ((port >> 8) & 0xff);
request[request.Length - 1] = (byte) (port & 0xff);
var st = new Socks5State();
st.Callback = callback;
st.AsyncState = state;
_remote.BeginSend(request, 0, request.Length, 0, Socks5RequestSendCallback, st);
}
public void EndConnectDest(IAsyncResult asyncResult)
{
var state = ((FakeAsyncResult)asyncResult).innerState;
if (state.ex != null)
{
throw state.ex;
}
}
public void BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,
object state)
{
_remote.BeginSend(buffer, offset, size, socketFlags, callback, state);
}
public int EndSend(IAsyncResult asyncResult)
{
return _remote.EndSend(asyncResult);
}
public void BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,
object state)
{
_remote.BeginReceive(buffer, offset, size, socketFlags, callback, state);
}
public int EndReceive(IAsyncResult asyncResult)
{
return _remote.EndReceive(asyncResult);
}
public void Shutdown(SocketShutdown how)
{
_remote.Shutdown(how);
}
public void Close()
{
_remote.Dispose();
}
private void ConnectCallback(IAsyncResult ar)
{
var state = (Socks5State) ar.AsyncState;
try
{
_remote.EndConnect(ar);
_remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
byte[] handshake = {5, 1, 0};
_remote.BeginSend(handshake, 0, handshake.Length, 0, Socks5HandshakeSendCallback, state);
}
catch (Exception ex)
{
state.ex = ex;
state.Callback?.Invoke(new FakeAsyncResult(ar, state));
}
}
private void Socks5HandshakeSendCallback(IAsyncResult ar)
{
var state = (Socks5State)ar.AsyncState;
try
{
_remote.EndSend(ar);
_remote.BeginReceive(_receiveBuffer, 0, 2, 0, Socks5HandshakeReceiveCallback, state);
}
catch (Exception ex)
{
state.ex = ex;
state.Callback?.Invoke(new FakeAsyncResult(ar, state));
}
}
private void Socks5HandshakeReceiveCallback(IAsyncResult ar)
{
Exception ex = null;
var state = (Socks5State)ar.AsyncState;
try
{
var bytesRead = _remote.EndReceive(ar);
if (bytesRead >= 2)
{
if (_receiveBuffer[0] != 5 || _receiveBuffer[1] != 0)
{
ex = new Exception(I18N.GetString("Proxy handshake failed"));
}
}
else
{
ex = new Exception(I18N.GetString("Proxy handshake failed"));
}
}
catch (Exception ex2)
{
ex = ex2;
}
state.ex = ex;
state.Callback?.Invoke(new FakeAsyncResult(ar, state));
}
private void Socks5RequestSendCallback(IAsyncResult ar)
{
var state = (Socks5State)ar.AsyncState;
try
{
_remote.EndSend(ar);
_remote.BeginReceive(_receiveBuffer, 0, 4, 0, Socks5ReplyReceiveCallback, state);
}
catch (Exception ex)
{
state.ex = ex;
state.Callback?.Invoke(new FakeAsyncResult(ar, state));
}
}
private void Socks5ReplyReceiveCallback(IAsyncResult ar)
{
var state = (Socks5State)ar.AsyncState;
try
{
var bytesRead = _remote.EndReceive(ar);
if (bytesRead >= 4)
{
if (_receiveBuffer[0] == 5 && _receiveBuffer[1] == 0)
{
// 跳过剩下的reply
switch (_receiveBuffer[3]) // atyp
{
case 1:
state.BytesToRead = 4 + 2;
_remote.BeginReceive(_receiveBuffer, 0, 4 + 2, 0, Socks5ReplyReceiveCallback2, state);
break;
case 4:
state.BytesToRead = 16 + 2;
_remote.BeginReceive(_receiveBuffer, 0, 16 + 2, 0, Socks5ReplyReceiveCallback2, state);
break;
default:
state.ex = new Exception(I18N.GetString("Proxy request failed"));
state.Callback?.Invoke(new FakeAsyncResult(ar, state));
break;
}
}
else
{
state.ex = new Exception(I18N.GetString("Proxy request failed"));
state.Callback?.Invoke(new FakeAsyncResult(ar, state));
}
}
else
{
state.ex = new Exception(I18N.GetString("Proxy request failed"));
state.Callback?.Invoke(new FakeAsyncResult(ar, state));
}
}
catch (Exception ex)
{
state.ex = ex;
state.Callback?.Invoke(new FakeAsyncResult(ar, state));
}
}
private void Socks5ReplyReceiveCallback2(IAsyncResult ar)
{
Exception ex = null;
var state = (Socks5State)ar.AsyncState;
try
{
var bytesRead = _remote.EndReceive(ar);
var bytesNeedSkip = state.BytesToRead;
if (bytesRead < bytesNeedSkip)
{
ex = new Exception(I18N.GetString("Proxy request failed"));
}
}
catch (Exception ex2)
{
ex = ex2;
}
state.ex = ex;
state.Callback?.Invoke(new FakeAsyncResult(ar, state));
}
}
}
================================================
FILE: shadowsocks-csharp/Settings.cs
================================================
namespace Shadowsocks.Properties {
// 通过此类可以处理设置类的特定事件:
// 在更改某个设置的值之前将引发 SettingChanging 事件。
// 在更改某个设置的值之后将引发 PropertyChanged 事件。
// 在加载设置值之后将引发 SettingsLoaded 事件。
// 在保存设置值之前将引发 SettingsSaving 事件。
internal sealed partial class Settings {
public Settings() {
// // 若要为保存和更改设置添加事件处理程序,请取消注释下列行:
//
// this.SettingChanging += this.SettingChangingEventHandler;
//
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
}
private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {
// 在此处添加用于处理 SettingChangingEvent 事件的代码。
}
private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {
// 在此处添加用于处理 SettingsSaving 事件的代码。
}
}
}
================================================
FILE: shadowsocks-csharp/Util/ProcessManagement/Job.cs
================================================
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using NLog;
using Shadowsocks.Controller;
namespace Shadowsocks.Util.ProcessManagement
{
/*
* See:
* http://stackoverflow.com/questions/6266820/working-example-of-createjobobject-setinformationjobobject-pinvoke-in-net
*/
public class Job : IDisposable
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private IntPtr handle = IntPtr.Zero;
public Job()
{
handle = CreateJobObject(IntPtr.Zero, null);
var extendedInfoPtr = IntPtr.Zero;
var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION
{
LimitFlags = 0x2000
};
var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
BasicLimitInformation = info
};
try
{
int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
extendedInfoPtr = Marshal.AllocHGlobal(length);
Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);
if (!SetInformationJobObject(handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr,
(uint) length))
throw new Exception(string.Format("Unable to set information. Error: {0}",
Marshal.GetLastWin32Error()));
}
finally
{
if (extendedInfoPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(extendedInfoPtr);
extendedInfoPtr = IntPtr.Zero;
}
}
}
public bool AddProcess(IntPtr processHandle)
{
var succ = AssignProcessToJobObject(handle, processHandle);
if (!succ)
{
logger.Error("Failed to call AssignProcessToJobObject! GetLastError=" + Marshal.GetLastWin32Error());
}
return succ;
}
public bool AddProcess(int processId)
{
return AddProcess(Process.GetProcessById(processId).Handle);
}
#region IDisposable
private bool disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed) return;
disposed = true;
if (disposing)
{
// no managed objects to free
}
if (handle != IntPtr.Zero)
{
CloseHandle(handle);
handle = IntPtr.Zero;
}
}
~Job()
{
Dispose(false);
}
#endregion
#region Interop
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr CreateJobObject(IntPtr a, string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, UInt32 cbJobObjectInfoLength);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
#endregion
}
#region Helper classes
[StructLayout(LayoutKind.Sequential)]
struct IO_COUNTERS
{
public UInt64 ReadOperationCount;
public UInt64 WriteOperationCount;
public UInt64 OtherOperationCount;
public UInt64 ReadTransferCount;
public UInt64 WriteTransferCount;
public UInt64 OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
public Int64 PerProcessUserTimeLimit;
public Int64 PerJobUserTimeLimit;
public UInt32 LimitFlags;
public UIntPtr MinimumWorkingSetSize;
public UIntPtr MaximumWorkingSetSize;
public UInt32 ActiveProcessLimit;
public UIntPtr Affinity;
public UInt32 PriorityClass;
public UInt32 SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public UInt32 nLength;
public IntPtr lpSecurityDescriptor;
public Int32 bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
public IO_COUNTERS IoInfo;
public UIntPtr ProcessMemoryLimit;
public UIntPtr JobMemoryLimit;
public UIntPtr PeakProcessMemoryUsed;
public UIntPtr PeakJobMemoryUsed;
}
public enum JobObjectInfoType
{
AssociateCompletionPortInformation = 7,
BasicLimitInformation = 2,
BasicUIRestrictions = 4,
EndOfJobTimeInformation = 6,
ExtendedLimitInformation = 9,
SecurityLimitInformation = 5,
GroupInformation = 11
}
#endregion
}
================================================
FILE: shadowsocks-csharp/Util/ProcessManagement/ThreadUtil.cs
================================================
using System.Diagnostics;
using System.Management;
using System.Text;
namespace Shadowsocks.Util.ProcessManagement
{
static class ThreadUtil
{
/*
* See:
* http://stackoverflow.com/questions/2633628/can-i-get-command-line-arguments-of-other-processes-from-net-c
*/
public static string GetCommandLine(this Process process)
{
var commandLine = new StringBuilder(process.MainModule.FileName);
commandLine.Append(" ");
using (var searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
{
foreach (var @object in searcher.Get())
{
commandLine.Append(@object["CommandLine"]);
commandLine.Append(" ");
}
}
return commandLine.ToString();
}
}
}
================================================
FILE: shadowsocks-csharp/Util/Sockets/LineReader.cs
================================================
using System;
using System.Text;
namespace Shadowsocks.Util.Sockets
{
public class LineReader
{
private readonly WrappedSocket _socket;
private readonly Func _onLineRead;
private readonly Action _onException;
private readonly Action _onFinish;
private readonly Encoding _encoding;
// private readonly string _delimiter;
private readonly byte[] _delimiterBytes;
private readonly int[] _delimiterSearchCharTable;
private readonly int[] _delimiterSearchOffsetTable;
private readonly object _state;
private readonly byte[] _lineBuffer;
private int _bufferIndex;
public LineReader(WrappedSocket socket, Func onLineRead, Action onException,
Action onFinish, Encoding encoding, string delimiter, int maxLineBytes, object state)
{
if (socket == null)
{
throw new ArgumentNullException(nameof(socket));
}
if (onLineRead == null)
{
throw new ArgumentNullException(nameof(onLineRead));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (delimiter == null)
{
throw new ArgumentNullException(nameof(delimiter));
}
_socket = socket;
_onLineRead = onLineRead;
_onException = onException;
_onFinish = onFinish;
_encoding = encoding;
// _delimiter = delimiter;
_state = state;
// decode delimiter
_delimiterBytes = encoding.GetBytes(delimiter);
if (_delimiterBytes.Length == 0)
{
throw new ArgumentException("Too short!", nameof(delimiter));
}
if (maxLineBytes < _delimiterBytes.Length)
{
throw new ArgumentException("Too small!", nameof(maxLineBytes));
}
_delimiterSearchCharTable = MakeCharTable(_delimiterBytes);
_delimiterSearchOffsetTable = MakeOffsetTable(_delimiterBytes);
_lineBuffer = new byte[maxLineBytes];
// start reading
socket.BeginReceive(_lineBuffer, 0, maxLineBytes, 0, ReceiveCallback, 0);
}
private void ReceiveCallback(IAsyncResult ar)
{
int length = (int)ar.AsyncState;
try
{
var bytesRead = _socket.EndReceive(ar);
if (bytesRead == 0)
{
OnFinish(length);
return;
}
length += bytesRead;
int i;
while ((i = IndexOf(_lineBuffer, _bufferIndex, length, _delimiterBytes, _delimiterSearchOffsetTable,
_delimiterSearchCharTable)) != -1)
{
var decodeLen = i - _bufferIndex;
string line = _encoding.GetString(_lineBuffer, _bufferIndex, decodeLen);
_bufferIndex = i + _delimiterBytes.Length;
length -= decodeLen;
length -= _delimiterBytes.Length;
var stop = _onLineRead(line, _state);
if (stop)
{
OnFinish(length);
return;
}
}
if (length == _lineBuffer.Length)
{
OnException(new IndexOutOfRangeException("LineBuffer full! Try increace maxLineBytes!"));
OnFinish(length);
return;
}
if (_bufferIndex > 0)
{
Buffer.BlockCopy(_lineBuffer, _bufferIndex, _lineBuffer, 0, length);
_bufferIndex = 0;
}
_socket.BeginReceive(_lineBuffer, length, _lineBuffer.Length - length, 0, ReceiveCallback, length);
}
catch (Exception ex)
{
OnException(ex);
OnFinish(length);
}
}
private void OnException(Exception ex)
{
_onException?.Invoke(ex, _state);
}
private void OnFinish(int length)
{
_onFinish?.Invoke(_lineBuffer, _bufferIndex, length, _state);
}
#region Boyer-Moore string search
public static int IndexOf(byte[] haystack, int index, int length, byte[] needle, int[] offsetTable, int[] charTable)
{
var end = index + length;
for (int i = needle.Length - 1 + index, j; i < end;)
{
for (j = needle.Length - 1; needle[j] == haystack[i]; --i, --j)
{
if (j == 0)
{
return i;
}
}
// i += needle.length - j; // For naive method
i += Math.Max(offsetTable[needle.Length - 1 - j], charTable[haystack[i]]);
}
return -1;
}
/**
* Makes the jump table based on the mismatched character information.
*/
private static int[] MakeCharTable(byte[] needle)
{
const int ALPHABET_SIZE = 256;
int[] table = new int[ALPHABET_SIZE];
for (int i = 0; i < table.Length; ++i)
{
table[i] = needle.Length;
}
for (int i = 0; i < needle.Length - 1; ++i)
{
table[needle[i]] = needle.Length - 1 - i;
}
return table;
}
/**
* Makes the jump table based on the scan offset which mismatch occurs.
*/
private static int[] MakeOffsetTable(byte[] needle)
{
int[] table = new int[needle.Length];
int lastPrefixPosition = needle.Length;
for (int i = needle.Length - 1; i >= 0; --i)
{
if (IsPrefix(needle, i + 1))
{
lastPrefixPosition = i + 1;
}
table[needle.Length - 1 - i] = lastPrefixPosition - i + needle.Length - 1;
}
for (int i = 0; i < needle.Length - 1; ++i)
{
int slen = SuffixLength(needle, i);
table[slen] = needle.Length - 1 - i + slen;
}
return table;
}
/**
* Is needle[p:end] a prefix of needle?
*/
private static bool IsPrefix(byte[] needle, int p)
{
for (int i = p, j = 0; i < needle.Length; ++i, ++j)
{
if (needle[i] != needle[j])
{
return false;
}
}
return true;
}
/**
* Returns the maximum length of the substring ends at p and is a suffix.
*/
private static int SuffixLength(byte[] needle, int p)
{
int len = 0;
for (int i = p, j = needle.Length - 1;
i >= 0 && needle[i] == needle[j]; --i, --j)
{
len += 1;
}
return len;
}
#endregion
}
}
================================================
FILE: shadowsocks-csharp/Util/Sockets/SocketUtil.cs
================================================
using System;
using System.Net;
using System.Net.Sockets;
namespace Shadowsocks.Util.Sockets
{
public static class SocketUtil
{
private class DnsEndPoint2 : DnsEndPoint
{
public DnsEndPoint2(string host, int port) : base(host, port)
{
}
public DnsEndPoint2(string host, int port, AddressFamily addressFamily) : base(host, port, addressFamily)
{
}
public override string ToString()
{
return this.Host + ":" + this.Port;
}
}
public static EndPoint GetEndPoint(string host, int port)
{
IPAddress ipAddress;
bool parsed = IPAddress.TryParse(host, out ipAddress);
if (parsed)
{
return new IPEndPoint(ipAddress, port);
}
// maybe is a domain name
return new DnsEndPoint2(host, port);
}
public static void FullClose(this System.Net.Sockets.Socket s)
{
try
{
s.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
try
{
s.Disconnect(false);
}
catch (Exception)
{
}
try
{
s.Close();
}
catch (Exception)
{
}
}
}
}
================================================
FILE: shadowsocks-csharp/Util/Sockets/WrappedSocket.cs
================================================
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Shadowsocks.Util.Sockets
{
/*
* A wrapped socket class which support both ipv4 and ipv6 based on the
* connected remote endpoint.
*
* If the server address is host name, then it may have both ipv4 and ipv6 address
* after resolving. The main idea is we don't want to resolve and choose the address
* by ourself. Instead, Socket.ConnectAsync() do handle this thing internally by trying
* each address and returning an established socket connection.
*/
public class WrappedSocket
{
public EndPoint LocalEndPoint => _activeSocket?.LocalEndPoint;
// Only used during connection and close, so it won't cost too much.
private SpinLock _socketSyncLock = new SpinLock();
private bool _disposed;
private bool Connected => _activeSocket != null;
private Socket _activeSocket;
public void BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (Connected)
{
throw new SocketException((int) SocketError.IsConnected);
}
var arg = new SocketAsyncEventArgs();
arg.RemoteEndPoint = remoteEP;
arg.Completed += OnTcpConnectCompleted;
arg.UserToken = new TcpUserToken(callback, state);
if(!Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, arg))
{
OnTcpConnectCompleted(this, arg);
}
}
private class FakeAsyncResult : IAsyncResult
{
public bool IsCompleted { get; } = true;
public WaitHandle AsyncWaitHandle { get; } = null;
public object AsyncState { get; set; }
public bool CompletedSynchronously { get; } = true;
public Exception InternalException { get; set; } = null;
}
private class TcpUserToken
{
public AsyncCallback Callback { get; }
public object AsyncState { get; }
public TcpUserToken(AsyncCallback callback, object state)
{
Callback = callback;
AsyncState = state;
}
}
private void OnTcpConnectCompleted(object sender, SocketAsyncEventArgs args)
{
using (args)
{
args.Completed -= OnTcpConnectCompleted;
var token = (TcpUserToken) args.UserToken;
if (args.SocketError != SocketError.Success)
{
var ex = args.ConnectByNameError ?? new SocketException((int) args.SocketError);
var r = new FakeAsyncResult()
{
AsyncState = token.AsyncState,
InternalException = ex
};
token.Callback(r);
}
else
{
var lockTaken = false;
if (!_socketSyncLock.IsHeldByCurrentThread)
{
_socketSyncLock.TryEnter(ref lockTaken);
}
try
{
if (Connected)
{
args.ConnectSocket.FullClose();
}
else
{
_activeSocket = args.ConnectSocket;
if (_disposed)
{
_activeSocket.FullClose();
}
var r = new FakeAsyncResult()
{
AsyncState = token.AsyncState
};
token.Callback(r);
}
}
finally
{
if (lockTaken)
{
_socketSyncLock.Exit();
}
}
}
}
}
public void EndConnect(IAsyncResult asyncResult)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
var r = asyncResult as FakeAsyncResult;
if (r == null)
{
throw new ArgumentException("Invalid asyncResult.", nameof(asyncResult));
}
if (r.InternalException != null)
{
throw r.InternalException;
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
var lockTaken = false;
if (!_socketSyncLock.IsHeldByCurrentThread)
{
_socketSyncLock.TryEnter(ref lockTaken);
}
try
{
_disposed = true;
_activeSocket?.FullClose();
}
finally
{
if (lockTaken)
{
_socketSyncLock.Exit();
}
}
}
public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags,
AsyncCallback callback,
object state)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (!Connected)
{
throw new SocketException((int) SocketError.NotConnected);
}
return _activeSocket.BeginSend(buffer, offset, size, socketFlags, callback, state);
}
public int EndSend(IAsyncResult asyncResult)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (!Connected)
{
throw new SocketException((int) SocketError.NotConnected);
}
return _activeSocket.EndSend(asyncResult);
}
public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags,
AsyncCallback callback,
object state)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (!Connected)
{
throw new SocketException((int) SocketError.NotConnected);
}
return _activeSocket.BeginReceive(buffer, offset, size, socketFlags, callback, state);
}
public int EndReceive(IAsyncResult asyncResult)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (!Connected)
{
throw new SocketException((int) SocketError.NotConnected);
}
return _activeSocket.EndReceive(asyncResult);
}
public void Shutdown(SocketShutdown how)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (!Connected)
{
return;
}
_activeSocket.Shutdown(how);
}
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
{
SetSocketOption(optionLevel, optionName, optionValue ? 1 : 0);
}
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (!Connected)
{
throw new SocketException((int)SocketError.NotConnected);
}
_activeSocket.SetSocketOption(optionLevel, optionName, optionValue);
}
}
}
================================================
FILE: shadowsocks-csharp/Util/SystemProxy/ProxyException.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Shadowsocks.Util.SystemProxy
{
enum ProxyExceptionType
{
Unspecific,
FailToRun,
QueryReturnEmpty,
SysproxyExitError,
QueryReturnMalformed
}
class ProxyException : Exception
{
// provide more specific information about exception
public ProxyExceptionType Type { get; }
public ProxyException()
{
}
public ProxyException(string message) : base(message)
{
}
public ProxyException(string message, Exception innerException) : base(message, innerException)
{
}
protected ProxyException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public ProxyException(ProxyExceptionType type)
{
this.Type = type;
}
public ProxyException(ProxyExceptionType type, string message) : base(message)
{
this.Type = type;
}
public ProxyException(ProxyExceptionType type, string message, Exception innerException) : base(message, innerException)
{
this.Type = type;
}
protected ProxyException(ProxyExceptionType type, SerializationInfo info, StreamingContext context) : base(info, context)
{
this.Type = type;
}
}
}
================================================
FILE: shadowsocks-csharp/Util/SystemProxy/Sysproxy.cs
================================================
using Newtonsoft.Json;
using NLog;
using Shadowsocks.Controller;
using Shadowsocks.Model;
using Shadowsocks.Properties;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
namespace Shadowsocks.Util.SystemProxy
{
public static class Sysproxy
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private const string _userWininetConfigFile = "user-wininet.json";
private readonly static string[] _lanIP = {
"",
"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.*"
};
private static string _queryStr;
// In general, this won't change
// format:
//
//
//
//
private static SysproxyConfig _userSettings = null;
enum RET_ERRORS : int
{
RET_NO_ERROR = 0,
INVALID_FORMAT = 1,
NO_PERMISSION = 2,
SYSCALL_FAILED = 3,
NO_MEMORY = 4,
INVAILD_OPTION_COUNT = 5,
};
static Sysproxy()
{
try
{
FileManager.UncompressFile(Utils.GetTempPath("sysproxy.exe"),
Environment.Is64BitOperatingSystem ? Resources.sysproxy64_exe : Resources.sysproxy_exe);
}
catch (IOException e)
{
logger.LogUsefulException(e);
}
}
public static void SetIEProxy(bool enable, bool global, string proxyServer, string pacURL)
{
Read();
if (!_userSettings.UserSettingsRecorded)
{
// record user settings
ExecSysproxy("query");
ParseQueryStr(_queryStr);
}
string arguments;
if (enable)
{
string customBypassString = _userSettings.BypassList ?? "";
List customBypassList = new List(customBypassString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
customBypassList.AddRange(_lanIP);
string[] realBypassList = customBypassList.Distinct().ToArray();
string realBypassString = string.Join(";", realBypassList);
arguments = global
? $"global {proxyServer} {realBypassString}"
: $"pac {pacURL}";
}
else
{
// restore user settings
var flags = _userSettings.Flags;
var proxy_server = _userSettings.ProxyServer ?? "-";
var bypass_list = _userSettings.BypassList ?? "-";
var pac_url = _userSettings.PacUrl ?? "-";
arguments = $"set {flags} {proxy_server} {bypass_list} {pac_url}";
// have to get new settings
_userSettings.UserSettingsRecorded = false;
}
Save();
ExecSysproxy(arguments);
}
// set system proxy to 1 (null) (null) (null)
public static bool ResetIEProxy()
{
try
{
// clear user-wininet.json
_userSettings = new SysproxyConfig();
Save();
// clear system setting
ExecSysproxy("set 1 - - -");
}
catch (Exception)
{
return false;
}
return true;
}
private static void ExecSysproxy(string arguments)
{
// using event to avoid hanging when redirect standard output/error
// ref: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
// and http://blog.csdn.net/zhangweixing0/article/details/7356841
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
using (var process = new Process())
{
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = Utils.GetTempPath("sysproxy.exe");
process.StartInfo.Arguments = arguments;
process.StartInfo.WorkingDirectory = Utils.GetTempPath();
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
// Need to provide encoding info, or output/error strings we got will be wrong.
process.StartInfo.StandardOutputEncoding = Encoding.Unicode;
process.StartInfo.StandardErrorEncoding = Encoding.Unicode;
process.StartInfo.CreateNoWindow = true;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};
try
{
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();
}
catch (System.ComponentModel.Win32Exception e)
{
// log the arguments
throw new ProxyException(ProxyExceptionType.FailToRun, process.StartInfo.Arguments, e);
}
var stderr = error.ToString();
var stdout = output.ToString();
var exitCode = process.ExitCode;
if (exitCode != (int)RET_ERRORS.RET_NO_ERROR)
{
throw new ProxyException(ProxyExceptionType.SysproxyExitError, stderr);
}
if (arguments == "query")
{
if (string.IsNullOrWhiteSpace(stdout))
{
// we cannot get user settings
throw new ProxyException(ProxyExceptionType.QueryReturnEmpty);
}
_queryStr = stdout;
}
}
}
}
private static void Save()
{
try
{
using (StreamWriter sw = new StreamWriter(File.Open(Utils.GetTempPath(_userWininetConfigFile), FileMode.Create)))
{
string jsonString = JsonConvert.SerializeObject(_userSettings, Formatting.Indented);
sw.Write(jsonString);
sw.Flush();
}
}
catch (IOException e)
{
logger.LogUsefulException(e);
}
}
private static void Read()
{
try
{
string configContent = File.ReadAllText(Utils.GetTempPath(_userWininetConfigFile));
_userSettings = JsonConvert.DeserializeObject(configContent);
}
catch (Exception)
{
// Suppress all exceptions. finally block will initialize new user config settings.
}
finally
{
if (_userSettings == null) _userSettings = new SysproxyConfig();
}
}
private static void ParseQueryStr(string str)
{
string[] userSettingsArr = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
// sometimes sysproxy output in utf16le instead of ascii
// manually translate it
if (userSettingsArr.Length != 4)
{
byte[] strByte = Encoding.ASCII.GetBytes(str);
str = Encoding.Unicode.GetString(strByte);
userSettingsArr = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
// still fail, throw exception with string hexdump
if (userSettingsArr.Length != 4)
{
throw new ProxyException(ProxyExceptionType.QueryReturnMalformed, BitConverter.ToString(strByte));
}
}
_userSettings.Flags = userSettingsArr[0];
// handle output from WinINET
if (userSettingsArr[1] == "(null)") _userSettings.ProxyServer = null;
else _userSettings.ProxyServer = userSettingsArr[1];
if (userSettingsArr[2] == "(null)") _userSettings.BypassList = null;
else _userSettings.BypassList = userSettingsArr[2];
if (userSettingsArr[3] == "(null)") _userSettings.PacUrl = null;
else _userSettings.PacUrl = userSettingsArr[3];
_userSettings.UserSettingsRecorded = true;
}
}
}
================================================
FILE: shadowsocks-csharp/Util/Util.cs
================================================
using NLog;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Win32;
using Shadowsocks.Controller;
using Shadowsocks.Model;
using System.Drawing;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;
namespace Shadowsocks.Util
{
public struct BandwidthScaleInfo
{
public float value;
public string unitName;
public long unit;
public BandwidthScaleInfo(float value, string unitName, long unit)
{
this.value = value;
this.unitName = unitName;
this.unit = unit;
}
}
public static class Utils
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private static string _tempPath = null;
// return path to store temporary files
public static string GetTempPath()
{
if (_tempPath == null)
{
bool isPortableMode = Configuration.Load().portableMode;
try
{
if (isPortableMode)
{
_tempPath = Directory.CreateDirectory("ss_win_temp").FullName;
// don't use "/", it will fail when we call explorer /select xxx/ss_win_temp\xxx.log
}
else
{
_tempPath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), @"Shadowsocks\ss_win_temp_" + Program.ExecutablePath.GetHashCode())).FullName;
}
}
catch (Exception e)
{
logger.Error(e);
throw;
}
}
return _tempPath;
}
public enum WindowsThemeMode { Dark, Light }
// Support on Windows 10 1903+
public static WindowsThemeMode GetWindows10SystemThemeSetting()
{
WindowsThemeMode themeMode = WindowsThemeMode.Dark;
try
{
RegistryKey reg_ThemesPersonalize = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", false);
if (reg_ThemesPersonalize.GetValue("SystemUsesLightTheme") != null)
{
if ((int)(reg_ThemesPersonalize.GetValue("SystemUsesLightTheme")) == 0) // 0:dark mode, 1:light mode
themeMode = WindowsThemeMode.Dark;
else
themeMode = WindowsThemeMode.Light;
}
else
{
throw new Exception("Reg-Value SystemUsesLightTheme not found.");
}
}
catch
{
logger.Debug(
$"Cannot get Windows 10 system theme mode, return default value 0 (dark mode).");
}
return themeMode;
}
// return a full path with filename combined which pointed to the temporary directory
public static string GetTempPath(string filename)
{
return Path.Combine(GetTempPath(), filename);
}
public static string UnGzip(byte[] buf)
{
byte[] buffer = new byte[1024];
int n;
using (MemoryStream sb = new MemoryStream())
{
using (GZipStream input = new GZipStream(new MemoryStream(buf),
CompressionMode.Decompress,
false))
{
while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
{
sb.Write(buffer, 0, n);
}
}
return System.Text.Encoding.UTF8.GetString(sb.ToArray());
}
}
public static string FormatBandwidth(long n)
{
var result = GetBandwidthScale(n);
return $"{result.value:0.##}{result.unitName}";
}
public static string FormatBytes(long bytes)
{
const long K = 1024L;
const long M = K * 1024L;
const long G = M * 1024L;
const long T = G * 1024L;
const long P = T * 1024L;
const long E = P * 1024L;
if (bytes >= P * 990)
return (bytes / (double)E).ToString("F5") + "EiB";
if (bytes >= T * 990)
return (bytes / (double)P).ToString("F5") + "PiB";
if (bytes >= G * 990)
return (bytes / (double)T).ToString("F5") + "TiB";
if (bytes >= M * 990)
{
return (bytes / (double)G).ToString("F4") + "GiB";
}
if (bytes >= M * 100)
{
return (bytes / (double)M).ToString("F1") + "MiB";
}
if (bytes >= M * 10)
{
return (bytes / (double)M).ToString("F2") + "MiB";
}
if (bytes >= K * 990)
{
return (bytes / (double)M).ToString("F3") + "MiB";
}
if (bytes > K * 2)
{
return (bytes / (double)K).ToString("F1") + "KiB";
}
return bytes.ToString() + "B";
}
///
/// Return scaled bandwidth
///
/// Raw bandwidth
///
/// The BandwidthScaleInfo struct
///
public static BandwidthScaleInfo GetBandwidthScale(long n)
{
long scale = 1;
float f = n;
string unit = "B";
if (f > 1024)
{
f = f / 1024;
scale <<= 10;
unit = "KiB";
}
if (f > 1024)
{
f = f / 1024;
scale <<= 10;
unit = "MiB";
}
if (f > 1024)
{
f = f / 1024;
scale <<= 10;
unit = "GiB";
}
if (f > 1024)
{
f = f / 1024;
scale <<= 10;
unit = "TiB";
}
return new BandwidthScaleInfo(f, unit, scale);
}
public static RegistryKey OpenRegKey(string name, bool writable, RegistryHive hive = RegistryHive.CurrentUser)
{
// we are building x86 binary for both x86 and x64, which will
// cause problem when opening registry key
// detect operating system instead of CPU
if (string.IsNullOrEmpty(name)) throw new ArgumentException(nameof(name));
try
{
RegistryKey userKey = RegistryKey.OpenBaseKey(hive,
Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32)
.OpenSubKey(name, writable);
return userKey;
}
catch (ArgumentException ae)
{
MessageBox.Show("OpenRegKey: " + ae.ToString());
return null;
}
catch (Exception e)
{
logger.LogUsefulException(e);
return null;
}
}
public static bool IsWinVistaOrHigher()
{
return Environment.OSVersion.Version.Major > 5;
}
public static string ScanQRCodeFromScreen()
{
foreach (Screen screen in Screen.AllScreens)
{
using (Bitmap fullImage = new Bitmap(screen.Bounds.Width,
screen.Bounds.Height))
{
using (Graphics g = Graphics.FromImage(fullImage))
{
g.CopyFromScreen(screen.Bounds.X,
screen.Bounds.Y,
0, 0,
fullImage.Size,
CopyPixelOperation.SourceCopy);
}
int maxTry = 10;
for (int i = 0; i < maxTry; i++)
{
int marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry);
int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry);
Rectangle cropRect = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2);
Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);
double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width;
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),
cropRect,
GraphicsUnit.Pixel);
}
var source = new BitmapLuminanceSource(target);
var bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
var result = reader.decode(bitmap);
if (result != null)
return result.Text;
}
}
}
return null;
}
// See: https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
public static bool IsSupportedRuntimeVersion()
{
/*
* +-----------------------------------------------------------------+----------------------------+
* | Version | Value of the Release DWORD |
* +-----------------------------------------------------------------+----------------------------+
* | .NET Framework 4.6.2 installed on Windows 10 Anniversary Update | 394802 |
* | .NET Framework 4.6.2 installed on all other Windows OS versions | 394806 |
* +-----------------------------------------------------------------+----------------------------+
*/
const int minSupportedRelease = 394802;
const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
using (var ndpKey = OpenRegKey(subkey, false, RegistryHive.LocalMachine))
{
if (ndpKey?.GetValue("Release") != null)
{
var releaseKey = (int)ndpKey.GetValue("Release");
if (releaseKey >= minSupportedRelease)
{
return true;
}
}
}
return false;
}
}
}
================================================
FILE: shadowsocks-csharp/Util/ViewUtils.cs
================================================
using Shadowsocks.Controller;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
namespace Shadowsocks.Util
{
public static class ViewUtils
{
public static IEnumerable GetChildControls(this Control control) where TControl : Control
{
if (control.Controls.Count == 0)
{
return Enumerable.Empty();
}
var children = control.Controls.OfType().ToList();
return children.SelectMany(GetChildControls).Concat(children);
}
public static IEnumerable