[
  {
    "path": ".gitattributes",
    "content": "* text=auto\n\n# geosite database\n*.dat binary"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report_en.md",
    "content": "---\nname: Bug report (English)\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n<!--\n- Shadowsocks is a non-profit open source project. If you bought the service from a provider, please contact them.\n- If you have questions rather than Shadowsocks Windows client, please go to https://github.com/shadowsocks\n- Please read Wiki carefully, especially https://github.com/shadowsocks/shadowsocks-windows/wiki/Troubleshooting\n- And search from Issue Board https://github.com/shadowsocks/shadowsocks-windows/issues?utf8=%E2%9C%93&q=is%3Aissue\n- Please include the following information. Questions lacking details will be closed.\n-->\n\n### Describe the bug\n\n### Environment\n\n- Shadowsocks client version:\n- OS version:\n- .NET version:\n\n### Steps you have tried\n\n\n### What did you expect to see?\n\n\n### What did you see instead?\n\n\n### Config and error log in detail (with all sensitive info masked)\n\n```\nPASTE LOG HERE\n```\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report_zh.md",
    "content": "---\nname: Bug报告 （中文）\nabout: 反馈Bug\ntitle: ''\nlabels: bug report\nassignees: ''\n\n---\n\n<!--\n- 影梭（Shadowsocks）是一个开源非盈利项目，不提供任何托管服务。如果你是从服务提供商购买的服务，请联系他们。\n- 如果你有非影梭Windows客户端相关的问题，请去 https://github.com/shadowsocks\n- 提问前请先阅读wiki https://github.com/shadowsocks/shadowsocks-windows/wiki/Troubleshooting.\n- 并在Issue Board中搜索 https://github.com/shadowsocks/shadowsocks-windows/issues?utf8=%E2%9C%93&q=is%3Aissue\n- 请按照以下格式描述你的问题，描述不清的问题将会被关闭。\n-->\n\n### 简要描述问题\n\n### 环境\n\n- Shadowsocks客户端版本：\n- 操作系统版本：\n- .NET版本：\n\n### 操作步骤\n\n\n### 期望的结果\n\n\n### 实际结果\n\n\n### 配置文件和日志文件（请隐去敏感信息）\n\n```\n在此粘贴日志\n```\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here."
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "## Please follow the guide below\n\n- You will be asked some questions, please read them **carefully** and answer honestly\n- Put an `x` into all the boxes [ ] relevant to your *pull request* (like that [x])\n- Use *Preview* tab to see how your *pull request* will actually look like\n\n- [ ] [Searched](https://github.com/shadowsocks/shadowsocks-windows/search?q=is%3Apr&type=Issues) for similar pull requests\n- [ ] Compiled the code with Visual Studio\n- [ ] Require translation update\n- [ ] Require document update (readme.md, wikipage, etc)\n\n### What is the purpose of your *pull request*?\n- [ ] Bug fix\n- [ ] Improvement\n- [ ] New feature\n\n---\n\n### Description of your *pull request* and other information\n\nExplanation 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."
  },
  {
    "path": ".gitignore",
    "content": "## Ignore Visual Studio and VSCode temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n##\n## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore\n## and https://github.com/github/gitignore/blob/master/Global/VisualStudioCode.gitignore\n\n# User-specific files\n*.rsuser\n*.suo\n*.user\n*.userosscache\n*.sln.docstates\n\n# User-specific files (MonoDevelop/Xamarin Studio)\n*.userprefs\n\n# Mono auto generated files\nmono_crash.*\n\n# Build results\n[Dd]ebug/\n[Dd]ebugPublic/\n[Rr]elease/\n[Rr]eleases/\nx64/\nx86/\n[Ww][Ii][Nn]32/\n[Aa][Rr][Mm]/\n[Aa][Rr][Mm]64/\nbld/\n[Bb]in/\n[Oo]bj/\n[Ll]og/\n[Ll]ogs/\n\n# Visual Studio 2015/2017 cache/options directory\n.vs/\n# Uncomment if you have tasks that create the project's static files in wwwroot\n#wwwroot/\n\n# Visual Studio 2017 auto generated files\nGenerated\\ Files/\n\n# MSTest test Results\n[Tt]est[Rr]esult*/\n[Bb]uild[Ll]og.*\n\n# NUnit\n*.VisualState.xml\nTestResult.xml\nnunit-*.xml\n\n# Build Results of an ATL Project\n[Dd]ebugPS/\n[Rr]eleasePS/\ndlldata.c\n\n# Benchmark Results\nBenchmarkDotNet.Artifacts/\n\n# .NET Core\nproject.lock.json\nproject.fragment.lock.json\nartifacts/\n\n# ASP.NET Scaffolding\nScaffoldingReadMe.txt\n\n# StyleCop\nStyleCopReport.xml\n\n# Files built by Visual Studio\n*_i.c\n*_p.c\n*_h.h\n*.ilk\n*.meta\n*.obj\n*.iobj\n*.pch\n*.pdb\n*.ipdb\n*.pgc\n*.pgd\n*.rsp\n*.sbr\n*.tlb\n*.tli\n*.tlh\n*.tmp\n*.tmp_proj\n*_wpftmp.csproj\n*.log\n*.vspscc\n*.vssscc\n.builds\n*.pidb\n*.svclog\n*.scc\n\n# Chutzpah Test files\n_Chutzpah*\n\n# Visual C++ cache files\nipch/\n*.aps\n*.ncb\n*.opendb\n*.opensdf\n*.sdf\n*.cachefile\n*.VC.db\n*.VC.VC.opendb\n\n# Visual Studio profiler\n*.psess\n*.vsp\n*.vspx\n*.sap\n\n# Visual Studio Trace Files\n*.e2e\n\n# TFS 2012 Local Workspace\n$tf/\n\n# Guidance Automation Toolkit\n*.gpState\n\n# ReSharper is a .NET coding add-in\n_ReSharper*/\n*.[Rr]e[Ss]harper\n*.DotSettings.user\n\n# TeamCity is a build add-in\n_TeamCity*\n\n# DotCover is a Code Coverage Tool\n*.dotCover\n\n# AxoCover is a Code Coverage Tool\n.axoCover/*\n!.axoCover/settings.json\n\n# Coverlet is a free, cross platform Code Coverage Tool\ncoverage*[.json, .xml, .info]\n\n# Visual Studio code coverage results\n*.coverage\n*.coveragexml\n\n# NCrunch\n_NCrunch_*\n.*crunch*.local.xml\nnCrunchTemp_*\n\n# MightyMoose\n*.mm.*\nAutoTest.Net/\n\n# Web workbench (sass)\n.sass-cache/\n\n# Installshield output folder\n[Ee]xpress/\n\n# DocProject is a documentation generator add-in\nDocProject/buildhelp/\nDocProject/Help/*.HxT\nDocProject/Help/*.HxC\nDocProject/Help/*.hhc\nDocProject/Help/*.hhk\nDocProject/Help/*.hhp\nDocProject/Help/Html2\nDocProject/Help/html\n\n# Click-Once directory\npublish/\n\n# Publish Web Output\n*.[Pp]ublish.xml\n*.azurePubxml\n# Note: Comment the next line if you want to checkin your web deploy settings,\n# but database connection strings (with potential passwords) will be unencrypted\n# *.pubxml\n*.publishproj\n\n# Microsoft Azure Web App publish settings. Comment the next line if you want to\n# checkin your Azure Web App publish settings, but sensitive information contained\n# in these scripts will be unencrypted\nPublishScripts/\n\n# NuGet Packages\n*.nupkg\n# NuGet Symbol Packages\n*.snupkg\n# The packages folder can be ignored because of Package Restore\n**/[Pp]ackages/*\n# except build/, which is used as an MSBuild target.\n!**/[Pp]ackages/build/\n# Uncomment if necessary however generally it will be regenerated when needed\n#!**/[Pp]ackages/repositories.config\n# NuGet v3's project.json files produces more ignorable files\n*.nuget.props\n*.nuget.targets\n\n# Microsoft Azure Build Output\ncsx/\n*.build.csdef\n\n# Microsoft Azure Emulator\necf/\nrcf/\n\n# Windows Store app package directories and files\nAppPackages/\nBundleArtifacts/\nPackage.StoreAssociation.xml\n_pkginfo.txt\n*.appx\n*.appxbundle\n*.appxupload\n\n# Visual Studio cache files\n# files ending in .cache can be ignored\n*.[Cc]ache\n# but keep track of directories ending in .cache\n!?*.[Cc]ache/\n\n# Others\nClientBin/\n~$*\n*~\n*.dbmdl\n*.dbproj.schemaview\n*.jfm\n*.pfx\n*.publishsettings\norleans.codegen.cs\n\n# Including strong name files can present a security risk\n# (https://github.com/github/gitignore/pull/2483#issue-259490424)\n#*.snk\n\n# Since there are multiple workflows, uncomment next line to ignore bower_components\n# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)\n#bower_components/\n\n# RIA/Silverlight projects\nGenerated_Code/\n\n# Backup & report files from converting an old project file\n# to a newer Visual Studio version. Backup files are not needed,\n# because we have git ;-)\n_UpgradeReport_Files/\nBackup*/\nUpgradeLog*.XML\nUpgradeLog*.htm\nServiceFabricBackup/\n*.rptproj.bak\n\n# SQL Server files\n*.mdf\n*.ldf\n*.ndf\n\n# Business Intelligence projects\n*.rdl.data\n*.bim.layout\n*.bim_*.settings\n*.rptproj.rsuser\n*- [Bb]ackup.rdl\n*- [Bb]ackup ([0-9]).rdl\n*- [Bb]ackup ([0-9][0-9]).rdl\n\n# Microsoft Fakes\nFakesAssemblies/\n\n# GhostDoc plugin setting file\n*.GhostDoc.xml\n\n# Node.js Tools for Visual Studio\n.ntvs_analysis.dat\nnode_modules/\n\n# Visual Studio 6 build log\n*.plg\n\n# Visual Studio 6 workspace options file\n*.opt\n\n# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)\n*.vbw\n\n# Visual Studio LightSwitch build output\n**/*.HTMLClient/GeneratedArtifacts\n**/*.DesktopClient/GeneratedArtifacts\n**/*.DesktopClient/ModelManifest.xml\n**/*.Server/GeneratedArtifacts\n**/*.Server/ModelManifest.xml\n_Pvt_Extensions\n\n# Paket dependency manager\n.paket/paket.exe\npaket-files/\n\n# FAKE - F# Make\n.fake/\n\n# CodeRush personal settings\n.cr/personal\n\n# Python Tools for Visual Studio (PTVS)\n__pycache__/\n*.pyc\n\n# Cake - Uncomment if you are using it\n# tools/**\n# !tools/packages.config\n\n# Tabs Studio\n*.tss\n\n# Telerik's JustMock configuration file\n*.jmconfig\n\n# BizTalk build output\n*.btp.cs\n*.btm.cs\n*.odx.cs\n*.xsd.cs\n\n# OpenCover UI analysis results\nOpenCover/\n\n# Azure Stream Analytics local run output\nASALocalRun/\n\n# MSBuild Binary and Structured Log\n*.binlog\n\n# NVidia Nsight GPU debugger configuration file\n*.nvuser\n\n# MFractors (Xamarin productivity tool) working folder\n.mfractor/\n\n# Local History for Visual Studio\n.localhistory/\n\n# BeatPulse healthcheck temp database\nhealthchecksdb\n\n# Backup folder for Package Reference Convert tool in Visual Studio 2017\nMigrationBackup/\n\n# Ionide (cross platform F# VS Code tools) working folder\n.ionide/\n\n# VSCode\n.vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json\n*.code-workspace\n"
  },
  {
    "path": "CHANGES",
    "content": "4.4.1.0 2022-02-08\r\n- Add plain/none ciphers\r\n\r\n4.4.0.0 2021-01-01\r\n- Security: remove infrastructure of stream ciphers (#3048)\r\n- Show warning message when importing from deprecated legacy ss:// links.\r\n- Other minor bug fixes and improvements\r\n\r\n4.3.3.0 2020-12-07\r\n- PAC: Add option for custom sha256sum URL of custom geosite source (#3026)\r\n- Update to .NET Framework 4.8\r\n- Other minor bug fixes and improvements\r\n\r\n4.3.2.0 2020-11-05\r\n- PAC: direct connection for private IP ranges by @studentmain (#3008)\r\n- Remove duplicate startup entries (#3012)\r\n- Other minor bug fixes and improvements\r\n\r\n4.3.1.0 2020-10-25\r\n- Update abp.js (#2999)\r\n- Separate QR code scanning from MenuViewController (#2995)\r\n- Remove statistics strategy (#2994)\r\n- Other minor bug fixes and improvements\r\n\r\n4.3.0.0 2020-10-19\r\n- Cleanup and update dependencies (#2983)\r\n- Geosite group validation + PAC regeneration on version update (#2988)\r\n- PAC: add options for direct and proxied groups (#2990)\r\n- Transition to WPF: ForwardProxyView + HotkeysView + OnlineConfigView + VersionUpdatePromptView (#2991)\r\n\r\n4.2.1.0 2020-10-12\r\n- SIP008 support (#2942)\r\n- Exclude @cn from PAC proxied list (#2982)\r\n- Transition to WPF: ReactiveUI and ServerSharingView (#2959)\r\n- User-Agent for OnlineConfigResolver and GeositeUpdater (#2978)\r\n\r\n4.2.0.1 2020-09-26\r\n- Fix domain rule handling in PAC script (#2956)\r\n\r\n4.2.0.0 2020-09-10\r\n- Update TCPHandler.lastActivity (#2858)\r\n- Add Franch translation (#2861)\r\n- New option for ss:// URL association (#2855)\r\n- Updated Korean Language (#2871)\r\n- Decouple statistic and TCPRelay (#2872)\r\n- Fix nLogConfig NullReferenceExceltion (#2887)\r\n- Use v2ray GeoSsite to replace GFWList (#2875)\r\n- Optimize the updater and downloader (#2910)\r\n- Update SIP002 (#2904)\r\n- Update Japanese translations\r\n- Fix improperly parsed remark section (#2935)\r\n- Other minor bug fixes and improvements\r\n\r\n4.1.10.0 2020-04-11\r\n- Fix NLog config file issue (#2841, #2846)\r\n- Tweak log level\r\n\r\n4.1.9.3 2020-03-31\r\n- Set default method to chacha20-ietf-poly1305\r\n- Using hash in PAC URL (#2759)\r\n- Rename and translate title of statistics form (#2768)\r\n- Russian translation (#2767)\r\n- Refine Updated Notification logic\r\n- Using NLog (#2783)\r\n- Bug fix: wrong server in tray menu (#2782)\r\n- Deprecate unsafe encryption method (#2757, #2801)\r\n- Bug fix: server config is overwritten by others when moving up/down (#2830)\r\n- Other minor bug fixes and improvements\r\n\r\n4.1.9.2 2019-12-25\r\n- Fix i18n issues (#2740, #2741)\r\n\r\n4.1.9.1 2019-12-22\r\n- Fix #2739: PAC does not work\r\n- Translate Show Plugin Option\r\n\r\n4.1.9.0 2019-12-21\r\n- Refine merge PAC+abp script logic (#2598)\r\n- Format the proxy hostname in GfwListUpdater (#2616)\r\n- Fix the trayIcon display issue under Win10 dark theme (#2658)\r\n- Set default encryption method as chacha20-ietf-poly1305 (#2699)\r\n- Translate statistics config form (#2698)\r\n- Update .Net Framework download link (#2731)\r\n- Use MD5 hash instead of timestamp for PAC URL parameter (#2705)\r\n- Add option \"Show Plugin Output\" (#2722)\r\n- Support custom GFWListUrl defined in config file (#2728)\r\n- Implement new I18N csv structure (#2712)\r\n- Refine message when plugin program file does not exist (#2730)\r\n- Other minor bug fixes and improvements\r\n\r\n4.1.8 2019-10-31\r\n- Update the nuget configurations and packages\r\n- Fix some crash about thread-safe in statistics (#2591)\r\n- Fix server list index invalidation (#2543, #2542)\r\n- Refine PAC server (#2539)\r\n- Update the GFWList via IPv6Loopback when available\r\n- Modify PAC request behavior (#2526)\r\n- Fix .NET 4.7.2 on Win7 TLS compatibility (#2473)\r\n- Other minor bug fixes and improvements\r\n\r\n4.1.7.1 2019-07-14\r\n- Fix unexpected server delete behavior (#2459)\r\n- Reduce info log when checking Windows 10 Light Theme\r\n\r\n4.1.7 2019-07-10\r\n- Fix UDP relay (#2387)\r\n- Support Windows 10 1903 Light Theme (#2379)\r\n- Listening on local IPv6 interface (#2419) (Experimental)\r\n- Turn off per-monitor DPI awareness as it is not supported (#2427)\r\n- Fix a defect when parsing ss:// URL (#2364)\r\n- Upgrade the development environment to VS2017 with .NET Framework 4.7.2\r\n- Refactoring config form (#2410)\r\n- Refactoring tray icon\r\n- Other minor bug fixes and improvements\r\n\r\n4.1.6 2019-04-17\r\n- Add http proxy \"basic access authentication\"\r\n- Add check box to toggle plugin argument input\r\n- Add apply button for server configuration form\r\n- Update UI of switching proxy mode\r\n- Update exception handler for port assignment\r\n\r\n4.1.5 2019-03-08\r\n- Update nuget packages\r\n- Update the PAC javascript to support user rules in a better way\r\n- Other minor bug fixes and improvements\r\n\r\n4.1.4 2019-02-04\r\n- Update Privoxy to 3.0.28\r\n- Enlarge Privoxy max client connections\r\n- Update the system proxy when user-rule.txt is changed\r\n- Register restart after system reboot\r\n\r\n4.1.3.1 2018-12-09\r\n- Fix error when usersettings bypasslist is null\r\n\r\n4.1.3 2018-12-08\r\n- Refine sysproxy exception handling\r\n- Keep user bypass setting when use global proxy mode\r\n- Update .Net download link\r\n- Minor improvements\r\n\r\n4.1.2 2018-09-13\r\n- Fix plugin CLI argument environment variable issue (#1969 #1818)\r\n- Other minor bug fixes and improvements (#1978 #1968 #1993)\r\n\r\n4.1.1 2018-08-18\r\n- Fix auto hotkey reg issue when OS wakeup\r\n- Other minor bug fixes and improvements\r\n\r\n4.1.0 2018-08-05\r\n- Support portable mode Temp folder\r\n- Register hotkeys on startup\r\n- Fix sysproxy hanging issue\r\n- Minor improvements\r\n\r\n4.0.10 2018-05-10\r\n- Add square bracket for SIP002 IPv6 (RFC3986)\r\n- Add plugin CLI arguments support\r\n- Bug fix: Server address should not be encoded (#1758)\r\n- Bug fix: Wrong splash on multi display (#1729)\r\n- Fix PerPixelAlphaForm's issue in designer\r\n- Other minor bug fixes and improvements\r\n\r\n4.0.9 2018-03-14\r\n- Fix port occupied issue\r\n- Add xchacha20-ietf-poly1305\r\n- Update cryptographic libraries\r\n- Bug fixes and improvements\r\n\r\n4.0.8 2018-02-16\r\n- Add OpenSSL 1.1.0g support #1671\r\n- Update nuget packages\r\n- Bug fixes and improvements\r\n\r\n4.0.7 2017-12-09\r\n- Fix QR code and ss:// protocol import issue\r\n- Add an option to show password\r\n- User rules have higher priority in PAC file\r\n- Bug fixes and improvements\r\n\r\n4.0.6 2017-09-09\r\n- SIP002 support\r\n- SIP003 support\r\n\r\n4.0.5 2017-08-09\r\n- Fix crash when user-wininet.json fail to parse. (#1178)\r\n- Bug fixes and improvements.\r\n\r\n4.0.4 2017-06-01\r\n- Save user wininet settings as user-wininet.json\r\n- Improve performance of aes-256-gcm\r\n\r\n4.0.2 2017-05-19\r\n- Fix legacy key derivation\r\n- Bug fixes and improvements\r\n\r\n4.0.1 2017-04-08\r\n- Fix UDP relay\r\n- Allow to add multiple servers via Shadowsocks URL\r\n- Bug fixes and improvements\r\n\r\n4.0 2017-04-04\r\n- Add AEAD ciphers support, removed OTA\r\n- I18N: add Japanese support, update Traditional Chinese strings\r\n- sysproxy: restore user settings when system proxy is turned off\r\n- Bug fixes and improvements\r\n\r\n3.4.3 2017-1-11\r\n- Make the previous portable mode as default\r\n- Refine networking by Noisyfox\r\n- Bug fixes and improvements\r\n\r\n3.4.2.1 2016-12-30\r\n- Refine Traditional Chinese translation by LNDDYL\r\n- sysproxy: reduce false positives on virus detection\r\n- sysproxy: set LAN proxy settings even if RAS query fails\r\n- privoxy: drop obsolete tray area refreshing code\r\n- Fix auto startup\r\n- Bug fixes and improvements\r\n\r\n3.4.2 2016-12-16\r\n- Fix null ref in TCPRelay. (#940)\r\n- Bring Privoxy back. (#948)\r\n- Bug fixes and improvements.\r\n\r\n3.4.1 (pre-release) 2016-12-13\r\n- Fix crash if user input an invaild server address. (#933)\r\n- Fix ERR_TOO_MANY_REDIRECTS with http proxy. (#937)\r\n- Show SS URL in QRCode form.\r\n- Add import URL from clipboard.\r\n- Bug fixes and improvements.\r\n\r\n3.4.0 (pre-release) 2016-12-9\r\n- Replace Privoxy with built-in http proxy.\r\n- Try fix system proxy settings on windows 10 insider preview.\r\n- Secure local pac.\r\n- Update bypass list.\r\n- Bug fixes and improvements.\r\n\r\n3.3.6 2016-12-6\r\n- Refine system proxy mode switching logic,\r\n  merge 'Switch to PAC' and 'Switch to Global' into\r\n  'Switch system proxy mode'.\r\n- Don't store LogViewer window size in config file,\r\n  now you can sync config between devices with different\r\n  resolutions.\r\n- Add tag support for SS url\r\n- Add pre-release channel in update checker\r\n- Bug fixes and improvements\r\n\r\n3.3.5 2016-11-7\r\n- Improve system power mode handling\r\n- Update mbed TLS to 2.4.0\r\n- Check .NET Framework version on startup\r\n\r\n3.3.4 2016-10-21\r\n- Fix IE dial-up and VPN connection proxy settings\r\n  not changed since release 3.3.3.\r\n- Fix a UI bug\r\n\r\n3.3.3 2016-10-10\r\n- Add timeout support for server and forward proxy,\r\n  only integer is allowed\r\n- Use wininet API to setup system proxy\r\n- Upgrade to .NET Framework 4.6.2\r\n\r\n3.3.2 2016-10-03\r\n- Add HTTP forward proxy support\r\n- Bug fixes and improvements\r\n\r\n3.3.1 2016-09-20\r\n- Add global hotkey support\r\n- Bug fixes and improvements\r\n\r\n3.3 2016-09-09\r\n- Update Privoxy to 3.0.26\r\n- Change minimum system version explicitly to Windows Vista\r\n  since we are using dual-mode socket\r\n- Support running multiple instances of Privoxy for system proxy\r\n- Improve networking\r\n- New traffic chart and icon style\r\n- I18N: Traditional Chinese support\r\n- Bug fixes and improvements\r\n\r\n3.2 2016-08-13\r\n- Add AES-CTR, blowfish and camellia ciphers support,\r\n  including aes-256-ctr, aes-192-ctr, aes-128-ctr,\r\n  bf-cfb, camellia-128-cfb, camellia-192-cfb\r\n  and camellia-256-cfb.\r\n- Support one-time authentication in ss urls for sharing\r\n- Support traffic chart and traffic icon\r\n- Add proxy support\r\n- Add verbose logging\r\n- Improve LogForm\r\n- Delete log file when clicking \"Clean Logs\" in the LogForm\r\n- Bug fixes and improvements\r\n\r\n3.1 2016-05-01\r\n- Disable StatisticsStrategy by default\r\n\r\n3.0 2016-03-02\r\n- Update Privoxy to 3.0.24\r\n- Replace Choose by Total Packet Loss with Choose by Statistics\r\n- Support chacha20-ietf\r\n- Support Onetime Authentication\r\n- Optional checking updates\r\n- Download updates automatically\r\n- Improve log viewer\r\n- Minor fixes\r\n- Other improvements\r\n\r\n2.5.8 2015-09-20\r\n- Update GFWList url\r\n\r\n2.5.7 2015-09-19\r\n- Fix repeated IV\r\n\r\n2.5.6 2015-08-19\r\n- Add portable mode. Create shadowsocks_portable_mode.txt to use it\r\n- Support server reorder\r\n\r\n2.5.5 2015-08-17\r\n- Fix crash when enabling Availability Statistics and some servers can not be resolved\r\n- Allow multiple instances\r\n- Other fixes\r\n\r\n2.5.4 2015-08-16\r\n- Hide Privoxy icon\r\n\r\n2.5.3 2015-08-16\r\n- Replace Polipo with Privoxy\r\n- Add Choose by Total Packet Loss\r\n\r\n2.5.2 2015-08-04\r\n- Add log viewer\r\n\r\n2.5.1 2015-07-26\r\n- Prevent HA from switching servers too frequently\r\n- Fix server settings can not be updated when using HA\r\n- Fix server port can't be 8123\r\n- Other minor fixes\r\n\r\n2.5 2015-07-25\r\n- Support load balance\r\n- Support high availability\r\n\r\n2.4 2015-07-11\r\n- Support UDP relay\r\n- Support online PAC\r\n- Migrate update checker to GitHub releases\r\n- Other fixes\r\n\r\n2.3.1 2015-03-06\r\n- Support user rule\r\n\r\n2.3 2015-01-25\r\n- Use the same port for every profile\r\n- Use the same port for HTTP/Socks5/PAC\r\n- Fix GFWList PAC compatibility issue with IE11\r\n- Encourage users to report to GFWList when no update found\r\n- Minor UI improvements\r\n\r\n2.2.1 2015-01-18\r\n- Fix QR Code compatibility\r\n\r\n2.2 2015-01-14\r\n- Support updating PAC from GFWList\r\n- Support adding server by scanning QR Code\r\n- Output timestamp in logs\r\n- Minor fixes\r\n\r\n2.1.6 2015-01-02\r\n- Fix OPTIONS requests\r\n- Improve logs\r\n\r\n2.1.5 2014-12-25\r\n- Fix QR Code compatibility with iOS\r\n- Only left button will trigger double click on tray icon\r\n\r\n2.1.4 2014-12-20\r\n- Fix crash when remarks are too long\r\n\r\n2.1.3 2014-12-20\r\n- Add Chinese Language\r\n- Fix some UI issues on Windows 8\r\n- Fix some UI issues on high DPI screens\r\n- Log bind error more friendly\r\n- Stability issues\r\n\r\n2.1.2 2014-12-14\r\n- Fix sometimes Shadowsocks doesn't respond to requests\r\n\r\n2.1.1 2014-12-14\r\n- Add global proxy option\r\n\r\n2.1 2014-12-12\r\n- Add salsa20 and chacha20 support\r\n\r\n2.0.11 2014-11-23\r\n- Fix a crash\r\n- Only switch the system proxy off if we have switched it on\r\n\r\n2.0.10 2014-11-18\r\n- Minor fixes\r\n- Optimize code\r\n\r\n2.0.9 2014-11-13\r\n- Fix startup path\r\n- Fix allowed port range for polipo\r\n\r\n2.0.8 2014-11-12\r\n- Fix data corruption\r\n- Set proxy for PPPoE\r\n- Auto Startup Option\r\n- Support high DPI screens\r\n\r\n2.0.7 2014-11-11\r\n- Use OpenSSL for now\r\n\r\n2.0.6 2014-11-10\r\n- Minor bug fixes\r\n\r\n2.0.5 2014-11-09\r\n- Fix QRCode size\r\n- Share over LAN option\r\n- Log to temp path instead\r\n\r\n2.0.4 2014-11-09\r\n- Try to fix data corruption\r\n- Remove all configuration except x86\r\n\r\n2.0.3 2014-11-08\r\n- Support QRCode generation\r\n- Fix compatibility issues with some Chrome version\r\n\r\n2.0.2 2014-11-08\r\n- Add remarks\r\n- Fix error when polipo is killed\r\n\r\n2.0.1 2014-11-08\r\n- Check already running\r\n\r\n2.0 2014-11-08\r\n- Initial release\r\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "How to Contribute\n=================\n\nPull Requests\n-------------\n\n1. Pull requests are welcome.\n2. Make sure to pass the unit tests. Write unit tests for new modules if\nneeded.\n3. Search before sending new pull request.\n\nIssues\n------\n\n1. **DO NOT post question about connection problem in issue tracker**, read [Troubleshooting].\n2. Search before sending new issue.\n\n[Troubleshooting]: https://github.com/shadowsocks/shadowsocks-windows/wiki/Troubleshooting\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "shadowsocks-csharp\r\n==================\r\n\r\n                    GNU GENERAL PUBLIC LICENSE\r\n                       Version 3, 29 June 2007\r\n\r\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\r\n Everyone is permitted to copy and distribute verbatim copies\r\n of this license document, but changing it is not allowed.\r\n\r\n                            Preamble\r\n\r\n  The GNU General Public License is a free, copyleft license for\r\nsoftware and other kinds of works.\r\n\r\n  The licenses for most software and other practical works are designed\r\nto take away your freedom to share and change the works.  By contrast,\r\nthe GNU General Public License is intended to guarantee your freedom to\r\nshare and change all versions of a program--to make sure it remains free\r\nsoftware for all its users.  We, the Free Software Foundation, use the\r\nGNU General Public License for most of our software; it applies also to\r\nany other work released this way by its authors.  You can apply it to\r\nyour programs, too.\r\n\r\n  When we speak of free software, we are referring to freedom, not\r\nprice.  Our General Public Licenses are designed to make sure that you\r\nhave the freedom to distribute copies of free software (and charge for\r\nthem if you wish), that you receive source code or can get it if you\r\nwant it, that you can change the software or use pieces of it in new\r\nfree programs, and that you know you can do these things.\r\n\r\n  To protect your rights, we need to prevent others from denying you\r\nthese rights or asking you to surrender the rights.  Therefore, you have\r\ncertain responsibilities if you distribute copies of the software, or if\r\nyou modify it: responsibilities to respect the freedom of others.\r\n\r\n  For example, if you distribute copies of such a program, whether\r\ngratis or for a fee, you must pass on to the recipients the same\r\nfreedoms that you received.  You must make sure that they, too, receive\r\nor can get the source code.  And you must show them these terms so they\r\nknow their rights.\r\n\r\n  Developers that use the GNU GPL protect your rights with two steps:\r\n(1) assert copyright on the software, and (2) offer you this License\r\ngiving you legal permission to copy, distribute and/or modify it.\r\n\r\n  For the developers' and authors' protection, the GPL clearly explains\r\nthat there is no warranty for this free software.  For both users' and\r\nauthors' sake, the GPL requires that modified versions be marked as\r\nchanged, so that their problems will not be attributed erroneously to\r\nauthors of previous versions.\r\n\r\n  Some devices are designed to deny users access to install or run\r\nmodified versions of the software inside them, although the manufacturer\r\ncan do so.  This is fundamentally incompatible with the aim of\r\nprotecting users' freedom to change the software.  The systematic\r\npattern of such abuse occurs in the area of products for individuals to\r\nuse, which is precisely where it is most unacceptable.  Therefore, we\r\nhave designed this version of the GPL to prohibit the practice for those\r\nproducts.  If such problems arise substantially in other domains, we\r\nstand ready to extend this provision to those domains in future versions\r\nof the GPL, as needed to protect the freedom of users.\r\n\r\n  Finally, every program is threatened constantly by software patents.\r\nStates should not allow patents to restrict development and use of\r\nsoftware on general-purpose computers, but in those that do, we wish to\r\navoid the special danger that patents applied to a free program could\r\nmake it effectively proprietary.  To prevent this, the GPL assures that\r\npatents cannot be used to render the program non-free.\r\n\r\n  The precise terms and conditions for copying, distribution and\r\nmodification follow.\r\n\r\n                       TERMS AND CONDITIONS\r\n\r\n  0. Definitions.\r\n\r\n  \"This License\" refers to version 3 of the GNU General Public License.\r\n\r\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\r\nworks, such as semiconductor masks.\r\n\r\n  \"The Program\" refers to any copyrightable work licensed under this\r\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\r\n\"recipients\" may be individuals or organizations.\r\n\r\n  To \"modify\" a work means to copy from or adapt all or part of the work\r\nin a fashion requiring copyright permission, other than the making of an\r\nexact copy.  The resulting work is called a \"modified version\" of the\r\nearlier work or a work \"based on\" the earlier work.\r\n\r\n  A \"covered work\" means either the unmodified Program or a work based\r\non the Program.\r\n\r\n  To \"propagate\" a work means to do anything with it that, without\r\npermission, would make you directly or secondarily liable for\r\ninfringement under applicable copyright law, except executing it on a\r\ncomputer or modifying a private copy.  Propagation includes copying,\r\ndistribution (with or without modification), making available to the\r\npublic, and in some countries other activities as well.\r\n\r\n  To \"convey\" a work means any kind of propagation that enables other\r\nparties to make or receive copies.  Mere interaction with a user through\r\na computer network, with no transfer of a copy, is not conveying.\r\n\r\n  An interactive user interface displays \"Appropriate Legal Notices\"\r\nto the extent that it includes a convenient and prominently visible\r\nfeature that (1) displays an appropriate copyright notice, and (2)\r\ntells the user that there is no warranty for the work (except to the\r\nextent that warranties are provided), that licensees may convey the\r\nwork under this License, and how to view a copy of this License.  If\r\nthe interface presents a list of user commands or options, such as a\r\nmenu, a prominent item in the list meets this criterion.\r\n\r\n  1. Source Code.\r\n\r\n  The \"source code\" for a work means the preferred form of the work\r\nfor making modifications to it.  \"Object code\" means any non-source\r\nform of a work.\r\n\r\n  A \"Standard Interface\" means an interface that either is an official\r\nstandard defined by a recognized standards body, or, in the case of\r\ninterfaces specified for a particular programming language, one that\r\nis widely used among developers working in that language.\r\n\r\n  The \"System Libraries\" of an executable work include anything, other\r\nthan the work as a whole, that (a) is included in the normal form of\r\npackaging a Major Component, but which is not part of that Major\r\nComponent, and (b) serves only to enable use of the work with that\r\nMajor Component, or to implement a Standard Interface for which an\r\nimplementation is available to the public in source code form.  A\r\n\"Major Component\", in this context, means a major essential component\r\n(kernel, window system, and so on) of the specific operating system\r\n(if any) on which the executable work runs, or a compiler used to\r\nproduce the work, or an object code interpreter used to run it.\r\n\r\n  The \"Corresponding Source\" for a work in object code form means all\r\nthe source code needed to generate, install, and (for an executable\r\nwork) run the object code and to modify the work, including scripts to\r\ncontrol those activities.  However, it does not include the work's\r\nSystem Libraries, or general-purpose tools or generally available free\r\nprograms which are used unmodified in performing those activities but\r\nwhich are not part of the work.  For example, Corresponding Source\r\nincludes interface definition files associated with source files for\r\nthe work, and the source code for shared libraries and dynamically\r\nlinked subprograms that the work is specifically designed to require,\r\nsuch as by intimate data communication or control flow between those\r\nsubprograms and other parts of the work.\r\n\r\n  The Corresponding Source need not include anything that users\r\ncan regenerate automatically from other parts of the Corresponding\r\nSource.\r\n\r\n  The Corresponding Source for a work in source code form is that\r\nsame work.\r\n\r\n  2. Basic Permissions.\r\n\r\n  All rights granted under this License are granted for the term of\r\ncopyright on the Program, and are irrevocable provided the stated\r\nconditions are met.  This License explicitly affirms your unlimited\r\npermission to run the unmodified Program.  The output from running a\r\ncovered work is covered by this License only if the output, given its\r\ncontent, constitutes a covered work.  This License acknowledges your\r\nrights of fair use or other equivalent, as provided by copyright law.\r\n\r\n  You may make, run and propagate covered works that you do not\r\nconvey, without conditions so long as your license otherwise remains\r\nin force.  You may convey covered works to others for the sole purpose\r\nof having them make modifications exclusively for you, or provide you\r\nwith facilities for running those works, provided that you comply with\r\nthe terms of this License in conveying all material for which you do\r\nnot control copyright.  Those thus making or running the covered works\r\nfor you must do so exclusively on your behalf, under your direction\r\nand control, on terms that prohibit them from making any copies of\r\nyour copyrighted material outside their relationship with you.\r\n\r\n  Conveying under any other circumstances is permitted solely under\r\nthe conditions stated below.  Sublicensing is not allowed; section 10\r\nmakes it unnecessary.\r\n\r\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\r\n\r\n  No covered work shall be deemed part of an effective technological\r\nmeasure under any applicable law fulfilling obligations under article\r\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\r\nsimilar laws prohibiting or restricting circumvention of such\r\nmeasures.\r\n\r\n  When you convey a covered work, you waive any legal power to forbid\r\ncircumvention of technological measures to the extent such circumvention\r\nis effected by exercising rights under this License with respect to\r\nthe covered work, and you disclaim any intention to limit operation or\r\nmodification of the work as a means of enforcing, against the work's\r\nusers, your or third parties' legal rights to forbid circumvention of\r\ntechnological measures.\r\n\r\n  4. Conveying Verbatim Copies.\r\n\r\n  You may convey verbatim copies of the Program's source code as you\r\nreceive it, in any medium, provided that you conspicuously and\r\nappropriately publish on each copy an appropriate copyright notice;\r\nkeep intact all notices stating that this License and any\r\nnon-permissive terms added in accord with section 7 apply to the code;\r\nkeep intact all notices of the absence of any warranty; and give all\r\nrecipients a copy of this License along with the Program.\r\n\r\n  You may charge any price or no price for each copy that you convey,\r\nand you may offer support or warranty protection for a fee.\r\n\r\n  5. Conveying Modified Source Versions.\r\n\r\n  You may convey a work based on the Program, or the modifications to\r\nproduce it from the Program, in the form of source code under the\r\nterms of section 4, provided that you also meet all of these conditions:\r\n\r\n    a) The work must carry prominent notices stating that you modified\r\n    it, and giving a relevant date.\r\n\r\n    b) The work must carry prominent notices stating that it is\r\n    released under this License and any conditions added under section\r\n    7.  This requirement modifies the requirement in section 4 to\r\n    \"keep intact all notices\".\r\n\r\n    c) You must license the entire work, as a whole, under this\r\n    License to anyone who comes into possession of a copy.  This\r\n    License will therefore apply, along with any applicable section 7\r\n    additional terms, to the whole of the work, and all its parts,\r\n    regardless of how they are packaged.  This License gives no\r\n    permission to license the work in any other way, but it does not\r\n    invalidate such permission if you have separately received it.\r\n\r\n    d) If the work has interactive user interfaces, each must display\r\n    Appropriate Legal Notices; however, if the Program has interactive\r\n    interfaces that do not display Appropriate Legal Notices, your\r\n    work need not make them do so.\r\n\r\n  A compilation of a covered work with other separate and independent\r\nworks, which are not by their nature extensions of the covered work,\r\nand which are not combined with it such as to form a larger program,\r\nin or on a volume of a storage or distribution medium, is called an\r\n\"aggregate\" if the compilation and its resulting copyright are not\r\nused to limit the access or legal rights of the compilation's users\r\nbeyond what the individual works permit.  Inclusion of a covered work\r\nin an aggregate does not cause this License to apply to the other\r\nparts of the aggregate.\r\n\r\n  6. Conveying Non-Source Forms.\r\n\r\n  You may convey a covered work in object code form under the terms\r\nof sections 4 and 5, provided that you also convey the\r\nmachine-readable Corresponding Source under the terms of this License,\r\nin one of these ways:\r\n\r\n    a) Convey the object code in, or embodied in, a physical product\r\n    (including a physical distribution medium), accompanied by the\r\n    Corresponding Source fixed on a durable physical medium\r\n    customarily used for software interchange.\r\n\r\n    b) Convey the object code in, or embodied in, a physical product\r\n    (including a physical distribution medium), accompanied by a\r\n    written offer, valid for at least three years and valid for as\r\n    long as you offer spare parts or customer support for that product\r\n    model, to give anyone who possesses the object code either (1) a\r\n    copy of the Corresponding Source for all the software in the\r\n    product that is covered by this License, on a durable physical\r\n    medium customarily used for software interchange, for a price no\r\n    more than your reasonable cost of physically performing this\r\n    conveying of source, or (2) access to copy the\r\n    Corresponding Source from a network server at no charge.\r\n\r\n    c) Convey individual copies of the object code with a copy of the\r\n    written offer to provide the Corresponding Source.  This\r\n    alternative is allowed only occasionally and noncommercially, and\r\n    only if you received the object code with such an offer, in accord\r\n    with subsection 6b.\r\n\r\n    d) Convey the object code by offering access from a designated\r\n    place (gratis or for a charge), and offer equivalent access to the\r\n    Corresponding Source in the same way through the same place at no\r\n    further charge.  You need not require recipients to copy the\r\n    Corresponding Source along with the object code.  If the place to\r\n    copy the object code is a network server, the Corresponding Source\r\n    may be on a different server (operated by you or a third party)\r\n    that supports equivalent copying facilities, provided you maintain\r\n    clear directions next to the object code saying where to find the\r\n    Corresponding Source.  Regardless of what server hosts the\r\n    Corresponding Source, you remain obligated to ensure that it is\r\n    available for as long as needed to satisfy these requirements.\r\n\r\n    e) Convey the object code using peer-to-peer transmission, provided\r\n    you inform other peers where the object code and Corresponding\r\n    Source of the work are being offered to the general public at no\r\n    charge under subsection 6d.\r\n\r\n  A separable portion of the object code, whose source code is excluded\r\nfrom the Corresponding Source as a System Library, need not be\r\nincluded in conveying the object code work.\r\n\r\n  A \"User Product\" is either (1) a \"consumer product\", which means any\r\ntangible personal property which is normally used for personal, family,\r\nor household purposes, or (2) anything designed or sold for incorporation\r\ninto a dwelling.  In determining whether a product is a consumer product,\r\ndoubtful cases shall be resolved in favor of coverage.  For a particular\r\nproduct received by a particular user, \"normally used\" refers to a\r\ntypical or common use of that class of product, regardless of the status\r\nof the particular user or of the way in which the particular user\r\nactually uses, or expects or is expected to use, the product.  A product\r\nis a consumer product regardless of whether the product has substantial\r\ncommercial, industrial or non-consumer uses, unless such uses represent\r\nthe only significant mode of use of the product.\r\n\r\n  \"Installation Information\" for a User Product means any methods,\r\nprocedures, authorization keys, or other information required to install\r\nand execute modified versions of a covered work in that User Product from\r\na modified version of its Corresponding Source.  The information must\r\nsuffice to ensure that the continued functioning of the modified object\r\ncode is in no case prevented or interfered with solely because\r\nmodification has been made.\r\n\r\n  If you convey an object code work under this section in, or with, or\r\nspecifically for use in, a User Product, and the conveying occurs as\r\npart of a transaction in which the right of possession and use of the\r\nUser Product is transferred to the recipient in perpetuity or for a\r\nfixed term (regardless of how the transaction is characterized), the\r\nCorresponding Source conveyed under this section must be accompanied\r\nby the Installation Information.  But this requirement does not apply\r\nif neither you nor any third party retains the ability to install\r\nmodified object code on the User Product (for example, the work has\r\nbeen installed in ROM).\r\n\r\n  The requirement to provide Installation Information does not include a\r\nrequirement to continue to provide support service, warranty, or updates\r\nfor a work that has been modified or installed by the recipient, or for\r\nthe User Product in which it has been modified or installed.  Access to a\r\nnetwork may be denied when the modification itself materially and\r\nadversely affects the operation of the network or violates the rules and\r\nprotocols for communication across the network.\r\n\r\n  Corresponding Source conveyed, and Installation Information provided,\r\nin accord with this section must be in a format that is publicly\r\ndocumented (and with an implementation available to the public in\r\nsource code form), and must require no special password or key for\r\nunpacking, reading or copying.\r\n\r\n  7. Additional Terms.\r\n\r\n  \"Additional permissions\" are terms that supplement the terms of this\r\nLicense by making exceptions from one or more of its conditions.\r\nAdditional permissions that are applicable to the entire Program shall\r\nbe treated as though they were included in this License, to the extent\r\nthat they are valid under applicable law.  If additional permissions\r\napply only to part of the Program, that part may be used separately\r\nunder those permissions, but the entire Program remains governed by\r\nthis License without regard to the additional permissions.\r\n\r\n  When you convey a copy of a covered work, you may at your option\r\nremove any additional permissions from that copy, or from any part of\r\nit.  (Additional permissions may be written to require their own\r\nremoval in certain cases when you modify the work.)  You may place\r\nadditional permissions on material, added by you to a covered work,\r\nfor which you have or can give appropriate copyright permission.\r\n\r\n  Notwithstanding any other provision of this License, for material you\r\nadd to a covered work, you may (if authorized by the copyright holders of\r\nthat material) supplement the terms of this License with terms:\r\n\r\n    a) Disclaiming warranty or limiting liability differently from the\r\n    terms of sections 15 and 16 of this License; or\r\n\r\n    b) Requiring preservation of specified reasonable legal notices or\r\n    author attributions in that material or in the Appropriate Legal\r\n    Notices displayed by works containing it; or\r\n\r\n    c) Prohibiting misrepresentation of the origin of that material, or\r\n    requiring that modified versions of such material be marked in\r\n    reasonable ways as different from the original version; or\r\n\r\n    d) Limiting the use for publicity purposes of names of licensors or\r\n    authors of the material; or\r\n\r\n    e) Declining to grant rights under trademark law for use of some\r\n    trade names, trademarks, or service marks; or\r\n\r\n    f) Requiring indemnification of licensors and authors of that\r\n    material by anyone who conveys the material (or modified versions of\r\n    it) with contractual assumptions of liability to the recipient, for\r\n    any liability that these contractual assumptions directly impose on\r\n    those licensors and authors.\r\n\r\n  All other non-permissive additional terms are considered \"further\r\nrestrictions\" within the meaning of section 10.  If the Program as you\r\nreceived it, or any part of it, contains a notice stating that it is\r\ngoverned by this License along with a term that is a further\r\nrestriction, you may remove that term.  If a license document contains\r\na further restriction but permits relicensing or conveying under this\r\nLicense, you may add to a covered work material governed by the terms\r\nof that license document, provided that the further restriction does\r\nnot survive such relicensing or conveying.\r\n\r\n  If you add terms to a covered work in accord with this section, you\r\nmust place, in the relevant source files, a statement of the\r\nadditional terms that apply to those files, or a notice indicating\r\nwhere to find the applicable terms.\r\n\r\n  Additional terms, permissive or non-permissive, may be stated in the\r\nform of a separately written license, or stated as exceptions;\r\nthe above requirements apply either way.\r\n\r\n  8. Termination.\r\n\r\n  You may not propagate or modify a covered work except as expressly\r\nprovided under this License.  Any attempt otherwise to propagate or\r\nmodify it is void, and will automatically terminate your rights under\r\nthis License (including any patent licenses granted under the third\r\nparagraph of section 11).\r\n\r\n  However, if you cease all violation of this License, then your\r\nlicense from a particular copyright holder is reinstated (a)\r\nprovisionally, unless and until the copyright holder explicitly and\r\nfinally terminates your license, and (b) permanently, if the copyright\r\nholder fails to notify you of the violation by some reasonable means\r\nprior to 60 days after the cessation.\r\n\r\n  Moreover, your license from a particular copyright holder is\r\nreinstated permanently if the copyright holder notifies you of the\r\nviolation by some reasonable means, this is the first time you have\r\nreceived notice of violation of this License (for any work) from that\r\ncopyright holder, and you cure the violation prior to 30 days after\r\nyour receipt of the notice.\r\n\r\n  Termination of your rights under this section does not terminate the\r\nlicenses of parties who have received copies or rights from you under\r\nthis License.  If your rights have been terminated and not permanently\r\nreinstated, you do not qualify to receive new licenses for the same\r\nmaterial under section 10.\r\n\r\n  9. Acceptance Not Required for Having Copies.\r\n\r\n  You are not required to accept this License in order to receive or\r\nrun a copy of the Program.  Ancillary propagation of a covered work\r\noccurring solely as a consequence of using peer-to-peer transmission\r\nto receive a copy likewise does not require acceptance.  However,\r\nnothing other than this License grants you permission to propagate or\r\nmodify any covered work.  These actions infringe copyright if you do\r\nnot accept this License.  Therefore, by modifying or propagating a\r\ncovered work, you indicate your acceptance of this License to do so.\r\n\r\n  10. Automatic Licensing of Downstream Recipients.\r\n\r\n  Each time you convey a covered work, the recipient automatically\r\nreceives a license from the original licensors, to run, modify and\r\npropagate that work, subject to this License.  You are not responsible\r\nfor enforcing compliance by third parties with this License.\r\n\r\n  An \"entity transaction\" is a transaction transferring control of an\r\norganization, or substantially all assets of one, or subdividing an\r\norganization, or merging organizations.  If propagation of a covered\r\nwork results from an entity transaction, each party to that\r\ntransaction who receives a copy of the work also receives whatever\r\nlicenses to the work the party's predecessor in interest had or could\r\ngive under the previous paragraph, plus a right to possession of the\r\nCorresponding Source of the work from the predecessor in interest, if\r\nthe predecessor has it or can get it with reasonable efforts.\r\n\r\n  You may not impose any further restrictions on the exercise of the\r\nrights granted or affirmed under this License.  For example, you may\r\nnot impose a license fee, royalty, or other charge for exercise of\r\nrights granted under this License, and you may not initiate litigation\r\n(including a cross-claim or counterclaim in a lawsuit) alleging that\r\nany patent claim is infringed by making, using, selling, offering for\r\nsale, or importing the Program or any portion of it.\r\n\r\n  11. Patents.\r\n\r\n  A \"contributor\" is a copyright holder who authorizes use under this\r\nLicense of the Program or a work on which the Program is based.  The\r\nwork thus licensed is called the contributor's \"contributor version\".\r\n\r\n  A contributor's \"essential patent claims\" are all patent claims\r\nowned or controlled by the contributor, whether already acquired or\r\nhereafter acquired, that would be infringed by some manner, permitted\r\nby this License, of making, using, or selling its contributor version,\r\nbut do not include claims that would be infringed only as a\r\nconsequence of further modification of the contributor version.  For\r\npurposes of this definition, \"control\" includes the right to grant\r\npatent sublicenses in a manner consistent with the requirements of\r\nthis License.\r\n\r\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\r\npatent license under the contributor's essential patent claims, to\r\nmake, use, sell, offer for sale, import and otherwise run, modify and\r\npropagate the contents of its contributor version.\r\n\r\n  In the following three paragraphs, a \"patent license\" is any express\r\nagreement or commitment, however denominated, not to enforce a patent\r\n(such as an express permission to practice a patent or covenant not to\r\nsue for patent infringement).  To \"grant\" such a patent license to a\r\nparty means to make such an agreement or commitment not to enforce a\r\npatent against the party.\r\n\r\n  If you convey a covered work, knowingly relying on a patent license,\r\nand the Corresponding Source of the work is not available for anyone\r\nto copy, free of charge and under the terms of this License, through a\r\npublicly available network server or other readily accessible means,\r\nthen you must either (1) cause the Corresponding Source to be so\r\navailable, or (2) arrange to deprive yourself of the benefit of the\r\npatent license for this particular work, or (3) arrange, in a manner\r\nconsistent with the requirements of this License, to extend the patent\r\nlicense to downstream recipients.  \"Knowingly relying\" means you have\r\nactual knowledge that, but for the patent license, your conveying the\r\ncovered work in a country, or your recipient's use of the covered work\r\nin a country, would infringe one or more identifiable patents in that\r\ncountry that you have reason to believe are valid.\r\n\r\n  If, pursuant to or in connection with a single transaction or\r\narrangement, you convey, or propagate by procuring conveyance of, a\r\ncovered work, and grant a patent license to some of the parties\r\nreceiving the covered work authorizing them to use, propagate, modify\r\nor convey a specific copy of the covered work, then the patent license\r\nyou grant is automatically extended to all recipients of the covered\r\nwork and works based on it.\r\n\r\n  A patent license is \"discriminatory\" if it does not include within\r\nthe scope of its coverage, prohibits the exercise of, or is\r\nconditioned on the non-exercise of one or more of the rights that are\r\nspecifically granted under this License.  You may not convey a covered\r\nwork if you are a party to an arrangement with a third party that is\r\nin the business of distributing software, under which you make payment\r\nto the third party based on the extent of your activity of conveying\r\nthe work, and under which the third party grants, to any of the\r\nparties who would receive the covered work from you, a discriminatory\r\npatent license (a) in connection with copies of the covered work\r\nconveyed by you (or copies made from those copies), or (b) primarily\r\nfor and in connection with specific products or compilations that\r\ncontain the covered work, unless you entered into that arrangement,\r\nor that patent license was granted, prior to 28 March 2007.\r\n\r\n  Nothing in this License shall be construed as excluding or limiting\r\nany implied license or other defenses to infringement that may\r\notherwise be available to you under applicable patent law.\r\n\r\n  12. No Surrender of Others' Freedom.\r\n\r\n  If conditions are imposed on you (whether by court order, agreement or\r\notherwise) that contradict the conditions of this License, they do not\r\nexcuse you from the conditions of this License.  If you cannot convey a\r\ncovered work so as to satisfy simultaneously your obligations under this\r\nLicense and any other pertinent obligations, then as a consequence you may\r\nnot convey it at all.  For example, if you agree to terms that obligate you\r\nto collect a royalty for further conveying from those to whom you convey\r\nthe Program, the only way you could satisfy both those terms and this\r\nLicense would be to refrain entirely from conveying the Program.\r\n\r\n  13. Use with the GNU Affero General Public License.\r\n\r\n  Notwithstanding any other provision of this License, you have\r\npermission to link or combine any covered work with a work licensed\r\nunder version 3 of the GNU Affero General Public License into a single\r\ncombined work, and to convey the resulting work.  The terms of this\r\nLicense will continue to apply to the part which is the covered work,\r\nbut the special requirements of the GNU Affero General Public License,\r\nsection 13, concerning interaction through a network will apply to the\r\ncombination as such.\r\n\r\n  14. Revised Versions of this License.\r\n\r\n  The Free Software Foundation may publish revised and/or new versions of\r\nthe GNU General Public License from time to time.  Such new versions will\r\nbe similar in spirit to the present version, but may differ in detail to\r\naddress new problems or concerns.\r\n\r\n  Each version is given a distinguishing version number.  If the\r\nProgram specifies that a certain numbered version of the GNU General\r\nPublic License \"or any later version\" applies to it, you have the\r\noption of following the terms and conditions either of that numbered\r\nversion or of any later version published by the Free Software\r\nFoundation.  If the Program does not specify a version number of the\r\nGNU General Public License, you may choose any version ever published\r\nby the Free Software Foundation.\r\n\r\n  If the Program specifies that a proxy can decide which future\r\nversions of the GNU General Public License can be used, that proxy's\r\npublic statement of acceptance of a version permanently authorizes you\r\nto choose that version for the Program.\r\n\r\n  Later license versions may give you additional or different\r\npermissions.  However, no additional obligations are imposed on any\r\nauthor or copyright holder as a result of your choosing to follow a\r\nlater version.\r\n\r\n  15. Disclaimer of Warranty.\r\n\r\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\r\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\r\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\r\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\r\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\r\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\r\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\r\n\r\n  16. Limitation of Liability.\r\n\r\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\r\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\r\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\r\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\r\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\r\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\r\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\r\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\r\nSUCH DAMAGES.\r\n\r\n  17. Interpretation of Sections 15 and 16.\r\n\r\n  If the disclaimer of warranty and limitation of liability provided\r\nabove cannot be given local legal effect according to their terms,\r\nreviewing courts shall apply local law that most closely approximates\r\nan absolute waiver of all civil liability in connection with the\r\nProgram, unless a warranty or assumption of liability accompanies a\r\ncopy of the Program in return for a fee.\r\n\r\n                     END OF TERMS AND CONDITIONS\r\n\r\nCopyright (C) 2015 clowwindy <clowwindy42@gmail.com>\r\nCopyright (C) 2020 Shadowsocks Project <https://shadowsocks.org>\r\n\r\nThis program is free software: you can redistribute it and/or modify\r\nit under the terms of the GNU General Public License as published by\r\nthe Free Software Foundation, either version 3 of the License, or\r\n(at your option) any later version.\r\n\r\nThis program is distributed in the hope that it will be useful,\r\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\nGNU General Public License for more details.\r\n\r\nYou should have received a copy of the GNU General Public License\r\nalong with this program.  If not, see <http://www.gnu.org/licenses/>.\r\n\r\n\r\n3rd party projects\r\n==================\r\n\r\nPrivoxy\r\n------------------\r\n\r\n                    GNU GENERAL PUBLIC LICENSE\r\n                       Version 2, June 1991\r\n\r\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\r\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\r\n Everyone is permitted to copy and distribute verbatim copies\r\n of this license document, but changing it is not allowed.\r\n\r\n                            Preamble\r\n\r\n  The licenses for most software are designed to take away your\r\nfreedom to share and change it.  By contrast, the GNU General Public\r\nLicense is intended to guarantee your freedom to share and change free\r\nsoftware--to make sure the software is free for all its users.  This\r\nGeneral Public License applies to most of the Free Software\r\nFoundation's software and to any other program whose authors commit to\r\nusing it.  (Some other Free Software Foundation software is covered by\r\nthe GNU Lesser General Public License instead.)  You can apply it to\r\nyour programs, too.\r\n\r\n  When we speak of free software, we are referring to freedom, not\r\nprice.  Our General Public Licenses are designed to make sure that you\r\nhave the freedom to distribute copies of free software (and charge for\r\nthis service if you wish), that you receive source code or can get it\r\nif you want it, that you can change the software or use pieces of it\r\nin new free programs; and that you know you can do these things.\r\n\r\n  To protect your rights, we need to make restrictions that forbid\r\nanyone to deny you these rights or to ask you to surrender the rights.\r\nThese restrictions translate to certain responsibilities for you if you\r\ndistribute copies of the software, or if you modify it.\r\n\r\n  For example, if you distribute copies of such a program, whether\r\ngratis or for a fee, you must give the recipients all the rights that\r\nyou have.  You must make sure that they, too, receive or can get the\r\nsource code.  And you must show them these terms so they know their\r\nrights.\r\n\r\n  We protect your rights with two steps: (1) copyright the software, and\r\n(2) offer you this license which gives you legal permission to copy,\r\ndistribute and/or modify the software.\r\n\r\n  Also, for each author's protection and ours, we want to make certain\r\nthat everyone understands that there is no warranty for this free\r\nsoftware.  If the software is modified by someone else and passed on, we\r\nwant its recipients to know that what they have is not the original, so\r\nthat any problems introduced by others will not reflect on the original\r\nauthors' reputations.\r\n\r\n  Finally, any free program is threatened constantly by software\r\npatents.  We wish to avoid the danger that redistributors of a free\r\nprogram will individually obtain patent licenses, in effect making the\r\nprogram proprietary.  To prevent this, we have made it clear that any\r\npatent must be licensed for everyone's free use or not licensed at all.\r\n\r\n  The precise terms and conditions for copying, distribution and\r\nmodification follow.\r\n\r\n                    GNU GENERAL PUBLIC LICENSE\r\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\r\n\r\n  0. This License applies to any program or other work which contains\r\na notice placed by the copyright holder saying it may be distributed\r\nunder the terms of this General Public License.  The \"Program\", below,\r\nrefers to any such program or work, and a \"work based on the Program\"\r\nmeans either the Program or any derivative work under copyright law:\r\nthat is to say, a work containing the Program or a portion of it,\r\neither verbatim or with modifications and/or translated into another\r\nlanguage.  (Hereinafter, translation is included without limitation in\r\nthe term \"modification\".)  Each licensee is addressed as \"you\".\r\n\r\nActivities other than copying, distribution and modification are not\r\ncovered by this License; they are outside its scope.  The act of\r\nrunning the Program is not restricted, and the output from the Program\r\nis covered only if its contents constitute a work based on the\r\nProgram (independent of having been made by running the Program).\r\nWhether that is true depends on what the Program does.\r\n\r\n  1. You may copy and distribute verbatim copies of the Program's\r\nsource code as you receive it, in any medium, provided that you\r\nconspicuously and appropriately publish on each copy an appropriate\r\ncopyright notice and disclaimer of warranty; keep intact all the\r\nnotices that refer to this License and to the absence of any warranty;\r\nand give any other recipients of the Program a copy of this License\r\nalong with the Program.\r\n\r\nYou may charge a fee for the physical act of transferring a copy, and\r\nyou may at your option offer warranty protection in exchange for a fee.\r\n\r\n  2. You may modify your copy or copies of the Program or any portion\r\nof it, thus forming a work based on the Program, and copy and\r\ndistribute such modifications or work under the terms of Section 1\r\nabove, provided that you also meet all of these conditions:\r\n\r\n    a) You must cause the modified files to carry prominent notices\r\n    stating that you changed the files and the date of any change.\r\n\r\n    b) You must cause any work that you distribute or publish, that in\r\n    whole or in part contains or is derived from the Program or any\r\n    part thereof, to be licensed as a whole at no charge to all third\r\n    parties under the terms of this License.\r\n\r\n    c) If the modified program normally reads commands interactively\r\n    when run, you must cause it, when started running for such\r\n    interactive use in the most ordinary way, to print or display an\r\n    announcement including an appropriate copyright notice and a\r\n    notice that there is no warranty (or else, saying that you provide\r\n    a warranty) and that users may redistribute the program under\r\n    these conditions, and telling the user how to view a copy of this\r\n    License.  (Exception: if the Program itself is interactive but\r\n    does not normally print such an announcement, your work based on\r\n    the Program is not required to print an announcement.)\r\n\r\nThese requirements apply to the modified work as a whole.  If\r\nidentifiable sections of that work are not derived from the Program,\r\nand can be reasonably considered independent and separate works in\r\nthemselves, then this License, and its terms, do not apply to those\r\nsections when you distribute them as separate works.  But when you\r\ndistribute the same sections as part of a whole which is a work based\r\non the Program, the distribution of the whole must be on the terms of\r\nthis License, whose permissions for other licensees extend to the\r\nentire whole, and thus to each and every part regardless of who wrote it.\r\n\r\nThus, it is not the intent of this section to claim rights or contest\r\nyour rights to work written entirely by you; rather, the intent is to\r\nexercise the right to control the distribution of derivative or\r\ncollective works based on the Program.\r\n\r\nIn addition, mere aggregation of another work not based on the Program\r\nwith the Program (or with a work based on the Program) on a volume of\r\na storage or distribution medium does not bring the other work under\r\nthe scope of this License.\r\n\r\n  3. You may copy and distribute the Program (or a work based on it,\r\nunder Section 2) in object code or executable form under the terms of\r\nSections 1 and 2 above provided that you also do one of the following:\r\n\r\n    a) Accompany it with the complete corresponding machine-readable\r\n    source code, which must be distributed under the terms of Sections\r\n    1 and 2 above on a medium customarily used for software interchange; or,\r\n\r\n    b) Accompany it with a written offer, valid for at least three\r\n    years, to give any third party, for a charge no more than your\r\n    cost of physically performing source distribution, a complete\r\n    machine-readable copy of the corresponding source code, to be\r\n    distributed under the terms of Sections 1 and 2 above on a medium\r\n    customarily used for software interchange; or,\r\n\r\n    c) Accompany it with the information you received as to the offer\r\n    to distribute corresponding source code.  (This alternative is\r\n    allowed only for noncommercial distribution and only if you\r\n    received the program in object code or executable form with such\r\n    an offer, in accord with Subsection b above.)\r\n\r\nThe source code for a work means the preferred form of the work for\r\nmaking modifications to it.  For an executable work, complete source\r\ncode means all the source code for all modules it contains, plus any\r\nassociated interface definition files, plus the scripts used to\r\ncontrol compilation and installation of the executable.  However, as a\r\nspecial exception, the source code distributed need not include\r\nanything that is normally distributed (in either source or binary\r\nform) with the major components (compiler, kernel, and so on) of the\r\noperating system on which the executable runs, unless that component\r\nitself accompanies the executable.\r\n\r\nIf distribution of executable or object code is made by offering\r\naccess to copy from a designated place, then offering equivalent\r\naccess to copy the source code from the same place counts as\r\ndistribution of the source code, even though third parties are not\r\ncompelled to copy the source along with the object code.\r\n\r\n  4. You may not copy, modify, sublicense, or distribute the Program\r\nexcept as expressly provided under this License.  Any attempt\r\notherwise to copy, modify, sublicense or distribute the Program is\r\nvoid, and will automatically terminate your rights under this License.\r\nHowever, parties who have received copies, or rights, from you under\r\nthis License will not have their licenses terminated so long as such\r\nparties remain in full compliance.\r\n\r\n  5. You are not required to accept this License, since you have not\r\nsigned it.  However, nothing else grants you permission to modify or\r\ndistribute the Program or its derivative works.  These actions are\r\nprohibited by law if you do not accept this License.  Therefore, by\r\nmodifying or distributing the Program (or any work based on the\r\nProgram), you indicate your acceptance of this License to do so, and\r\nall its terms and conditions for copying, distributing or modifying\r\nthe Program or works based on it.\r\n\r\n  6. Each time you redistribute the Program (or any work based on the\r\nProgram), the recipient automatically receives a license from the\r\noriginal licensor to copy, distribute or modify the Program subject to\r\nthese terms and conditions.  You may not impose any further\r\nrestrictions on the recipients' exercise of the rights granted herein.\r\nYou are not responsible for enforcing compliance by third parties to\r\nthis License.\r\n\r\n  7. If, as a consequence of a court judgment or allegation of patent\r\ninfringement or for any other reason (not limited to patent issues),\r\nconditions are imposed on you (whether by court order, agreement or\r\notherwise) that contradict the conditions of this License, they do not\r\nexcuse you from the conditions of this License.  If you cannot\r\ndistribute so as to satisfy simultaneously your obligations under this\r\nLicense and any other pertinent obligations, then as a consequence you\r\nmay not distribute the Program at all.  For example, if a patent\r\nlicense would not permit royalty-free redistribution of the Program by\r\nall those who receive copies directly or indirectly through you, then\r\nthe only way you could satisfy both it and this License would be to\r\nrefrain entirely from distribution of the Program.\r\n\r\nIf any portion of this section is held invalid or unenforceable under\r\nany particular circumstance, the balance of the section is intended to\r\napply and the section as a whole is intended to apply in other\r\ncircumstances.\r\n\r\nIt is not the purpose of this section to induce you to infringe any\r\npatents or other property right claims or to contest validity of any\r\nsuch claims; this section has the sole purpose of protecting the\r\nintegrity of the free software distribution system, which is\r\nimplemented by public license practices.  Many people have made\r\ngenerous contributions to the wide range of software distributed\r\nthrough that system in reliance on consistent application of that\r\nsystem; it is up to the author/donor to decide if he or she is willing\r\nto distribute software through any other system and a licensee cannot\r\nimpose that choice.\r\n\r\nThis section is intended to make thoroughly clear what is believed to\r\nbe a consequence of the rest of this License.\r\n\r\n  8. If the distribution and/or use of the Program is restricted in\r\ncertain countries either by patents or by copyrighted interfaces, the\r\noriginal copyright holder who places the Program under this License\r\nmay add an explicit geographical distribution limitation excluding\r\nthose countries, so that distribution is permitted only in or among\r\ncountries not thus excluded.  In such case, this License incorporates\r\nthe limitation as if written in the body of this License.\r\n\r\n  9. The Free Software Foundation may publish revised and/or new versions\r\nof the General Public License from time to time.  Such new versions will\r\nbe similar in spirit to the present version, but may differ in detail to\r\naddress new problems or concerns.\r\n\r\nEach version is given a distinguishing version number.  If the Program\r\nspecifies a version number of this License which applies to it and \"any\r\nlater version\", you have the option of following the terms and conditions\r\neither of that version or of any later version published by the Free\r\nSoftware Foundation.  If the Program does not specify a version number of\r\nthis License, you may choose any version ever published by the Free Software\r\nFoundation.\r\n\r\n  10. If you wish to incorporate parts of the Program into other free\r\nprograms whose distribution conditions are different, write to the author\r\nto ask for permission.  For software which is copyrighted by the Free\r\nSoftware Foundation, write to the Free Software Foundation; we sometimes\r\nmake exceptions for this.  Our decision will be guided by the two goals\r\nof preserving the free status of all derivatives of our free software and\r\nof promoting the sharing and reuse of software generally.\r\n\r\n                            NO WARRANTY\r\n\r\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\r\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\r\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\r\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\r\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\r\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\r\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\r\nREPAIR OR CORRECTION.\r\n\r\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\r\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\r\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\r\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\r\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\r\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\r\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\r\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\r\nPOSSIBILITY OF SUCH DAMAGES.\r\n\r\n                     END OF TERMS AND CONDITIONS\r\n\r\n            How to Apply These Terms to Your New Programs\r\n\r\n  If you develop a new program, and you want it to be of the greatest\r\npossible use to the public, the best way to achieve this is to make it\r\nfree software which everyone can redistribute and change under these terms.\r\n\r\n  To do so, attach the following notices to the program.  It is safest\r\nto attach them to the start of each source file to most effectively\r\nconvey the exclusion of warranty; and each file should have at least\r\nthe \"copyright\" line and a pointer to where the full notice is found.\r\n\r\n    <one line to give the program's name and a brief idea of what it does.>\r\n    Copyright (C) <year>  <name of author>\r\n\r\n    This program is free software; you can redistribute it and/or modify\r\n    it under the terms of the GNU General Public License as published by\r\n    the Free Software Foundation; either version 2 of the License, or\r\n    (at your option) any later version.\r\n\r\n    This program is distributed in the hope that it will be useful,\r\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n    GNU General Public License for more details.\r\n\r\n    You should have received a copy of the GNU General Public License along\r\n    with this program; if not, write to the Free Software Foundation, Inc.,\r\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\r\n\r\nAlso add information on how to contact you by electronic and paper mail.\r\n\r\nIf the program is interactive, make it output a short notice like this\r\nwhen it starts in an interactive mode:\r\n\r\n    Gnomovision version 69, Copyright (C) year name of author\r\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\r\n    This is free software, and you are welcome to redistribute it\r\n    under certain conditions; type `show c' for details.\r\n\r\nThe hypothetical commands `show w' and `show c' should show the appropriate\r\nparts of the General Public License.  Of course, the commands you use may\r\nbe called something other than `show w' and `show c'; they could even be\r\nmouse-clicks or menu items--whatever suits your program.\r\n\r\nYou should also get your employer (if you work as a programmer) or your\r\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\r\nnecessary.  Here is a sample; alter the names:\r\n\r\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\r\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\r\n\r\n  <signature of Ty Coon>, 1 April 1989\r\n  Ty Coon, President of Vice\r\n\r\nThis General Public License does not permit incorporating your program into\r\nproprietary programs.  If your program is a subroutine library, you may\r\nconsider it more useful to permit linking proprietary applications with the\r\nlibrary.  If this is what you want to do, use the GNU Lesser General\r\nPublic License instead of this License.\r\n\r\n\r\nmbed TLS\r\n--------\r\n\r\nhttps://tls.mbed.org\r\n\r\nLicense: https://raw.githubusercontent.com/ARMmbed/mbedtls/master/LICENSE\r\n\r\n\r\nNewtonsoft.Json\r\n----------\r\n\r\nhttps://raw.githubusercontent.com/JamesNK/Newtonsoft.Json/master/LICENSE.md\r\n\r\nThe MIT License (MIT)\r\n\r\nCopyright (c) 2007 James Newton-King\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of\r\nthis software and associated documentation files (the \"Software\"), to deal in\r\nthe Software without restriction, including without limitation the rights to\r\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r\nthe Software, and to permit persons to whom the Software is furnished to do so,\r\nsubject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n\r\nZXing\r\n-----\r\n\r\nCopyright 2007 ZXing authors\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n   http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n\r\nlibsodium\r\n---------\r\n\r\nCopyright (c) 2013-2015\r\nFrank Denis <j at pureftpd dot org>\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted, provided that the above\r\ncopyright notice and this permission notice appear in all copies.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\r\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\r\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\r\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\r\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\r\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\r\nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\r\n"
  },
  {
    "path": "OPENSSL-GUIDE",
    "content": "OpenSSL library guide for VS2017\r\n\r\n# Read NOTES.WIN and NOTES.PERL\r\n\r\n# use Visual Studio native tools command prompt\r\n# use activeperl, install NASM assembler\r\nppm install dmake\r\n\r\n# Win32 x86\r\nset PATH=D:\\NASM-32;%PATH%\r\nperl 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\r\nnmake\r\nnmake test\r\n# to rebuild\r\nnmake distclean\r\n"
  },
  {
    "path": "README.md",
    "content": "<img src=\"shadowsocks-csharp/Resources/ssw128.png\" alt=\"[logo]\" width=\"48\"/> Shadowsocks for Windows\r\n=======================\r\n\r\n[![Build Status]][Appveyor]\r\n\r\n[中文说明]\r\n\r\n## Features\r\n\r\n1. System proxy configuration\r\n2. PAC mode and global mode\r\n3. [GeoSite] and user rules\r\n4. Supports HTTP proxy\r\n5. Supports server auto switching\r\n6. Supports UDP relay (see Usage)\r\n7. Supports plugins\r\n\r\n## Downloads\r\n\r\nDownload the latest release from [release page].\r\n\r\n## Requirements\r\n\r\n.NET Framework 4.8 or higher, Microsoft [Visual C++ 2015 Redistributable] (x86) .\r\n\r\n## Basics\r\n\r\n1. Find Shadowsocks icon in the notification tray\r\n2. You can add multiple servers in servers menu\r\n3. Select `Enable System Proxy` menu to enable system proxy. Please disable other\r\nproxy addons in your browser, or set them to use system proxy\r\n4. You can also configure your browser proxy manually if you don't want to enable\r\nsystem proxy. Set Socks5 or HTTP proxy to 127.0.0.1:1080. You can change this\r\nport in `Servers -> Edit Servers`\r\n\r\n## PAC\r\n\r\n- The PAC rules are generated from the geosite database in [v2fly/domain-list-community](https://github.com/v2fly/domain-list-community).\r\n- Generation modes: whitelist mode and blacklist mode.\r\n- Domain groups: `geositeDirectGroups` and `geositeProxiedGroups`.\r\n    - `geositeDirectGroups` is initialized with `cn` and `geolocation-!cn@cn`.\r\n    - `geositeProxiedGroups` is initialized with `geolocation-!cn`.\r\n- To switch between different modes, modify the `geositePreferDirect` property in `gui-config.json`\r\n    - When `geositePreferDirect` is false (default), PAC works in whitelist mode. Exception rules are generated from `geositeDirectGroups`. Unmatched domains goes through the proxy.\r\n    - 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.\r\n- Starting from 4.3.0.0, shadowsocks-windows defaults to whitelist mode with Chinese domains excluded from connecting via the proxy.\r\n- The new default values make sure that:\r\n    - When in whitelist mode, Chinese domains, including non-Chinese companies' Chinese CDNs, are connected to directly.\r\n    - 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.\r\n\r\n### User-defined rules\r\n\r\n- To define your own PAC rules, it's recommended to use the `user-rule.txt` file.\r\n- You can also modify `pac.txt` directly. But your modifications won't persist after updating geosite from the upstream.\r\n\r\nFor Windows10 Store and related applications, please execute the following command under Admin privilege:\r\n```\r\nnetsh winhttp import proxy source=ie\r\n```\r\n\r\n## Server Auto Switching\r\n\r\n1. Load balance: choosing server randomly\r\n2. High availability: choosing the best server (low latency and packet loss)\r\n3. Choose By Total Package Loss: ping and choose. Please also enable\r\n   `Availability Statistics` in the menu if you want to use this\r\n4. Write your own strategy by implement IStrategy interface and send us a pull request!\r\n\r\n## UDP\r\n\r\nFor UDP, you need to use SocksCap or ProxyCap to force programs you want\r\nto be proxied to tunnel over Shadowsocks\r\n\r\n## Multiple Instances\r\n\r\nIf you want to manage multiple servers using other tools like SwitchyOmega,\r\nyou can start multiple Shadowsocks instances. To avoid configuration conflicts,\r\ncopy Shadowsocks to a new directory and choose a different local port.\r\n\r\n## Plugins\r\n\r\nIf you would like to connect to server via a plugin, please set the plugin's\r\npath (relative or absolute) on Edit Servers form.\r\n_Note_: Forward Proxy will not be used while a plugin is enabled.\r\n\r\nDetails:\r\n[Working with non SIP003 standard Plugin].\r\n\r\n## Global hotkeys\r\n\r\nHotkeys could be registered automatically on startup.\r\nIf you are using multiple instances of Shadowsocks,\r\nyou must set different key combination for each instance.\r\n\r\n### How to input?\r\n\r\n1. Put focus in the corresponding textbox.\r\n2. Press the key combination that you want to use.\r\n3. Release all keys when you think it is ready.\r\n4. Your input appears in the textbox.\r\n\r\n### How to change?\r\n\r\n1. Put focus in the corresponding textbox.\r\n2. Press BackSpace key to clear content.\r\n3. Re-input new key combination.\r\n\r\n### How to deactivate?\r\n\r\n1. Clear content in the textbox that you want to deactivate,\r\nif you want to deactivate all, please clear all textboxes.\r\n2. Press OK button to confirm.\r\n\r\n### Meaning of label color\r\n\r\n- Green: This key combination is not occupied by other programs and register successfully.\r\n- Yellow: This key combination is occupied by other programs and you have to change to another one.\r\n- Transparent without color: The initial status.\r\n\r\n## Server Configuration\r\n\r\nPlease visit [Servers] for more information.\r\n\r\n## Experimental\r\n\r\n[Experimental Features]\r\n\r\n## Development\r\n\r\n1. Visual Studio 2019 & .NET Framework 4.8 SDK are required.\r\n2. It is recommended to share your idea on the Issue Board before you start to work,\r\nespecially for feature development.\r\n\r\n## License\r\n\r\n[GPLv3]\r\n\r\n## Open Source Components / Libraries\r\n\r\n```\r\nCaseless.Fody (MIT)              https://github.com/Fody/Caseless\r\nCostura.Fody (MIT)               https://github.com/Fody/Costura\r\nFody (MIT)                       https://github.com/Fody/Fody\r\nGlobalHotKey (GPLv3)             https://github.com/kirmir/GlobalHotKey\r\nMdXaml (MIT)                     https://github.com/whistyun/MdXaml\r\nNewtonsoft.Json (MIT)            https://www.newtonsoft.com/json\r\nReactiveUI.WPF (MIT)             https://github.com/reactiveui/ReactiveUI\r\nReactiveUI.Events.WPF (MIT)      https://github.com/reactiveui/ReactiveUI\r\nReactiveUI.Fody (MIT)            https://github.com/reactiveui/ReactiveUI\r\nReactiveUI.Validation (MIT)      https://github.com/reactiveui/ReactiveUI.Validation\r\nWPFLocalizationExtension (MS-PL) https://github.com/XAMLMarkupExtensions/WPFLocalizationExtension/\r\nZXing.Net (Apache 2.0)           https://github.com/micjahn/ZXing.Net\r\n\r\nlibsscrypto (GPLv2)    https://github.com/shadowsocks/libsscrypto\r\nPrivoxy (GPLv2)        https://www.privoxy.org\r\nSysproxy ()            https://github.com/Noisyfox/sysproxy\r\n```\r\n\r\n\r\n\r\n[Appveyor]:     https://ci.appveyor.com/project/celeron533/shadowsocks-windows\r\n[Build Status]: https://ci.appveyor.com/api/projects/status/tfw57q6eecippsl5/branch/master?svg=true\r\n[release page]: https://github.com/shadowsocks/shadowsocks-csharp/releases\r\n[GeoSite]:      https://github.com/v2fly/domain-list-community\r\n[Servers]:      https://github.com/shadowsocks/shadowsocks/wiki/Ports-and-Clients#linux--server-side\r\n[中文说明]:     https://github.com/shadowsocks/shadowsocks-windows/wiki/Shadowsocks-Windows-%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E\r\n[Visual C++ 2015 Redistributable]:     https://www.microsoft.com/en-us/download/details.aspx?id=53840\r\n[GPLv3]:        https://github.com/shadowsocks/shadowsocks-windows/blob/master/LICENSE.txt\r\n[Working with non SIP003 standard Plugin]: https://github.com/shadowsocks/shadowsocks-windows/wiki/Working-with-non-SIP003-standard-Plugin\r\n[Experimental Features]: https://github.com/shadowsocks/shadowsocks-windows/wiki/Experimental"
  },
  {
    "path": "appveyor.yml",
    "content": "\r\n# Notes:\r\n#   - Minimal appveyor.yml file is an empty file. All sections are optional.\r\n#   - Indent each level of configuration with 2 spaces. Do not use tabs!\r\n#   - All section names are case-sensitive.\r\n#   - Section names should be unique on each level.\r\n\r\n#---------------------------------#\r\n#      general configuration      #\r\n#---------------------------------#\r\n\r\n# version format\r\n# Build version format is taken from UI if it is not set\r\nversion: 4.4.1.{build}\r\n\r\n# # branches to build\r\n# branches:\r\n#   # whitelist\r\n#   only:\r\n#     - master\r\n#     - production\r\n\r\n#   # blacklist\r\n#   except:\r\n#     - gh-pages\r\n\r\n\r\n#---------------------------------#\r\n#    environment configuration    #\r\n#---------------------------------#\r\n\r\n# Build worker image (VM template)\r\nimage: Visual Studio 2019\r\n\r\n# scripts that are called at very beginning, before repo cloning\r\n# init:\r\n#   - git config --global core.autocrlf false\r\n\r\n\r\n# set clone depth\r\nclone_depth: 5                      # clone entire repository history if not defined\r\n\r\n\r\n# environment variables\r\nenvironment:\r\n  # my_var1: value1\r\n  # # this is how to set encrypted variable. Go to \"Settings\" -> \"Encrypt YAML\" page in account menu to encrypt data.\r\n  # my_secure_var1:\r\n  #   secure: FW3tJ3fMncxvs58/ifSP7w==\r\n  matrix:\r\n    - platform: x86\r\n      configuration: Debug\r\n    - platform: x86\r\n      configuration: Release\r\n\r\n# this is how to allow failing jobs in the matrix\r\nmatrix:\r\n  fast_finish: false     # set this flag to immediately finish build once one of the jobs fails.\r\n\r\n# build cache to preserve files/folders between builds\r\ncache:\r\n  - packages -> **\\packages.config  # preserve \"packages\" directory in the root of build folder but will reset it if packages.config is modified\r\n  # - '%LocalAppData%\\NuGet\\Cache'    # NuGet < v3\r\n  - '%LocalAppData%\\NuGet\\v3-cache' # NuGet v3\r\n\r\n\r\n# Automatically register private account and/or project AppVeyor NuGet feeds.\r\n# nuget:\r\n  # account_feed: true\r\n  # project_feed: true\r\n  # disable_publish_on_pr: true     # disable publishing of .nupkg artifacts to account/project feeds for pull request builds\r\n  # publish_wap_octopus: true       # disable publishing of Octopus Deploy .nupkg artifacts to account/project feeds\r\n\r\n#---------------------------------#\r\n#       build configuration       #\r\n#---------------------------------#\r\n\r\n# Build settings, not to be confused with \"before_build\" and \"after_build\".\r\n# \"project\" is relative to the original build directory and not influenced by directory changes in \"before_build\".\r\nbuild:\r\n  # parallel: true                  # enable MSBuild parallel builds\r\n  # publish_nuget: true             # package projects with .nuspec files and push to artifacts\r\n  # publish_nuget_symbols: true     # generate and publish NuGet symbol packages\r\n  # include_nuget_references: true  # add -IncludeReferencedProjects option while packaging NuGet artifacts\r\n\r\n  # MSBuild verbosity level\r\n  verbosity: normal  # quiet|minimal|normal|detailed\r\n\r\n\r\n# scripts to run before build\r\nbefore_build:\r\n  - cmd: nuget restore\r\n\r\n# to run your custom scripts instead of automatic MSBuild\r\n# build_script:\r\n\r\n# scripts to run after build (working directory and environment changes are persisted from the previous steps)\r\nafter_build:\r\n- ps: |+\r\n    function CalculateHash($file)\r\n    {\r\n        $newLine = \"`r`n\"\r\n        $text = (Split-Path $file -Leaf) + $newLine\r\n        $text += 'MD5' + $newLine\r\n        $text += (Get-FileHash $file -Algorithm MD5).Hash + $newLine\r\n        $text += 'SHA-1' + $newLine\r\n        $text += (Get-FileHash $file -Algorithm SHA1).Hash + $newLine\r\n        $text += 'SHA-256' + $newLine\r\n        $text += (Get-FileHash $file -Algorithm SHA256).Hash + $newLine\r\n        $text += 'SHA-512' + $newLine\r\n        $text += (Get-FileHash $file -Algorithm SHA512).Hash\r\n        return $text\r\n    }\r\n\r\n    $WorkingFolder = \"$env:APPVEYOR_BUILD_FOLDER\\shadowsocks-csharp\\bin\\$env:PLATFORM\\$env:CONFIGURATION\"\r\n    $ReleaseFile = \"$WorkingFolder\\Shadowsocks.exe\"\r\n    $ReleaseHashFile = \"$ReleaseFile.hash\"\r\n    $ReleaseLocalizationFiles = \"$WorkingFolder\\*\\\"\r\n    $ZipFile = \"$WorkingFolder\\Shadowsocks-$env:APPVEYOR_BUILD_VERSION.zip\"\r\n    $ZipHashFile = \"$ZipFile.hash\"\r\n\r\n    CalculateHash -file \"$ReleaseFile\" | Out-File -FilePath \"$ReleaseHashFile\"\r\n    7z a \"$ZipFile\" \"$ReleaseFile\" \"$ReleaseHashFile\" \"$ReleaseLocalizationFiles\"\r\n    Push-AppveyorArtifact \"$ZipFile\"\r\n\r\n    # Calculate packed zip Hash\r\n    CalculateHash -file \"$ZipFile\" | Out-File -FilePath \"$ZipHashFile\"\r\n    Push-AppveyorArtifact \"$ZipHashFile\"\r\n\r\n\r\n# scripts to run *after* solution is built and *before* automatic packaging occurs (web apps, NuGet packages, Azure Cloud Services)\r\n# before_package:\r\n\r\n# to disable automatic builds\r\n#build: off\r\n\r\n\r\n#---------------------------------#\r\n#     deployment configuration    #\r\n#---------------------------------#\r\n\r\n# providers: Local, FTP, WebDeploy, AzureCS, AzureBlob, S3, NuGet, Environment\r\n# provider names are case-sensitive!\r\n# deploy:\r\n\r\n# # scripts to run before deployment\r\n# before_deploy:\r\n\r\n# # scripts to run after deployment\r\n# after_deploy:\r\n\r\n# # to run your custom scripts instead of provider deployments\r\n# deploy_script:\r\n\r\n# # to disable deployment\r\n#deploy: off"
  },
  {
    "path": "appveyor.yml.obsolete",
    "content": "# Created by wongsyrone\n\nversion: 1.0.{build}\nimage: Visual Studio 2017\nenvironment:\n  matrix:\n    - platform: x86\n      configuration: Debug\n    - platform: x86\n      configuration: Release\nmatrix:\n  fast_finish: false\nnuget:\n  project_feed: true\nbefore_build:\n- cmd: nuget restore\nbuild:\n  parallel: true\n  verbosity: normal\nartifacts:\n- path: shadowsocks-csharp\\bin\\x86\\Release\\Shadowsocks.exe\n  name: Shadowsocks-release.exe\n- path: shadowsocks-csharp\\bin\\x86\\Debug\\Shadowsocks.exe\n  name: Shadowsocks-debug.exe\n"
  },
  {
    "path": "appveyor.yml.sample",
    "content": "\r\n# Notes:\r\n#   - Minimal appveyor.yml file is an empty file. All sections are optional.\r\n#   - Indent each level of configuration with 2 spaces. Do not use tabs!\r\n#   - All section names are case-sensitive.\r\n#   - Section names should be unique on each level.\r\n\r\n#---------------------------------#\r\n#      general configuration      #\r\n#---------------------------------#\r\n\r\n# version format\r\nversion: 1.0.{build}\r\n\r\n# you can use {branch} name in version format too\r\n# version: 1.0.{build}-{branch}\r\n\r\n# branches to build\r\nbranches:\r\n  # whitelist\r\n  only:\r\n    - master\r\n    - production\r\n\r\n  # blacklist\r\n  except:\r\n    - gh-pages\r\n\r\n# Do not build on tags (GitHub and BitBucket)\r\nskip_tags: true\r\n\r\n# Start builds on tags only (GitHub and BitBucket)\r\nskip_non_tags: true\r\n\r\n# Skipping commits with particular message or from specific user\r\nskip_commits:\r\n  message: /Created.*\\.(png|jpg|jpeg|bmp|gif)/      # Regex for matching commit message\r\n  author: John                                      # Commit author's username, name, email or regexp maching one of these.\r\n\r\n# Including commits with particular message or from specific user\r\nonly_commits:\r\n  message: /build/                # Start a new build if message contains 'build'\r\n  author: jack@company.com        # Start a new build for commit of user with email jack@company.com\r\n\r\n# Skipping commits affecting specific files (GitHub only). More details here: /docs/appveyor-yml\r\n#skip_commits:\r\n#  files:\r\n#    - docs/*\r\n#    - '**/*.html'\r\n\r\n# Including commits affecting specific files (GitHub only). More details here: /docs/appveyor-yml\r\n#only_commits:\r\n#  files:\r\n#    - Project-A/\r\n#    - Project-B/\r\n\r\n# Do not build feature branch with open Pull Requests\r\nskip_branch_with_pr: true\r\n\r\n# Maximum number of concurrent jobs for the project\r\nmax_jobs: 1\r\n\r\n#---------------------------------#\r\n#    environment configuration    #\r\n#---------------------------------#\r\n\r\n# Build worker image (VM template)\r\nimage: Visual Studio 2015\r\n\r\n# scripts that are called at very beginning, before repo cloning\r\ninit:\r\n  - git config --global core.autocrlf input\r\n\r\n# clone directory\r\nclone_folder: c:\\projects\\myproject\r\n\r\n# fetch repository as zip archive\r\nshallow_clone: true                 # default is \"false\"\r\n\r\n# set clone depth\r\nclone_depth: 5                      # clone entire repository history if not defined\r\n\r\n# setting up etc\\hosts file\r\nhosts:\r\n  queue-server: 127.0.0.1\r\n  db.server.com: 127.0.0.2\r\n\r\n# environment variables\r\nenvironment:\r\n  my_var1: value1\r\n  my_var2: value2\r\n  # this is how to set encrypted variable. Go to \"Settings\" -> \"Encrypt YAML\" page in account menu to encrypt data.\r\n  my_secure_var1:\r\n    secure: FW3tJ3fMncxvs58/ifSP7w==\r\n\r\n# environment:\r\n#  global:\r\n#    connection_string: server=12;password=13;\r\n#    service_url: https://127.0.0.1:8090\r\n#\r\n#  matrix:\r\n#  - db: mysql\r\n#    provider: mysql\r\n#\r\n#  - db: mssql\r\n#    provider: mssql\r\n#    password:\r\n#      secure: $#(JFDA)jQ@#$\r\n\r\n# this is how to allow failing jobs in the matrix\r\nmatrix:\r\n  fast_finish: true     # set this flag to immediately finish build once one of the jobs fails.\r\n  allow_failures:\r\n    - platform: x86\r\n      configuration: Debug\r\n    - platform: x64\r\n      configuration: Release\r\n\r\n# exclude configuration from the matrix. Works similarly to 'allow_failures' but build not even being started for excluded combination.\r\n  exclude:\r\n    - platform: x86\r\n      configuration: Debug\r\n\r\n# build cache to preserve files/folders between builds\r\ncache:\r\n  - packages -> **\\packages.config  # preserve \"packages\" directory in the root of build folder but will reset it if packages.config is modified\r\n  - projectA\\libs\r\n  - node_modules                    # local npm modules\r\n  - '%LocalAppData%\\NuGet\\Cache'    # NuGet < v3\r\n  - '%LocalAppData%\\NuGet\\v3-cache' # NuGet v3\r\n\r\n# enable service required for build/tests\r\nservices:\r\n  - mssql2014           # start SQL Server 2014 Express\r\n  - mssql2014rs         # start SQL Server 2014 Express and Reporting Services\r\n  - mssql2012sp1        # start SQL Server 2012 SP1 Express\r\n  - mssql2012sp1rs      # start SQL Server 2012 SP1 Express and Reporting Services\r\n  - mssql2008r2sp2      # start SQL Server 2008 R2 SP2 Express\r\n  - mssql2008r2sp2rs    # start SQL Server 2008 R2 SP2 Express and Reporting Services\r\n  - mysql               # start MySQL 5.6 service\r\n  - postgresql          # start PostgreSQL 9.5 service\r\n  - iis                 # start IIS\r\n  - msmq                # start Queuing services\r\n  - mongodb             # start MongoDB\r\n\r\n# scripts that run after cloning repository\r\ninstall:\r\n  # by default, all script lines are interpreted as batch\r\n  - echo This is batch\r\n  # to run script as a PowerShell command prepend it with ps:\r\n  - ps: Write-Host 'This is PowerShell'\r\n  # batch commands start from cmd:\r\n  - cmd: echo This is batch again\r\n  - cmd: set MY_VAR=12345\r\n\r\n# enable patching of AssemblyInfo.* files\r\nassembly_info:\r\n  patch: true\r\n  file: AssemblyInfo.*\r\n  assembly_version: \"2.2.{build}\"\r\n  assembly_file_version: \"{version}\"\r\n  assembly_informational_version: \"{version}\"\r\n\r\n\r\n# Automatically register private account and/or project AppVeyor NuGet feeds.\r\nnuget:\r\n  account_feed: true\r\n  project_feed: true\r\n  disable_publish_on_pr: true     # disable publishing of .nupkg artifacts to account/project feeds for pull request builds\r\n  publish_wap_octopus: true       # disable publishing of Octopus Deploy .nupkg artifacts to account/project feeds\r\n\r\n#---------------------------------#\r\n#       build configuration       #\r\n#---------------------------------#\r\n\r\n# build platform, i.e. x86, x64, Any CPU. This setting is optional.\r\nplatform: Any CPU\r\n\r\n# to add several platforms to build matrix:\r\n#platform:\r\n#  - x86\r\n#  - Any CPU\r\n\r\n# build Configuration, i.e. Debug, Release, etc.\r\nconfiguration: Release\r\n\r\n# to add several configurations to build matrix:\r\n#configuration:\r\n#  - Debug\r\n#  - Release\r\n\r\n# Build settings, not to be confused with \"before_build\" and \"after_build\".\r\n# \"project\" is relative to the original build directory and not influenced by directory changes in \"before_build\".\r\nbuild:\r\n  parallel: true                  # enable MSBuild parallel builds\r\n  project: MyTestAzureCS.sln      # path to Visual Studio solution or project\r\n  publish_wap: true               # package Web Application Projects (WAP) for Web Deploy\r\n  publish_wap_xcopy: true         # package Web Application Projects (WAP) for XCopy deployment\r\n  publish_wap_beanstalk: true     # Package Web Applications for AWS Elastic Beanstalk deployment\r\n  publish_wap_octopus: true       # Package Web Applications for Octopus deployment\r\n  publish_azure_webjob: true      # Package Azure WebJobs for Zip Push deployment\r\n  publish_azure: true             # package Azure Cloud Service projects and push to artifacts\r\n  publish_aspnet_core: true       # Package ASP.NET Core projects\r\n  publish_core_console: true      # Package .NET Core console projects\r\n  publish_nuget: true             # package projects with .nuspec files and push to artifacts\r\n  publish_nuget_symbols: true     # generate and publish NuGet symbol packages\r\n  include_nuget_references: true  # add -IncludeReferencedProjects option while packaging NuGet artifacts\r\n\r\n  # MSBuild verbosity level\r\n  verbosity: quiet|minimal|normal|detailed\r\n\r\n\r\n# scripts to run before build\r\nbefore_build:\r\n\r\n# to run your custom scripts instead of automatic MSBuild\r\nbuild_script:\r\n\r\n# scripts to run after build (working directory and environment changes are persisted from the previous steps)\r\nafter_build:\r\n\r\n# scripts to run *after* solution is built and *before* automatic packaging occurs (web apps, NuGet packages, Azure Cloud Services)\r\nbefore_package:\r\n\r\n# to disable automatic builds\r\n#build: off\r\n\r\n#---------------------------------#\r\n#       tests configuration       #\r\n#---------------------------------#\r\n\r\n# to run tests against only selected assemblies and/or categories\r\ntest:\r\n  assemblies:\r\n    only:\r\n      - asm1.dll\r\n      - asm2.dll\r\n\r\n  categories:\r\n    only:\r\n      - UI\r\n      - E2E\r\n\r\n# to run tests against all except selected assemblies and/or categories\r\n#test:\r\n#  assemblies:\r\n#    except:\r\n#      - asm1.dll\r\n#      - asm2.dll\r\n#\r\n#  categories:\r\n#    except:\r\n#      - UI\r\n#      - E2E\r\n\r\n# to run tests from different categories as separate jobs in parallel\r\n#test:\r\n#  categories:\r\n#    - A            # A category common for all jobs\r\n#    - [UI]         # 1st job\r\n#    - [DAL, BL]    # 2nd job\r\n\r\n# scripts to run before tests (working directory and environment changes are persisted from the previous steps such as \"before_build\")\r\nbefore_test:\r\n  - echo script1\r\n  - ps: Write-Host \"script1\"\r\n\r\n# to run your custom scripts instead of automatic tests\r\ntest_script:\r\n  - echo This is my custom test script\r\n\r\n# scripts to run after tests\r\nafter_test:\r\n\r\n# to disable automatic tests\r\n#test: off\r\n\r\n\r\n#---------------------------------#\r\n#      artifacts configuration    #\r\n#---------------------------------#\r\n\r\nartifacts:\r\n\r\n  # pushing a single file\r\n  - path: test.zip\r\n\r\n  # pushing a single file with environment variable in path and \"Deployment name\" specified\r\n  - path: MyProject\\bin\\$(configuration)\r\n    name: myapp\r\n\r\n  # pushing entire folder as a zip archive\r\n  - path: logs\r\n\r\n  # pushing all *.nupkg files in build directory recursively\r\n  - path: '**\\*.nupkg'\r\n\r\n\r\n#---------------------------------#\r\n#     deployment configuration    #\r\n#---------------------------------#\r\n\r\n# providers: Local, FTP, WebDeploy, AzureCS, AzureBlob, S3, NuGet, Environment\r\n# provider names are case-sensitive!\r\ndeploy:\r\n\r\n    # FTP deployment provider settings\r\n  - provider: FTP\r\n    protocol: ftp|ftps|sftp\r\n    host: ftp.myserver.com\r\n    username: admin\r\n    password:\r\n      secure: eYKZKFkkEvFYWX6NfjZIVw==\r\n    folder:\r\n    application:\r\n    active_mode: false\r\n    beta: true      # enable alternative FTP library for 'ftp' and 'ftps' modes\r\n    debug: true     # show complete FTP log\r\n\r\n    # Amazon S3 deployment provider settings\r\n  - provider: S3\r\n    access_key_id:\r\n      secure: ABcd==\r\n    secret_access_key:\r\n      secure: ABcd==\r\n    bucket: my_bucket\r\n    folder:\r\n    artifact:\r\n    set_public: false\r\n\r\n    # Azure Blob storage deployment provider settings\r\n  - provider: AzureBlob\r\n    storage_account_name:\r\n      secure: ABcd==\r\n    storage_access_key:\r\n      secure: ABcd==\r\n    container: my_container\r\n    folder:\r\n    artifact:\r\n\r\n    # Web Deploy deployment provider settings\r\n  - provider: WebDeploy\r\n    server: http://www.deploy.com/myendpoint\r\n    website: mywebsite\r\n    username: user\r\n    password:\r\n      secure: eYKZKFkkEvFYWX6NfjZIVw==\r\n    ntlm: false\r\n    remove_files: false\r\n    app_offline: false\r\n    do_not_use_checksum: true           # do not use check sum for comparing source and destination files. By default checksums are used.\r\n    sync_retry_attempts: 2              # sync attempts, max\r\n    sync_retry_interval: 2000           # timeout between sync attempts, milliseconds\r\n    aspnet_core: true                   # artifact zip contains ASP.NET Core application\r\n    aspnet_core_force_restart: true     # poke app's web.config before deploy to force application restart\r\n    skip_dirs: \\\\App_Data\r\n    skip_files: web.config\r\n    on:\r\n      branch: release\r\n      platform: x86\r\n      configuration: debug\r\n\r\n    # Deploying to Azure Cloud Service\r\n  - provider: AzureCS\r\n    subscription_id:\r\n      secure: fjZIVw==\r\n    subscription_certificate:\r\n      secure: eYKZKFkkEv...FYWX6NfjZIVw==\r\n    storage_account_name: my_storage\r\n    storage_access_key:\r\n      secure: ABcd==\r\n    service: my_service\r\n    slot: Production\r\n    target_profile: Cloud\r\n    artifact: MyPackage.cspkg\r\n\r\n    # Deploying to NuGet feed\r\n  - provider: NuGet\r\n    server: https://my.nuget.server/feed\r\n    api_key:\r\n      secure: FYWX6NfjZIVw==\r\n    skip_symbols: false\r\n    symbol_server: https://your.symbol.server/feed\r\n    artifact: MyPackage.nupkg\r\n\r\n    # Deploy to GitHub Releases\r\n  - provider: GitHub\r\n    artifact: /.*\\.nupkg/           # upload all NuGet packages to release assets\r\n    draft: false\r\n    prerelease: false\r\n    on:\r\n      branch: master                # release from master branch only\r\n      APPVEYOR_REPO_TAG: true       # deploy on tag push only\r\n\r\n    # Deploying to a named environment\r\n  - provider: Environment\r\n    name: staging\r\n    on:\r\n      branch: staging\r\n      env_var1: value1\r\n      env_var2: value2\r\n\r\n# scripts to run before deployment\r\nbefore_deploy:\r\n\r\n# scripts to run after deployment\r\nafter_deploy:\r\n\r\n# to run your custom scripts instead of provider deployments\r\ndeploy_script:\r\n\r\n# to disable deployment\r\n#deploy: off\r\n\r\n#---------------------------------#\r\n#        global handlers          #\r\n#---------------------------------#\r\n\r\n# on successful build\r\non_success:\r\n  - do something\r\n\r\n# on build failure\r\non_failure:\r\n  - do something\r\n\r\n# after build failure or success\r\non_finish:\r\n  - do something\r\n\r\n\r\n#---------------------------------#\r\n#         notifications           #\r\n#---------------------------------#\r\n\r\nnotifications:\r\n\r\n  # Email\r\n  - provider: Email\r\n    to:\r\n      - user1@email.com\r\n      - user2@email.com\r\n    subject: 'Build {{status}}'                  # optional\r\n    message: \"{{message}}, {{commitId}}, ...\"    # optional\r\n    on_build_status_changed: true\r\n\r\n  # HipChat\r\n  - provider: HipChat\r\n    auth_token:\r\n      secure: RbOnSMSFKYzxzFRrxM1+XA==\r\n    room: ProjectA\r\n    template: \"{message}, {commitId}, ...\"\r\n\r\n  # Slack\r\n  - provider: Slack\r\n    incoming_webhook: http://incoming-webhook-url\r\n\r\n  # ...or using auth token\r\n\r\n  - provider: Slack\r\n    auth_token:\r\n      secure: kBl9BlxvRMr9liHmnBs14A==\r\n    channel: development\r\n    template: \"{message}, {commitId}, ...\"\r\n\r\n  # Campfire\r\n  - provider: Campfire\r\n    account: appveyor\r\n    auth_token:\r\n      secure: RifLRG8Vfyol+sNhj9u2JA==\r\n    room: ProjectA\r\n    template: \"{message}, {commitId}, ...\"\r\n\r\n  # Webhook\r\n  - provider: Webhook\r\n    url: http://www.myhook2.com\r\n    headers:\r\n      User-Agent: myapp 1.0\r\n      Authorization:\r\n        secure: GhD+5xhLz/tkYY6AO3fcfQ==\r\n    on_build_success: false\r\n    on_build_failure: true\r\n    on_build_status_changed: true\r\n"
  },
  {
    "path": "packaging/upload.sh",
    "content": "#!/bin/bash\n\nversion=$1\n\nrsync --progress -e ssh shadowsocks-csharp/bin/x86/Release/Shadowsocks-win-dotnet4.0-$1.zip frs.sourceforge.net:/home/frs/project/shadowsocksgui/dist/\nrsync --progress -e ssh shadowsocks-csharp/bin/x86/Release/Shadowsocks-win-$1.zip frs.sourceforge.net:/home/frs/project/shadowsocksgui/dist/\n"
  },
  {
    "path": "shadowsocks-csharp/CommandLineOption.cs",
    "content": "﻿using CommandLine;\n\nnamespace Shadowsocks\n{\n    public class CommandLineOption\n    {\n        [Option(\"open-url\",Required = false,HelpText = \"Add an ss:// URL\")]\n        public string OpenUrl { get; set; }\n    }\n}"
  },
  {
    "path": "shadowsocks-csharp/Controller/FileManager.cs",
    "content": "﻿using NLog;\r\nusing System;\r\nusing System.IO;\r\nusing System.IO.Compression;\r\nusing System.Text;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    public static class FileManager\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        public static bool ByteArrayToFile(string fileName, byte[] content)\r\n        {\r\n            try\r\n            {\r\n                using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))\r\n                    fs.Write(content, 0, content.Length);\r\n                return true;\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                logger.Error(ex);\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public static void UncompressFile(string fileName, byte[] content)\r\n        {\r\n            // Because the uncompressed size of the file is unknown,\r\n            // we are using an arbitrary buffer size.\r\n            byte[] buffer = new byte[4096];\r\n            int n;\r\n\r\n            using(var fs = File.Create(fileName))\r\n            using (var input = new GZipStream(new MemoryStream(content),\r\n                    CompressionMode.Decompress, false))\r\n            {\r\n                while ((n = input.Read(buffer, 0, buffer.Length)) > 0)\r\n                {\r\n                    fs.Write(buffer, 0, n);\r\n                }\r\n            }\r\n        }\r\n\r\n        public static string NonExclusiveReadAllText(string path)\r\n        {\r\n            return NonExclusiveReadAllText(path, Encoding.Default);\r\n        }\r\n\r\n        public static string NonExclusiveReadAllText(string path, Encoding encoding)\r\n        {\r\n            try\r\n            {\r\n                using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\r\n                using (var sr = new StreamReader(fs, encoding))\r\n                {\r\n                    return sr.ReadToEnd();\r\n                }\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                logger.Error(ex);\r\n                throw ex;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/HotkeyReg.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Windows.Forms;\nusing NLog;\nusing Shadowsocks.Controller.Hotkeys;\nusing Shadowsocks.Model;\n\nnamespace Shadowsocks.Controller\n{\n    static class HotkeyReg\n    {\n        private static Logger logger = LogManager.GetCurrentClassLogger();\n        public static void RegAllHotkeys()\n        {\n            var hotkeyConfig = Program.MainController.GetCurrentConfiguration().hotkey;\n\n            if (hotkeyConfig == null || !hotkeyConfig.RegHotkeysAtStartup)\n                return;\n\n            // if any of the hotkey reg fail, undo everything\n            if (RegHotkeyFromString(hotkeyConfig.SwitchSystemProxy, \"SwitchSystemProxyCallback\")\n                && RegHotkeyFromString(hotkeyConfig.SwitchSystemProxyMode, \"SwitchSystemProxyModeCallback\")\n                && RegHotkeyFromString(hotkeyConfig.SwitchAllowLan, \"SwitchAllowLanCallback\")\n                && RegHotkeyFromString(hotkeyConfig.ShowLogs, \"ShowLogsCallback\")\n                && RegHotkeyFromString(hotkeyConfig.ServerMoveUp, \"ServerMoveUpCallback\")\n                && RegHotkeyFromString(hotkeyConfig.ServerMoveDown, \"ServerMoveDownCallback\")\n            )\n            {\n                // success\n            }\n            else\n            {\n                RegHotkeyFromString(\"\", \"SwitchSystemProxyCallback\");\n                RegHotkeyFromString(\"\", \"SwitchSystemProxyModeCallback\");\n                RegHotkeyFromString(\"\", \"SwitchAllowLanCallback\");\n                RegHotkeyFromString(\"\", \"ShowLogsCallback\");\n                RegHotkeyFromString(\"\", \"ServerMoveUpCallback\");\n                RegHotkeyFromString(\"\", \"ServerMoveDownCallback\");\n                MessageBox.Show(I18N.GetString(\"Register hotkey failed\"), I18N.GetString(\"Shadowsocks\"));\n            }\n        }\n\n        public static bool RegHotkeyFromString(string hotkeyStr, string callbackName, Action<RegResult> onComplete = null)\n        {\n            var _callback = HotkeyCallbacks.GetCallback(callbackName);\n            if (_callback == null)\n            {\n                throw new Exception($\"{callbackName} not found\");\n            }\n\n            var callback = _callback as HotKeys.HotKeyCallBackHandler;\n\n            if (string.IsNullOrEmpty(hotkeyStr))\n            {\n                HotKeys.UnregExistingHotkey(callback);\n                onComplete?.Invoke(RegResult.UnregSuccess);\n                return true;\n            }\n            else\n            {\n                var hotkey = HotKeys.Str2HotKey(hotkeyStr);\n                if (hotkey == null)\n                {\n                    logger.Error($\"Cannot parse hotkey: {hotkeyStr}\");\n                    onComplete?.Invoke(RegResult.ParseError);\n                    return false;\n                }\n                else\n                {\n                    bool regResult = (HotKeys.RegHotkey(hotkey, callback));\n                    if (regResult)\n                    {\n                        onComplete?.Invoke(RegResult.RegSuccess);\n                    }\n                    else\n                    {\n                        onComplete?.Invoke(RegResult.RegFailure);\n                    }\n                    return regResult;\n                }\n            }\n        }\n\n        public enum RegResult\n        {\n            RegSuccess,\n            RegFailure,\n            ParseError,\n            UnregSuccess,\n            //UnregFailure\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/I18N.cs",
    "content": "﻿using Microsoft.VisualBasic.FileIO;\r\nusing NLog;\r\nusing Shadowsocks.Properties;\r\nusing Shadowsocks.Util;\r\nusing System.Collections.Generic;\r\nusing System.Globalization;\r\nusing System.IO;\r\nusing System.Text;\r\nusing System.Windows.Forms;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    public static class I18N\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        public const string I18N_FILE = \"i18n.csv\";\r\n\r\n        private static Dictionary<string, string> _strings = new Dictionary<string, string>();\r\n\r\n        private static void Init(string res, string locale)\r\n        {\r\n            using (TextFieldParser csvParser = new TextFieldParser(new StringReader(res)))\r\n            {\r\n                csvParser.SetDelimiters(\",\");\r\n\r\n                // search language index\r\n                string[] localeNames = csvParser.ReadFields();\r\n\r\n                int enIndex = 0;\r\n                int targetIndex = -1;\r\n\r\n                for (int i = 0; i < localeNames.Length; i++)\r\n                {\r\n                    if (localeNames[i] == \"en\")\r\n                        enIndex = i;\r\n                    if (localeNames[i] == locale)\r\n                        targetIndex = i;\r\n                }\r\n\r\n                // Fallback to same language with different region\r\n                if (targetIndex == -1)\r\n                {\r\n                    string localeNoRegion = locale.Split('-')[0];\r\n                    for (int i = 0; i < localeNames.Length; i++)\r\n                    {\r\n                        if (localeNames[i].Split('-')[0] == localeNoRegion)\r\n                            targetIndex = i;\r\n                    }\r\n                    if (targetIndex != -1 && enIndex != targetIndex)\r\n                    {\r\n                        logger.Info($\"Using {localeNames[targetIndex]} translation for {locale}\");\r\n                    }\r\n                    else\r\n                    {\r\n                        // Still not found, exit\r\n                        logger.Info($\"Translation for {locale} not found\");\r\n                        return;\r\n                    }\r\n                }\r\n\r\n                // read translation lines\r\n                while (!csvParser.EndOfData)\r\n                {\r\n                    string[] translations = csvParser.ReadFields();\r\n                    string source = translations[enIndex];\r\n                    string translation = translations[targetIndex];\r\n\r\n                    // source string or translation empty\r\n                    if (string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(translation)) continue;\r\n                    // line start with comment\r\n                    if (translations[0].TrimStart(' ')[0] == '#') continue;\r\n\r\n                    _strings[source] = translation;\r\n                }\r\n            }\r\n        }\r\n\r\n        static I18N()\r\n        {\r\n            string i18n;\r\n            string locale = CultureInfo.CurrentCulture.Name;\r\n            if (!File.Exists(I18N_FILE))\r\n            {\r\n                i18n = Resources.i18n_csv;\r\n                //File.WriteAllText(I18N_FILE, i18n, Encoding.UTF8);\r\n            }\r\n            else\r\n            {\r\n                logger.Info(\"Using external translation\");\r\n                i18n = File.ReadAllText(I18N_FILE, Encoding.UTF8);\r\n            }\r\n            logger.Info(\"Current language is: \" + locale);\r\n            Init(i18n, locale);\r\n        }\r\n\r\n        public static string GetString(string key, params object[] args)\r\n        {\r\n            return string.Format(_strings.TryGetValue(key.Trim(), out var value) ? value : key, args);\r\n        }\r\n\r\n        public static void TranslateForm(Form c)\r\n        {\r\n            if (c == null) return;\r\n            c.Text = GetString(c.Text);\r\n            foreach (var item in ViewUtils.GetChildControls<Control>(c))\r\n            {\r\n                if (item == null) continue;\r\n                item.Text = GetString(item.Text);\r\n            }\r\n            TranslateMenu(c.Menu);\r\n        }\r\n        public static void TranslateMenu(Menu m)\r\n        {\r\n            if (m == null) return;\r\n            foreach (var item in ViewUtils.GetMenuItems(m))\r\n            {\r\n                if (item == null) continue;\r\n                item.Text = GetString(item.Text);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/LoggerExtension.cs",
    "content": "﻿using System;\r\nusing System.ComponentModel;\r\nusing System.IO;\r\nusing System.Net.Sockets;\r\nusing System.Net;\r\nusing System.Diagnostics;\r\nusing System.Text;\r\nusing Shadowsocks.Util.SystemProxy;\r\n\r\nnamespace NLog\r\n{\r\n    public static class LoggerExtension\r\n    {\r\n        public static void Dump(this Logger logger, string tag, byte[] arr, int length)\r\n        {\r\n            if (logger.IsTraceEnabled)\r\n            {\r\n                var sb = new StringBuilder($\"{Environment.NewLine}{tag}: \");\r\n                for (int i = 0; i < length - 1; i++)\r\n                {\r\n                    sb.Append($\"0x{arr[i]:X2}, \");\r\n                }\r\n                sb.Append($\"0x{arr[length - 1]:X2}\");\r\n                sb.Append(Environment.NewLine);\r\n                logger.Trace(sb.ToString());\r\n            }\r\n        }\r\n\r\n        public static void Debug(this Logger logger, EndPoint local, EndPoint remote, int len, string header = null, string tailer = null)\r\n        {\r\n            if (logger.IsDebugEnabled)\r\n            {\r\n                if (header == null && tailer == null)\r\n                    logger.Debug($\"{local} => {remote} (size={len})\");\r\n                else if (header == null && tailer != null)\r\n                    logger.Debug($\"{local} => {remote} (size={len}), {tailer}\");\r\n                else if (header != null && tailer == null)\r\n                    logger.Debug($\"{header}: {local} => {remote} (size={len})\");\r\n                else\r\n                    logger.Debug($\"{header}: {local} => {remote} (size={len}), {tailer}\");\r\n            }\r\n        }\r\n\r\n        public static void Debug(this Logger logger, Socket sock, int len, string header = null, string tailer = null)\r\n        {\r\n            if (logger.IsDebugEnabled)\r\n            {\r\n                logger.Debug(sock.LocalEndPoint, sock.RemoteEndPoint, len, header, tailer);\r\n            }\r\n        }\r\n\r\n        public static void LogUsefulException(this Logger logger, Exception e)\r\n        {\r\n            // just log useful exceptions, not all of them\r\n            if (e is SocketException)\r\n            {\r\n                SocketException se = (SocketException)e;\r\n                if (se.SocketErrorCode == SocketError.ConnectionAborted)\r\n                {\r\n                    // closed by browser when sending\r\n                    // normally happens when download is canceled or a tab is closed before page is loaded\r\n                }\r\n                else if (se.SocketErrorCode == SocketError.ConnectionReset)\r\n                {\r\n                    // received rst\r\n                }\r\n                else if (se.SocketErrorCode == SocketError.NotConnected)\r\n                {\r\n                    // The application tried to send or receive data, and the System.Net.Sockets.Socket is not connected.\r\n                }\r\n                else if (se.SocketErrorCode == SocketError.HostUnreachable)\r\n                {\r\n                    // There is no network route to the specified host.\r\n                }\r\n                else if (se.SocketErrorCode == SocketError.TimedOut)\r\n                {\r\n                    // The connection attempt timed out, or the connected host has failed to respond.\r\n                }\r\n                else\r\n                {\r\n                    logger.Warn(e);\r\n                }\r\n            }\r\n            else if (e is ObjectDisposedException)\r\n            {\r\n            }\r\n            else if (e is Win32Exception)\r\n            {\r\n                var ex = (Win32Exception)e;\r\n\r\n                // Win32Exception (0x80004005): A 32 bit processes cannot access modules of a 64 bit process.\r\n                if ((uint)ex.ErrorCode != 0x80004005)\r\n                {\r\n                    logger.Warn(e);\r\n                }\r\n            }\r\n            else if (e is ProxyException)\r\n            {\r\n                var ex = (ProxyException)e;\r\n                switch (ex.Type)\r\n                {\r\n                    case ProxyExceptionType.FailToRun:\r\n                    case ProxyExceptionType.QueryReturnMalformed:\r\n                    case ProxyExceptionType.SysproxyExitError:\r\n                        logger.Error($\"sysproxy - {ex.Type.ToString()}:{ex.Message}\");\r\n                        break;\r\n                    case ProxyExceptionType.QueryReturnEmpty:\r\n                    case ProxyExceptionType.Unspecific:\r\n                        logger.Error($\"sysproxy - {ex.Type.ToString()}\");\r\n                        break;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                logger.Warn(e);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/GeositeUpdater.cs",
    "content": "﻿using NLog;\nusing Shadowsocks.Properties;\nusing Shadowsocks.Util;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing Newtonsoft.Json;\nusing Shadowsocks.Model;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing System.Security.Cryptography;\n\nnamespace Shadowsocks.Controller\n{\n    public class GeositeResultEventArgs : EventArgs\n    {\n        public bool Success;\n\n        public GeositeResultEventArgs(bool success)\n        {\n            this.Success = success;\n        }\n    }\n\n    public static class GeositeUpdater\n    {\n        private static Logger logger = LogManager.GetCurrentClassLogger();\n\n        public static event EventHandler<GeositeResultEventArgs> UpdateCompleted;\n\n        public static event ErrorEventHandler Error;\n\n        private static readonly string DATABASE_PATH = Utils.GetTempPath(\"dlc.dat\");\n\n        private static readonly string GEOSITE_URL = \"https://github.com/v2fly/domain-list-community/raw/release/dlc.dat\";\n        private static readonly string GEOSITE_SHA256SUM_URL = \"https://github.com/v2fly/domain-list-community/raw/release/dlc.dat.sha256sum\";\n        private static byte[] geositeDB;\n\n        public static readonly Dictionary<string, IList<DomainObject>> Geosites = new Dictionary<string, IList<DomainObject>>();\n\n        static GeositeUpdater()\n        {\n            if (File.Exists(DATABASE_PATH) && new FileInfo(DATABASE_PATH).Length > 0)\n            {\n                geositeDB = File.ReadAllBytes(DATABASE_PATH);\n            }\n            else\n            {\n                geositeDB = Resources.dlc_dat;\n                File.WriteAllBytes(DATABASE_PATH, Resources.dlc_dat);\n            }\n            LoadGeositeList();\n        }\n\n        /// <summary>\n        /// load new GeoSite data from geositeDB\n        /// </summary>\n        static void LoadGeositeList()\n        {\n            var list = GeositeList.Parser.ParseFrom(geositeDB);\n            foreach (var item in list.Entries)\n            {\n                Geosites[item.GroupName.ToLowerInvariant()] = item.Domains;\n            }\n        }\n\n        public static void ResetEvent()\n        {\n            UpdateCompleted = null;\n            Error = null;\n        }\n\n        public static async Task UpdatePACFromGeosite()\n        {\n            var geositeUrl = GEOSITE_URL;\n            var geositeSha256sumUrl = GEOSITE_SHA256SUM_URL;\n            var geositeVerifySha256 = true;\n            var geositeSha256sum = \"\";\n            var mySHA256 = SHA256.Create();\n            var config = Program.MainController.GetCurrentConfiguration();\n            var blacklist = config.geositePreferDirect;\n            var httpClient = Program.MainController.GetHttpClient();\n\n            if (!string.IsNullOrWhiteSpace(config.geositeUrl))\n            {\n                logger.Info(\"Found custom Geosite URL in config file\");\n                geositeUrl = config.geositeUrl;\n                geositeSha256sumUrl = config.geositeSha256sumUrl;\n                if (string.IsNullOrWhiteSpace(geositeSha256sumUrl))\n                {\n                    geositeVerifySha256 = false;\n                    logger.Info(\"Geosite SHA256 verification is disabled.\");\n                }\n            }\n            logger.Info($\"Checking Geosite from {geositeUrl}\");\n\n            try\n            {\n                // Use sha256sum to check if local database is already latest.\n                if (geositeVerifySha256)\n                {\n                    // download checksum first\n                    geositeSha256sum = await httpClient.GetStringAsync(geositeSha256sumUrl);\n                    geositeSha256sum = geositeSha256sum.Substring(0, 64).ToUpper();\n                    logger.Info($\"Got Sha256sum: {geositeSha256sum}\");\n                    // compare downloaded checksum with local geositeDB\n                    byte[] localDBHashBytes = mySHA256.ComputeHash(geositeDB);\n                    string localDBHash = BitConverter.ToString(localDBHashBytes).Replace(\"-\", String.Empty);\n                    logger.Info($\"Local Sha256sum: {localDBHash}\");\n                    // if already latest\n                    if (geositeSha256sum == localDBHash)\n                    {\n                        logger.Info(\"Local GeoSite DB is up to date.\");\n                        UpdateCompleted?.Invoke(null, new GeositeResultEventArgs(false));\n                        return;\n                    }\n                }\n\n                // not latest. download new DB\n                var downloadedBytes = await httpClient.GetByteArrayAsync(geositeUrl);\n\n                // verify sha256sum\n                if (geositeVerifySha256)\n                {\n                    byte[] downloadedDBHashBytes = mySHA256.ComputeHash(downloadedBytes);\n                    string downloadedDBHash = BitConverter.ToString(downloadedDBHashBytes).Replace(\"-\", String.Empty);\n                    logger.Info($\"Actual Sha256sum: {downloadedDBHash}\");\n                    if (geositeSha256sum != downloadedDBHash)\n                    {\n                        logger.Info(\"Sha256sum Verification: FAILED. Downloaded GeoSite DB is corrupted. Aborting the update.\");\n                        throw new Exception(\"Sha256sum mismatch\");\n                    }\n                    else\n                    {\n                        logger.Info(\"Sha256sum Verification: PASSED. Applying to local GeoSite DB.\");\n                    }\n                }\n\n                // write to geosite file\n                using (FileStream geositeFileStream = File.Create(DATABASE_PATH))\n                    await geositeFileStream.WriteAsync(downloadedBytes, 0, downloadedBytes.Length);\n\n                // update stuff\n                geositeDB = downloadedBytes;\n                LoadGeositeList();\n                bool pacFileChanged = MergeAndWritePACFile(config.geositeDirectGroups, config.geositeProxiedGroups, blacklist);\n                UpdateCompleted?.Invoke(null, new GeositeResultEventArgs(pacFileChanged));\n            }\n            catch (Exception ex)\n            {\n                Error?.Invoke(null, new ErrorEventArgs(ex));\n            }\n        }\n\n        /// <summary>\n        /// Merge and write pac.txt from geosite.\n        /// Used at multiple places.\n        /// </summary>\n        /// <param name=\"directGroups\">A list of geosite groups configured for direct connection.</param>\n        /// <param name=\"proxiedGroups\">A list of geosite groups configured for proxied connection.</param>\n        /// <param name=\"blacklist\">Whether to use blacklist mode. False for whitelist.</param>\n        /// <returns></returns>\n        public static bool MergeAndWritePACFile(List<string> directGroups, List<string> proxiedGroups, bool blacklist)\n        {\n            string abpContent = MergePACFile(directGroups, proxiedGroups, blacklist);\n            if (File.Exists(PACDaemon.PAC_FILE))\n            {\n                string original = FileManager.NonExclusiveReadAllText(PACDaemon.PAC_FILE, Encoding.UTF8);\n                if (original == abpContent)\n                {\n                    return false;\n                }\n            }\n            File.WriteAllText(PACDaemon.PAC_FILE, abpContent, Encoding.UTF8);\n            return true;\n        }\n\n        /// <summary>\n        /// Checks if the specified group exists in GeoSite database.\n        /// </summary>\n        /// <param name=\"group\">The group name to check for.</param>\n        /// <returns>True if the group exists. False if the group doesn't exist.</returns>\n        public static bool CheckGeositeGroup(string group) => SeparateAttributeFromGroupName(group, out string groupName, out _) && Geosites.ContainsKey(groupName);\n\n        /// <summary>\n        /// Separates the attribute (e.g. @cn) from a group name.\n        /// No checks are performed.\n        /// </summary>\n        /// <param name=\"group\">A group name potentially with a trailing attribute.</param>\n        /// <param name=\"groupName\">The group name with the attribute stripped.</param>\n        /// <param name=\"attribute\">The attribute.</param>\n        /// <returns>True for success. False for more than one '@'.</returns>\n        private static bool SeparateAttributeFromGroupName(string group, out string groupName, out string attribute)\n        {\n            var splitGroupAttributeList = group.Split('@');\n            if (splitGroupAttributeList.Length == 1) // no attribute\n            {\n                groupName = splitGroupAttributeList[0];\n                attribute = \"\";\n            }\n            else if (splitGroupAttributeList.Length == 2) // has attribute\n            {\n                groupName = splitGroupAttributeList[0];\n                attribute = splitGroupAttributeList[1];\n            }\n            else\n            {\n                groupName = \"\";\n                attribute = \"\";\n                return false;\n            }    \n            return true;\n        }\n\n        private static string MergePACFile(List<string> directGroups, List<string> proxiedGroups, bool blacklist)\n        {\n            string abpContent;\n            if (File.Exists(PACDaemon.USER_ABP_FILE))\n            {\n                abpContent = FileManager.NonExclusiveReadAllText(PACDaemon.USER_ABP_FILE, Encoding.UTF8);\n            }\n            else\n            {\n                abpContent = Resources.abp_js;\n            }\n\n            List<string> userruleLines = new List<string>();\n            if (File.Exists(PACDaemon.USER_RULE_FILE))\n            {\n                string userrulesString = FileManager.NonExclusiveReadAllText(PACDaemon.USER_RULE_FILE, Encoding.UTF8);\n                userruleLines = ProcessUserRules(userrulesString);\n            }\n\n            List<string> ruleLines = GenerateRules(directGroups, proxiedGroups, blacklist);\n            abpContent =\n$@\"var __USERRULES__ = {JsonConvert.SerializeObject(userruleLines, Formatting.Indented)};\nvar __RULES__ = {JsonConvert.SerializeObject(ruleLines, Formatting.Indented)};\n{abpContent}\";\n            return abpContent;\n        }\n\n        private static List<string> ProcessUserRules(string content)\n        {\n            List<string> valid_lines = new List<string>();\n            using (var stringReader = new StringReader(content))\n            {\n                for (string line = stringReader.ReadLine(); line != null; line = stringReader.ReadLine())\n                {\n                    if (string.IsNullOrWhiteSpace(line) || line.StartsWith(\"!\") || line.StartsWith(\"[\"))\n                        continue;\n                    valid_lines.Add(line);\n                }\n            }\n            return valid_lines;\n        }\n\n        /// <summary>\n        /// Generates rule lines based on user preference.\n        /// </summary>\n        /// <param name=\"directGroups\">A list of geosite groups configured for direct connection.</param>\n        /// <param name=\"proxiedGroups\">A list of geosite groups configured for proxied connection.</param>\n        /// <param name=\"blacklist\">Whether to use blacklist mode. False for whitelist.</param>\n        /// <returns>A list of rule lines.</returns>\n        private static List<string> GenerateRules(List<string> directGroups, List<string> proxiedGroups, bool blacklist)\n        {\n            List<string> ruleLines;\n            if (blacklist) // blocking + exception rules\n            {\n                ruleLines = GenerateBlockingRules(proxiedGroups);\n                ruleLines.AddRange(GenerateExceptionRules(directGroups));\n            }\n            else // proxy all + exception rules\n            {\n                ruleLines = new List<string>()\n                {\n                    \"/.*/\" // block/proxy all unmatched domains\n                };\n                ruleLines.AddRange(GenerateExceptionRules(directGroups));\n            }\n            return ruleLines;\n        }\n\n        /// <summary>\n        /// Generates rules that match domains that should be proxied.\n        /// </summary>\n        /// <param name=\"groups\">A list of source groups.</param>\n        /// <returns>A list of rule lines.</returns>\n        private static List<string> GenerateBlockingRules(List<string> groups)\n        {\n            List<string> ruleLines = new List<string>();\n            foreach (var group in groups)\n            {\n                // separate group name and attribute\n                SeparateAttributeFromGroupName(group, out string groupName, out string attribute);\n                var domainObjects = Geosites[groupName];\n                if (!string.IsNullOrEmpty(attribute)) // has attribute\n                {\n                    var attributeObject = new DomainObject.Types.Attribute\n                    {\n                        Key = attribute,\n                        BoolValue = true\n                    };\n                    foreach (var domainObject in domainObjects)\n                    {\n                        if (domainObject.Attribute.Contains(attributeObject))\n                            switch (domainObject.Type)\n                            {\n                                case DomainObject.Types.Type.Plain:\n                                    ruleLines.Add(domainObject.Value);\n                                    break;\n                                case DomainObject.Types.Type.Regex:\n                                    ruleLines.Add($\"/{domainObject.Value}/\");\n                                    break;\n                                case DomainObject.Types.Type.Domain:\n                                    ruleLines.Add($\"||{domainObject.Value}\");\n                                    break;\n                                case DomainObject.Types.Type.Full:\n                                    ruleLines.Add($\"|http://{domainObject.Value}\");\n                                    ruleLines.Add($\"|https://{domainObject.Value}\");\n                                    break;\n                            }\n                    }\n                }\n                else // no attribute\n                    foreach (var domainObject in domainObjects)\n                    {\n                        switch (domainObject.Type)\n                        {\n                            case DomainObject.Types.Type.Plain:\n                                ruleLines.Add(domainObject.Value);\n                                break;\n                            case DomainObject.Types.Type.Regex:\n                                ruleLines.Add($\"/{domainObject.Value}/\");\n                                break;\n                            case DomainObject.Types.Type.Domain:\n                                ruleLines.Add($\"||{domainObject.Value}\");\n                                break;\n                            case DomainObject.Types.Type.Full:\n                                ruleLines.Add($\"|http://{domainObject.Value}\");\n                                ruleLines.Add($\"|https://{domainObject.Value}\");\n                                break;\n                        }\n                    }\n            }\n            return ruleLines;\n        }\n\n        /// <summary>\n        /// Generates rules that match domains that should be connected directly without a proxy.\n        /// </summary>\n        /// <param name=\"groups\">A list of source groups.</param>\n        /// <returns>A list of rule lines.</returns>\n        private static List<string> GenerateExceptionRules(List<string> groups)\n            => GenerateBlockingRules(groups)\n                .Select(r => $\"@@{r}\") // convert blocking rules to exception rules\n                .ToList();\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/IPCService.cs",
    "content": "﻿using System;\nusing System.IO.Pipes;\nusing System.Net;\nusing System.Text;\n\nnamespace Shadowsocks.Controller\n{\n    class RequestAddUrlEventArgs : EventArgs\n    {\n        public readonly string Url;\n\n        public RequestAddUrlEventArgs(string url)\n        {\n            this.Url = url;\n        }\n    }\n\n    internal class IPCService\n    {\n        private const int INT32_LEN = 4;\n        private const int OP_OPEN_URL = 1;\n        private static readonly string PIPE_PATH = $\"Shadowsocks\\\\{Program.ExecutablePath.GetHashCode()}\";\n\n        public event EventHandler<RequestAddUrlEventArgs> OpenUrlRequested;\n\n        public async void RunServer()\n        {\n            byte[] buf = new byte[4096];\n            while (true)\n            {\n                using (NamedPipeServerStream stream = new NamedPipeServerStream(PIPE_PATH))\n                {\n                    await stream.WaitForConnectionAsync();\n                    await stream.ReadAsync(buf, 0, INT32_LEN);\n                    int opcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buf, 0));\n                    if (opcode == OP_OPEN_URL)\n                    {\n                        await stream.ReadAsync(buf, 0, INT32_LEN);\n                        int strlen = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buf, 0));\n\n                        await stream.ReadAsync(buf, 0, strlen);\n                        string url = Encoding.UTF8.GetString(buf, 0, strlen);\n\n                        OpenUrlRequested?.Invoke(this, new RequestAddUrlEventArgs(url));\n                    }\n                    stream.Close();\n                }\n            }\n        }\n\n        private static (NamedPipeClientStream, bool) TryConnect()\n        {\n            NamedPipeClientStream pipe = new NamedPipeClientStream(PIPE_PATH);\n            bool exist;\n            try\n            {\n                pipe.Connect(10);\n                exist = true;\n            }\n            catch (TimeoutException)\n            {\n                exist = false;\n            }\n            return (pipe, exist);\n        }\n\n        public static bool AnotherInstanceRunning()\n        {\n            (NamedPipeClientStream pipe, bool exist) = TryConnect();\n            pipe.Dispose();\n            return exist;\n        }\n\n        public static void RequestOpenUrl(string url)\n        {\n            (NamedPipeClientStream pipe, bool exist) = TryConnect();\n            if(!exist) return;\n            byte[] opAddUrl = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(OP_OPEN_URL));\n            pipe.Write(opAddUrl, 0, INT32_LEN); // opcode addurl\n            byte[] b = Encoding.UTF8.GetBytes(url);\n            byte[] blen = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(b.Length));\n            pipe.Write(blen, 0, INT32_LEN);\n            pipe.Write(b, 0, b.Length);\n            pipe.Close();\n            pipe.Dispose();\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/Listener.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Net;\r\nusing System.Net.NetworkInformation;\r\nusing System.Net.Sockets;\r\nusing NLog;\r\nusing Shadowsocks.Model;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    public class Listener\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        public interface IService\r\n        {\r\n            bool Handle(byte[] firstPacket, int length, Socket socket, object state);\r\n\r\n            void Stop();\r\n        }\r\n\r\n        public abstract class Service : IService\r\n        {\r\n            public abstract bool Handle(byte[] firstPacket, int length, Socket socket, object state);\r\n\r\n            public virtual void Stop() { }\r\n        }\r\n\r\n        public class UDPState\r\n        {\r\n            public UDPState(Socket s)\r\n            {\r\n                socket = s;\r\n                remoteEndPoint = new IPEndPoint(s.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, 0);\r\n            }\r\n            public Socket socket;\r\n            public byte[] buffer = new byte[4096];\r\n            public EndPoint remoteEndPoint;\r\n        }\r\n\r\n        Configuration _config;\r\n        bool _shareOverLAN;\r\n        Socket _tcpSocket;\r\n        Socket _udpSocket;\r\n        List<IService> _services;\r\n\r\n        public Listener(List<IService> services)\r\n        {\r\n            this._services = services;\r\n        }\r\n\r\n        private bool CheckIfPortInUse(int port)\r\n        {\r\n            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();\r\n            return ipProperties.GetActiveTcpListeners().Any(endPoint => endPoint.Port == port);\r\n        }\r\n\r\n        public void Start(Configuration config)\r\n        {\r\n            this._config = config;\r\n            this._shareOverLAN = config.shareOverLan;\r\n\r\n            if (CheckIfPortInUse(_config.localPort))\r\n                throw new Exception(I18N.GetString(\"Port {0} already in use\", _config.localPort));\r\n\r\n            try\r\n            {\r\n                // Create a TCP/IP socket.\r\n                _tcpSocket = new Socket(config.isIPv6Enabled ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\r\n                _udpSocket = new Socket(config.isIPv6Enabled ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\r\n                _tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);\r\n                _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);\r\n                IPEndPoint localEndPoint = null;\r\n                localEndPoint = _shareOverLAN\r\n                    ? new IPEndPoint(config.isIPv6Enabled ? IPAddress.IPv6Any : IPAddress.Any, _config.localPort)\r\n                    : new IPEndPoint(config.isIPv6Enabled ? IPAddress.IPv6Loopback : IPAddress.Loopback, _config.localPort);\r\n\r\n                // Bind the socket to the local endpoint and listen for incoming connections.\r\n                _tcpSocket.Bind(localEndPoint);\r\n                _udpSocket.Bind(localEndPoint);\r\n                _tcpSocket.Listen(1024);\r\n\r\n                // Start an asynchronous socket to listen for connections.\r\n                logger.Info($\"Shadowsocks started ({UpdateChecker.Version})\");\r\n                logger.Debug(Encryption.EncryptorFactory.DumpRegisteredEncryptor());\r\n                _tcpSocket.BeginAccept(new AsyncCallback(AcceptCallback), _tcpSocket);\r\n                UDPState udpState = new UDPState(_udpSocket);\r\n                _udpSocket.BeginReceiveFrom(udpState.buffer, 0, udpState.buffer.Length, 0, ref udpState.remoteEndPoint, new AsyncCallback(RecvFromCallback), udpState);\r\n            }\r\n            catch (SocketException)\r\n            {\r\n                _tcpSocket.Close();\r\n                throw;\r\n            }\r\n        }\r\n\r\n        public void Stop()\r\n        {\r\n            if (_tcpSocket != null)\r\n            {\r\n                _tcpSocket.Close();\r\n                _tcpSocket = null;\r\n            }\r\n            if (_udpSocket != null)\r\n            {\r\n                _udpSocket.Close();\r\n                _udpSocket = null;\r\n            }\r\n\r\n            _services.ForEach(s => s.Stop());\r\n        }\r\n\r\n        public void RecvFromCallback(IAsyncResult ar)\r\n        {\r\n            UDPState state = (UDPState)ar.AsyncState;\r\n            var socket = state.socket;\r\n            try\r\n            {\r\n                int bytesRead = socket.EndReceiveFrom(ar, ref state.remoteEndPoint);\r\n                foreach (IService service in _services)\r\n                {\r\n                    if (service.Handle(state.buffer, bytesRead, socket, state))\r\n                    {\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n            catch (ObjectDisposedException)\r\n            {\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                logger.Debug(ex);\r\n            }\r\n            finally\r\n            {\r\n                try\r\n                {\r\n                    socket.BeginReceiveFrom(state.buffer, 0, state.buffer.Length, 0, ref state.remoteEndPoint, new AsyncCallback(RecvFromCallback), state);\r\n                }\r\n                catch (ObjectDisposedException)\r\n                {\r\n                    // do nothing\r\n                }\r\n                catch (Exception)\r\n                {\r\n                }\r\n            }\r\n        }\r\n\r\n        public void AcceptCallback(IAsyncResult ar)\r\n        {\r\n            Socket listener = (Socket)ar.AsyncState;\r\n            try\r\n            {\r\n                Socket conn = listener.EndAccept(ar);\r\n\r\n                byte[] buf = new byte[4096];\r\n                object[] state = new object[] {\r\n                    conn,\r\n                    buf\r\n                };\r\n\r\n                conn.BeginReceive(buf, 0, buf.Length, 0,\r\n                    new AsyncCallback(ReceiveCallback), state);\r\n            }\r\n            catch (ObjectDisposedException)\r\n            {\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n            finally\r\n            {\r\n                try\r\n                {\r\n                    listener.BeginAccept(\r\n                        new AsyncCallback(AcceptCallback),\r\n                        listener);\r\n                }\r\n                catch (ObjectDisposedException)\r\n                {\r\n                    // do nothing\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.LogUsefulException(e);\r\n                }\r\n            }\r\n        }\r\n\r\n        private void ReceiveCallback(IAsyncResult ar)\r\n        {\r\n            object[] state = (object[])ar.AsyncState;\r\n\r\n            Socket conn = (Socket)state[0];\r\n            byte[] buf = (byte[])state[1];\r\n            try\r\n            {\r\n                int bytesRead = conn.EndReceive(ar);\r\n                if (bytesRead <= 0) goto Shutdown;\r\n                foreach (IService service in _services)\r\n                {\r\n                    if (service.Handle(buf, bytesRead, conn, null))\r\n                    {\r\n                        return;\r\n                    }\r\n                }\r\n                Shutdown:\r\n                // no service found for this\r\n                if (conn.ProtocolType == ProtocolType.Tcp)\r\n                {\r\n                    conn.Close();\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n                conn.Close();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/OnlineConfigResolver.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json.Linq;\nusing Shadowsocks.Model;\n\nnamespace Shadowsocks.Controller.Service\n{\n    public class OnlineConfigResolver\n    {\n        public static async Task<List<Server>> GetOnline(string url)\n        {\n            var httpClient = Program.MainController.GetHttpClient();\n            string server_json = await httpClient.GetStringAsync(url);\n            var servers = server_json.GetServers();\n            foreach (var server in servers)\n            {\n                server.group = url;\n            }\n            return servers.ToList();\n        }\n    }\n\n    internal static class OnlineConfigResolverEx\n    {\n        private static readonly string[] BASIC_FORMAT = new[] { \"server\", \"server_port\", \"password\", \"method\" };\n\n        private static readonly IEnumerable<Server> EMPTY_SERVERS = Array.Empty<Server>();\n\n        internal static IEnumerable<Server> GetServers(this string json) =>\n            JToken.Parse(json).SearchJToken().AsEnumerable();\n\n        private static IEnumerable<Server> SearchJArray(JArray array) =>\n            array == null ? EMPTY_SERVERS : array.SelectMany(SearchJToken).ToList();\n\n        private static IEnumerable<Server> SearchJObject(JObject obj)\n        {\n            if (obj == null)\n                return EMPTY_SERVERS;\n\n            if (BASIC_FORMAT.All(field => obj.ContainsKey(field)))\n                return new[] { obj.ToObject<Server>() };\n\n            var servers = new List<Server>();\n            foreach (var kv in obj)\n            {\n                var token = kv.Value;\n                servers.AddRange(SearchJToken(token));\n            }\n            return servers;\n        }\n\n        private static IEnumerable<Server> SearchJToken(this JToken token)\n        {\n            switch (token.Type)\n            {\n                default:\n                    return Array.Empty<Server>();\n                case JTokenType.Object:\n                    return SearchJObject(token as JObject);\n                case JTokenType.Array:\n                    return SearchJArray(token as JArray);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/PACDaemon.cs",
    "content": "﻿using NLog;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Properties;\r\nusing Shadowsocks.Util;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n\r\n    /// <summary>\r\n    /// Processing the PAC file content\r\n    /// </summary>\r\n    public class PACDaemon\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        public const string PAC_FILE = \"pac.txt\";\r\n        public const string USER_RULE_FILE = \"user-rule.txt\";\r\n        public const string USER_ABP_FILE = \"abp.txt\";\r\n        private Configuration config;\r\n\r\n        FileSystemWatcher PACFileWatcher;\r\n        FileSystemWatcher UserRuleFileWatcher;\r\n\r\n        public event EventHandler PACFileChanged;\r\n        public event EventHandler UserRuleFileChanged;\r\n\r\n        public PACDaemon(Configuration config)\r\n        {\r\n            this.config = config;\r\n            TouchPACFile();\r\n            TouchUserRuleFile();\r\n\r\n            this.WatchPacFile();\r\n            this.WatchUserRuleFile();\r\n        }\r\n\r\n\r\n        public string TouchPACFile()\r\n        {\r\n            if (!File.Exists(PAC_FILE))\r\n            {\r\n                GeositeUpdater.MergeAndWritePACFile(config.geositeDirectGroups, config.geositeProxiedGroups, config.geositePreferDirect);\r\n            }\r\n            return PAC_FILE;\r\n        }\r\n\r\n        internal string TouchUserRuleFile()\r\n        {\r\n            if (!File.Exists(USER_RULE_FILE))\r\n            {\r\n                File.WriteAllText(USER_RULE_FILE, Resources.user_rule);\r\n            }\r\n            return USER_RULE_FILE;\r\n        }\r\n\r\n        internal string GetPACContent()\r\n        {\r\n            if (!File.Exists(PAC_FILE))\r\n            {\r\n                GeositeUpdater.MergeAndWritePACFile(config.geositeDirectGroups, config.geositeProxiedGroups, config.geositePreferDirect);\r\n            }\r\n            return File.ReadAllText(PAC_FILE, Encoding.UTF8);\r\n        }\r\n\r\n\r\n        private void WatchPacFile()\r\n        {\r\n            PACFileWatcher?.Dispose();\r\n            PACFileWatcher = new FileSystemWatcher(Program.WorkingDirectory);\r\n            PACFileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;\r\n            PACFileWatcher.Filter = PAC_FILE;\r\n            PACFileWatcher.Changed += PACFileWatcher_Changed;\r\n            PACFileWatcher.Created += PACFileWatcher_Changed;\r\n            PACFileWatcher.Deleted += PACFileWatcher_Changed;\r\n            PACFileWatcher.Renamed += PACFileWatcher_Changed;\r\n            PACFileWatcher.EnableRaisingEvents = true;\r\n        }\r\n\r\n        private void WatchUserRuleFile()\r\n        {\r\n            UserRuleFileWatcher?.Dispose();\r\n            UserRuleFileWatcher = new FileSystemWatcher(Program.WorkingDirectory);\r\n            UserRuleFileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;\r\n            UserRuleFileWatcher.Filter = USER_RULE_FILE;\r\n            UserRuleFileWatcher.Changed += UserRuleFileWatcher_Changed;\r\n            UserRuleFileWatcher.Created += UserRuleFileWatcher_Changed;\r\n            UserRuleFileWatcher.Deleted += UserRuleFileWatcher_Changed;\r\n            UserRuleFileWatcher.Renamed += UserRuleFileWatcher_Changed;\r\n            UserRuleFileWatcher.EnableRaisingEvents = true;\r\n        }\r\n\r\n        #region FileSystemWatcher.OnChanged()\r\n        // FileSystemWatcher Changed event is raised twice\r\n        // http://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice\r\n        // Add a short delay to avoid raise event twice in a short period\r\n        private void PACFileWatcher_Changed(object sender, FileSystemEventArgs e)\r\n        {\r\n            if (PACFileChanged != null)\r\n            {\r\n                logger.Info($\"Detected: PAC file '{e.Name}' was {e.ChangeType.ToString().ToLower()}.\");\r\n                Task.Factory.StartNew(() =>\r\n                {\r\n                    ((FileSystemWatcher)sender).EnableRaisingEvents = false;\r\n                    System.Threading.Thread.Sleep(10);\r\n                    PACFileChanged(this, new EventArgs());\r\n                    ((FileSystemWatcher)sender).EnableRaisingEvents = true;\r\n                });\r\n            }\r\n        }\r\n\r\n        private void UserRuleFileWatcher_Changed(object sender, FileSystemEventArgs e)\r\n        {\r\n            if (UserRuleFileChanged != null)\r\n            {\r\n                logger.Info($\"Detected: User Rule file '{e.Name}' was {e.ChangeType.ToString().ToLower()}.\");\r\n                Task.Factory.StartNew(() =>\r\n                {\r\n                    ((FileSystemWatcher)sender).EnableRaisingEvents = false;\r\n                    System.Threading.Thread.Sleep(10);\r\n                    UserRuleFileChanged(this, new EventArgs());\r\n                    ((FileSystemWatcher)sender).EnableRaisingEvents = true;\r\n                });\r\n            }\r\n        }\r\n        #endregion\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/PACServer.cs",
    "content": "﻿using Shadowsocks.Encryption;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Util;\r\nusing System;\r\nusing System.Net;\r\nusing System.Net.Sockets;\r\nusing System.Text;\r\nusing System.Web;\r\nusing NLog;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    public class PACServer : Listener.Service\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        public const string RESOURCE_NAME = \"pac\";\r\n\r\n        private string PacSecret\r\n        {\r\n            get\r\n            {\r\n                if (string.IsNullOrEmpty(_cachedPacSecret))\r\n                {\r\n                    var rd = new byte[32];\r\n                    RNG.GetBytes(rd);\r\n                    _cachedPacSecret = HttpServerUtility.UrlTokenEncode(rd);\r\n                }\r\n                return _cachedPacSecret;\r\n            }\r\n        }\r\n        private string _cachedPacSecret = \"\";\r\n        public string PacUrl { get; private set; } = \"\";\r\n\r\n        private Configuration _config;\r\n        private PACDaemon _pacDaemon;\r\n\r\n        public PACServer(PACDaemon pacDaemon)\r\n        {\r\n            _pacDaemon = pacDaemon;\r\n        }\r\n\r\n        public void UpdatePACURL(Configuration config)\r\n        {\r\n            _config = config;\r\n            string usedSecret = _config.secureLocalPac ? $\"&secret={PacSecret}\" : \"\";\r\n            string contentHash = GetHash(_pacDaemon.GetPACContent());\r\n            PacUrl = $\"http://{config.LocalHost}:{config.localPort}/{RESOURCE_NAME}?hash={contentHash}{usedSecret}\";\r\n            logger.Debug(\"Set PAC URL:\" + PacUrl);\r\n        }\r\n\r\n        private static string GetHash(string content)\r\n        {\r\n            return HttpServerUtility.UrlTokenEncode(MbedTLS.MD5(Encoding.ASCII.GetBytes(content)));\r\n        }\r\n\r\n        public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)\r\n        {\r\n            if (socket.ProtocolType != ProtocolType.Tcp)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            try\r\n            {\r\n                /*\r\n                 *  RFC 7230\r\n                 *  \r\n                    GET /hello.txt HTTP/1.1\r\n                    User-Agent: curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3\r\n                    Host: www.example.com\r\n                    Accept-Language: en, mi \r\n                 */\r\n\r\n                string request = Encoding.UTF8.GetString(firstPacket, 0, length);\r\n                string[] lines = request.Split('\\r', '\\n');\r\n                bool hostMatch = false, pathMatch = false, useSocks = false;\r\n                bool secretMatch = !_config.secureLocalPac;\r\n\r\n                if (lines.Length < 2)   // need at lease RequestLine + Host\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                // parse request line\r\n                string requestLine = lines[0];\r\n                // GET /pac?t=yyyyMMddHHmmssfff&secret=foobar HTTP/1.1\r\n                string[] requestItems = requestLine.Split(' ');\r\n                if (requestItems.Length == 3 && requestItems[0] == \"GET\")\r\n                {\r\n                    int index = requestItems[1].IndexOf('?');\r\n                    if (index < 0)\r\n                    {\r\n                        index = requestItems[1].Length;\r\n                    }\r\n                    string resourceString = requestItems[1].Substring(0, index).Remove(0, 1);\r\n                    if (string.Equals(resourceString, RESOURCE_NAME, StringComparison.OrdinalIgnoreCase))\r\n                    {\r\n                        pathMatch = true;\r\n                        if (!secretMatch)\r\n                        {\r\n                            string queryString = requestItems[1].Substring(index);\r\n                            if (queryString.Contains(PacSecret))\r\n                            {\r\n                                secretMatch = true;\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n\r\n                // parse request header\r\n                for (int i = 1; i < lines.Length; i++)\r\n                {\r\n                    if (string.IsNullOrEmpty(lines[i]))\r\n                        continue;\r\n\r\n                    string[] kv = lines[i].Split(new char[] { ':' }, 2);\r\n                    if (kv.Length == 2)\r\n                    {\r\n                        if (kv[0] == \"Host\")\r\n                        {\r\n                            if (kv[1].Trim() == ((IPEndPoint)socket.LocalEndPoint).ToString())\r\n                            {\r\n                                hostMatch = true;\r\n                            }\r\n                        }\r\n                        //else if (kv[0] == \"User-Agent\")\r\n                        //{\r\n                        //    // we need to drop connections when changing servers\r\n                        //    if (kv[1].IndexOf(\"Chrome\") >= 0)\r\n                        //    {\r\n                        //        useSocks = true;\r\n                        //    }\r\n                        //}\r\n                    }\r\n                }\r\n\r\n                if (hostMatch && pathMatch)\r\n                {\r\n                    if (!secretMatch)\r\n                    {\r\n                        socket.Close(); // Close immediately\r\n                    }\r\n                    else\r\n                    {\r\n                        SendResponse(socket, useSocks);\r\n                    }\r\n                    return true;\r\n                }\r\n                return false;\r\n            }\r\n            catch (ArgumentException)\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n\r\n\r\n\r\n        public void SendResponse(Socket socket, bool useSocks)\r\n        {\r\n            try\r\n            {\r\n                IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;\r\n\r\n                string proxy = GetPACAddress(localEndPoint, useSocks);\r\n\r\n                string pacContent = $\"var __PROXY__ = '{proxy}';\\n\" + _pacDaemon.GetPACContent();\r\n                string responseHead =\r\n$@\"HTTP/1.1 200 OK\r\nServer: ShadowsocksWindows/{UpdateChecker.Version}\r\nContent-Type: application/x-ns-proxy-autoconfig\r\nContent-Length: { Encoding.UTF8.GetBytes(pacContent).Length}\r\nConnection: Close\r\n\r\n\";\r\n                byte[] response = Encoding.UTF8.GetBytes(responseHead + pacContent);\r\n                socket.BeginSend(response, 0, response.Length, 0, new AsyncCallback(SendCallback), socket);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n                socket.Close();\r\n            }\r\n        }\r\n\r\n        private void SendCallback(IAsyncResult ar)\r\n        {\r\n            Socket conn = (Socket)ar.AsyncState;\r\n            try\r\n            {\r\n                conn.Shutdown(SocketShutdown.Send);\r\n            }\r\n            catch\r\n            { }\r\n        }\r\n\r\n\r\n        private string GetPACAddress(IPEndPoint localEndPoint, bool useSocks)\r\n        {\r\n            return localEndPoint.AddressFamily == AddressFamily.InterNetworkV6\r\n                ? $\"{(useSocks ? \"SOCKS5\" : \"PROXY\")} [{localEndPoint.Address}]:{_config.localPort};\"\r\n                : $\"{(useSocks ? \"SOCKS5\" : \"PROXY\")} {localEndPoint.Address}:{_config.localPort};\";\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/PortForwarder.cs",
    "content": "﻿using System;\r\nusing System.Net;\r\nusing System.Net.Sockets;\r\nusing NLog;\r\nusing Shadowsocks.Util.Sockets;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    class PortForwarder : Listener.Service\r\n    {\r\n        private readonly int _targetPort;\r\n\r\n        public PortForwarder(int targetPort)\r\n        {\r\n            _targetPort = targetPort;\r\n        }\r\n\r\n        public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)\r\n        {\r\n            if (socket.ProtocolType != ProtocolType.Tcp)\r\n            {\r\n                return false;\r\n            }\r\n            new Handler().Start(firstPacket, length, socket, _targetPort);\r\n            return true;\r\n        }\r\n\r\n        private class Handler\r\n        {\r\n            private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n            private byte[] _firstPacket;\r\n            private int _firstPacketLength;\r\n            private Socket _local;\r\n            private WrappedSocket _remote;\r\n            private bool _closed = false;\r\n            private bool _localShutdown = false;\r\n            private bool _remoteShutdown = false;\r\n            private const int RecvSize = 2048;\r\n            // remote receive buffer\r\n            private byte[] remoteRecvBuffer = new byte[RecvSize];\r\n            // connection receive buffer\r\n            private byte[] connetionRecvBuffer = new byte[RecvSize];\r\n\r\n            // instance-based lock\r\n            private readonly object _Lock = new object();\r\n\r\n            public void Start(byte[] firstPacket, int length, Socket socket, int targetPort)\r\n            {\r\n                _firstPacket = firstPacket;\r\n                _firstPacketLength = length;\r\n                _local = socket;\r\n                try\r\n                {\r\n                    // Local Port Forward use IP as is\r\n                    EndPoint remoteEP = SocketUtil.GetEndPoint(_local.AddressFamily == AddressFamily.InterNetworkV6 ? \"[::1]\" : \"127.0.0.1\", targetPort);\r\n\r\n                    // Connect to the remote endpoint.\r\n                    _remote = new WrappedSocket();\r\n                    _remote.BeginConnect(remoteEP, ConnectCallback, null);\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.LogUsefulException(e);\r\n                    Close();\r\n                }\r\n            }\r\n\r\n            private void ConnectCallback(IAsyncResult ar)\r\n            {\r\n                if (_closed)\r\n                {\r\n                    return;\r\n                }\r\n                try\r\n                {\r\n                    _remote.EndConnect(ar);\r\n                    _remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);\r\n                    HandshakeReceive();\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.LogUsefulException(e);\r\n                    Close();\r\n                }\r\n            }\r\n\r\n            private void HandshakeReceive()\r\n            {\r\n                if (_closed)\r\n                {\r\n                    return;\r\n                }\r\n                try\r\n                {\r\n                    _remote.BeginSend(_firstPacket, 0, _firstPacketLength, 0, StartPipe, null);\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.LogUsefulException(e);\r\n                    Close();\r\n                }\r\n            }\r\n\r\n            private void StartPipe(IAsyncResult ar)\r\n            {\r\n                if (_closed)\r\n                {\r\n                    return;\r\n                }\r\n                try\r\n                {\r\n                    _remote.EndSend(ar);\r\n                    _remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0,\r\n                        PipeRemoteReceiveCallback, null);\r\n                    _local.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,\r\n                        PipeConnectionReceiveCallback, null);\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.LogUsefulException(e);\r\n                    Close();\r\n                }\r\n            }\r\n\r\n            private void PipeRemoteReceiveCallback(IAsyncResult ar)\r\n            {\r\n                if (_closed)\r\n                {\r\n                    return;\r\n                }\r\n                try\r\n                {\r\n                    int bytesRead = _remote.EndReceive(ar);\r\n                    if (bytesRead > 0)\r\n                    {\r\n                        _local.BeginSend(remoteRecvBuffer, 0, bytesRead, 0, PipeConnectionSendCallback, null);\r\n                    }\r\n                    else\r\n                    {\r\n                        _local.Shutdown(SocketShutdown.Send);\r\n                        _localShutdown = true;\r\n                        CheckClose();\r\n                    }\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.LogUsefulException(e);\r\n                    Close();\r\n                }\r\n            }\r\n\r\n            private void PipeConnectionReceiveCallback(IAsyncResult ar)\r\n            {\r\n                if (_closed)\r\n                {\r\n                    return;\r\n                }\r\n                try\r\n                {\r\n                    int bytesRead = _local.EndReceive(ar);\r\n                    if (bytesRead > 0)\r\n                    {\r\n                        _remote.BeginSend(connetionRecvBuffer, 0, bytesRead, 0, PipeRemoteSendCallback, null);\r\n                    }\r\n                    else\r\n                    {\r\n                        _remote.Shutdown(SocketShutdown.Send);\r\n                        _remoteShutdown = true;\r\n                        CheckClose();\r\n                    }\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.LogUsefulException(e);\r\n                    Close();\r\n                }\r\n            }\r\n\r\n            private void PipeRemoteSendCallback(IAsyncResult ar)\r\n            {\r\n                if (_closed)\r\n                {\r\n                    return;\r\n                }\r\n                try\r\n                {\r\n                    _remote.EndSend(ar);\r\n                    _local.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,\r\n                        PipeConnectionReceiveCallback, null);\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.LogUsefulException(e);\r\n                    Close();\r\n                }\r\n            }\r\n\r\n            private void PipeConnectionSendCallback(IAsyncResult ar)\r\n            {\r\n                if (_closed)\r\n                {\r\n                    return;\r\n                }\r\n                try\r\n                {\r\n                    _local.EndSend(ar);\r\n                    _remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0,\r\n                        PipeRemoteReceiveCallback, null);\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.LogUsefulException(e);\r\n                    Close();\r\n                }\r\n            }\r\n\r\n            private void CheckClose()\r\n            {\r\n                if (_localShutdown && _remoteShutdown)\r\n                {\r\n                    Close();\r\n                }\r\n            }\r\n\r\n            public void Close()\r\n            {\r\n                lock (_Lock)\r\n                {\r\n                    if (_closed)\r\n                    {\r\n                        return;\r\n                    }\r\n                    _closed = true;\r\n                }\r\n                if (_local != null)\r\n                {\r\n                    try\r\n                    {\r\n                        _local.Shutdown(SocketShutdown.Both);\r\n                        _local.Close();\r\n                    }\r\n                    catch (Exception e)\r\n                    {\r\n                        logger.LogUsefulException(e);\r\n                    }\r\n                }\r\n                if (_remote != null)\r\n                {\r\n                    try\r\n                    {\r\n                        _remote.Shutdown(SocketShutdown.Both);\r\n                        _remote.Dispose();\r\n                    }\r\n                    catch (SocketException e)\r\n                    {\r\n                        logger.LogUsefulException(e);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/PrivoxyRunner.cs",
    "content": "﻿using System;\r\nusing System.Diagnostics;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Net;\r\nusing System.Net.Sockets;\r\nusing System.Text;\r\nusing System.Windows.Forms;\r\nusing NLog;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Properties;\r\nusing Shadowsocks.Util;\r\nusing Shadowsocks.Util.ProcessManagement;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    class PrivoxyRunner\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private static int _uid;\r\n        private static string _uniqueConfigFile;\r\n        private static Job _privoxyJob;\r\n        private Process _process;\r\n        private int _runningPort;\r\n\r\n        static PrivoxyRunner()\r\n        {\r\n            try\r\n            {\r\n                _uid = Program.WorkingDirectory.GetHashCode(); // Currently we use ss's StartupPath to identify different Privoxy instance.\r\n                _uniqueConfigFile = $\"privoxy_{_uid}.conf\";\r\n                _privoxyJob = new Job();\r\n\r\n                FileManager.UncompressFile(Utils.GetTempPath(\"ss_privoxy.exe\"), Resources.privoxy_exe);\r\n            }\r\n            catch (IOException e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n        }\r\n\r\n        public int RunningPort => _runningPort;\r\n\r\n        public void Start(Configuration configuration)\r\n        {\r\n            if (_process == null)\r\n            {\r\n                Process[] existingPrivoxy = Process.GetProcessesByName(\"ss_privoxy\");\r\n                foreach (Process p in existingPrivoxy.Where(IsChildProcess))\r\n                {\r\n                    KillProcess(p);\r\n                }\r\n                string privoxyConfig = Resources.privoxy_conf;\r\n                _runningPort = GetFreePort(configuration.isIPv6Enabled);\r\n                privoxyConfig = privoxyConfig.Replace(\"__SOCKS_PORT__\", configuration.localPort.ToString());\r\n                privoxyConfig = privoxyConfig.Replace(\"__PRIVOXY_BIND_PORT__\", _runningPort.ToString());\r\n                privoxyConfig = configuration.isIPv6Enabled\r\n                    ? privoxyConfig.Replace(\"__PRIVOXY_BIND_IP__\", configuration.shareOverLan ? \"[::]\" : \"[::1]\")\r\n                    .Replace(\"__SOCKS_HOST__\", \"[::1]\")\r\n                    : privoxyConfig.Replace(\"__PRIVOXY_BIND_IP__\", configuration.shareOverLan ? \"0.0.0.0\" : \"127.0.0.1\")\r\n                    .Replace(\"__SOCKS_HOST__\", \"127.0.0.1\");\r\n                FileManager.ByteArrayToFile(Utils.GetTempPath(_uniqueConfigFile), Encoding.UTF8.GetBytes(privoxyConfig));\r\n\r\n                _process = new Process\r\n                {\r\n                    // Configure the process using the StartInfo properties.\r\n                    StartInfo =\r\n                    {\r\n                        FileName = \"ss_privoxy.exe\",\r\n                        Arguments = _uniqueConfigFile,\r\n                        WorkingDirectory = Utils.GetTempPath(),\r\n                        WindowStyle = ProcessWindowStyle.Hidden,\r\n                        UseShellExecute = true,\r\n                        CreateNoWindow = true\r\n                    }\r\n                };\r\n                _process.Start();\r\n\r\n                /*\r\n                 * Add this process to job obj associated with this ss process, so that\r\n                 * when ss exit unexpectedly, this process will be forced killed by system.\r\n                 */\r\n                _privoxyJob.AddProcess(_process.Handle);\r\n            }\r\n        }\r\n\r\n        public void Stop()\r\n        {\r\n            if (_process != null)\r\n            {\r\n                KillProcess(_process);\r\n                _process.Dispose();\r\n                _process = null;\r\n            }\r\n        }\r\n\r\n        private static void KillProcess(Process p)\r\n        {\r\n            try\r\n            {\r\n                p.CloseMainWindow();\r\n                p.WaitForExit(100);\r\n                if (!p.HasExited)\r\n                {\r\n                    p.Kill();\r\n                    p.WaitForExit();\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n        }\r\n\r\n        /*\r\n         * We won't like to kill other ss instances' ss_privoxy.exe.\r\n         * This function will check whether the given process is created\r\n         * by this process by checking the module path or command line.\r\n         * \r\n         * Since it's required to put ss in different dirs to run muti instances,\r\n         * different instance will create their unique \"privoxy_UID.conf\" where\r\n         * UID is hash of ss's location.\r\n         */\r\n\r\n        private static bool IsChildProcess(Process process)\r\n        {\r\n            try\r\n            {\r\n                /*\r\n                 * Under PortableMode, we could identify it by the path of ss_privoxy.exe.\r\n                 */\r\n                var path = process.MainModule.FileName;\r\n\r\n                return Utils.GetTempPath(\"ss_privoxy.exe\").Equals(path);\r\n\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                /*\r\n                 * Sometimes Process.GetProcessesByName will return some processes that\r\n                 * are already dead, and that will cause exceptions here.\r\n                 * We could simply ignore those exceptions.\r\n                 */\r\n                logger.LogUsefulException(ex);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        private int GetFreePort(bool isIPv6 = false)\r\n        {\r\n            int defaultPort = 8123;\r\n            try\r\n            {\r\n                // TCP stack please do me a favor\r\n                TcpListener l = new TcpListener(isIPv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0);\r\n                l.Start();\r\n                var port = ((IPEndPoint)l.LocalEndpoint).Port;\r\n                l.Stop();\r\n                return port;\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                // in case access denied\r\n                logger.LogUsefulException(e);\r\n                return defaultPort;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/Sip003Plugin.cs",
    "content": "﻿using System;\r\nusing System.Collections.Specialized;\r\nusing System.Diagnostics;\r\nusing System.IO;\r\nusing System.Net;\r\nusing System.Net.Sockets;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Util.ProcessManagement;\r\n\r\nnamespace Shadowsocks.Controller.Service\r\n{\r\n    // https://github.com/shadowsocks/shadowsocks-org/wiki/Plugin\r\n    public sealed class Sip003Plugin : IDisposable\r\n    {\r\n        public IPEndPoint LocalEndPoint { get; private set; }\r\n        public int ProcessId => _started ? _pluginProcess.Id : 0;\r\n\r\n        private readonly object _startProcessLock = new object();\r\n        private readonly Job _pluginJob;\r\n        private readonly Process _pluginProcess;\r\n        private bool _started;\r\n        private bool _disposed;\r\n\r\n        public static Sip003Plugin CreateIfConfigured(Server server, bool showPluginOutput)\r\n        {\r\n            if (server == null)\r\n            {\r\n                throw new ArgumentNullException(nameof(server));\r\n            }\r\n\r\n            if (string.IsNullOrWhiteSpace(server.plugin))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return new Sip003Plugin(\r\n                server.plugin,\r\n                server.plugin_opts,\r\n                server.plugin_args,\r\n                server.server,\r\n                server.server_port,\r\n                showPluginOutput);\r\n        }\r\n\r\n        private Sip003Plugin(string plugin, string pluginOpts, string pluginArgs, string serverAddress, int serverPort, bool showPluginOutput)\r\n        {\r\n            if (plugin == null) throw new ArgumentNullException(nameof(plugin));\r\n            if (string.IsNullOrWhiteSpace(serverAddress))\r\n            {\r\n                throw new ArgumentException(\"Value cannot be null or whitespace.\", nameof(serverAddress));\r\n            }\r\n            if (serverPort <= 0 || serverPort > 65535)\r\n            {\r\n                throw new ArgumentOutOfRangeException(\"serverPort\");\r\n            }\r\n\r\n            _pluginProcess = new Process\r\n            {\r\n                StartInfo = new ProcessStartInfo\r\n                {\r\n                    FileName = plugin,\r\n                    Arguments = pluginArgs,\r\n                    UseShellExecute = false,\r\n                    CreateNoWindow = !showPluginOutput,\r\n                    ErrorDialog = false,\r\n                    WindowStyle = ProcessWindowStyle.Hidden,\r\n                    WorkingDirectory = Program.WorkingDirectory ?? Environment.CurrentDirectory,\r\n                    Environment =\r\n                    {\r\n                        [\"SS_REMOTE_HOST\"] = serverAddress,\r\n                        [\"SS_REMOTE_PORT\"] = serverPort.ToString(),\r\n                        [\"SS_PLUGIN_OPTIONS\"] = pluginOpts\r\n                    }\r\n                }\r\n            };\r\n\r\n            _pluginJob = new Job();\r\n        }\r\n\r\n        public bool StartIfNeeded()\r\n        {\r\n            if (_disposed)\r\n            {\r\n                throw new ObjectDisposedException(GetType().FullName);\r\n            }\r\n\r\n            lock (_startProcessLock)\r\n            {\r\n                if (_started && !_pluginProcess.HasExited)\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                var localPort = GetNextFreeTcpPort();\r\n                LocalEndPoint = new IPEndPoint(IPAddress.Loopback, localPort);\r\n\r\n                _pluginProcess.StartInfo.Environment[\"SS_LOCAL_HOST\"] = LocalEndPoint.Address.ToString();\r\n                _pluginProcess.StartInfo.Environment[\"SS_LOCAL_PORT\"] = LocalEndPoint.Port.ToString();\r\n                _pluginProcess.StartInfo.Arguments = ExpandEnvironmentVariables(_pluginProcess.StartInfo.Arguments, _pluginProcess.StartInfo.EnvironmentVariables);\r\n                try\r\n                {\r\n                    _pluginProcess.Start();\r\n                }\r\n                catch (System.ComponentModel.Win32Exception ex)\r\n                {\r\n                    // do not use File.Exists(...), it can not handle the scenarios when the plugin file is in system environment path.\r\n                    // https://docs.microsoft.com/en-us/windows/win32/seccrypto/common-hresult-values\r\n                    //if ((uint)ex.ErrorCode == 0x80004005)\r\n                    //  https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d\r\n                    if (ex.NativeErrorCode == 0x00000002)\r\n                    {\r\n                        throw new FileNotFoundException(I18N.GetString(\"Cannot find the plugin program file\"), _pluginProcess.StartInfo.FileName, ex);\r\n                    }\r\n                    throw new ApplicationException(I18N.GetString(\"Plugin Program\"), ex);\r\n                }\r\n                _pluginJob.AddProcess(_pluginProcess.Handle);\r\n                _started = true;\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        public string ExpandEnvironmentVariables(string name, StringDictionary environmentVariables = null)\r\n        {\r\n            // Expand the environment variables from the new process itself\r\n            if (environmentVariables != null)\r\n            {\r\n                foreach(string key in environmentVariables.Keys)\r\n                {\r\n                    name = name.Replace($\"%{key}%\", environmentVariables[key]);\r\n                }\r\n            }\r\n            // Also expand the environment variables from current main process (system)\r\n            name = Environment.ExpandEnvironmentVariables(name);\r\n            return name;\r\n        }\r\n\r\n        static int GetNextFreeTcpPort()\r\n        {\r\n            var l = new TcpListener(IPAddress.Loopback, 0);\r\n            l.Start();\r\n            int port = ((IPEndPoint)l.LocalEndpoint).Port;\r\n            l.Stop();\r\n            return port;\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            if (_disposed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                if (!_pluginProcess.HasExited)\r\n                {\r\n                    _pluginProcess.Kill();\r\n                    _pluginProcess.WaitForExit();\r\n                }\r\n            }\r\n            catch (Exception) { }\r\n            finally\r\n            {\r\n                try\r\n                {\r\n                    _pluginProcess.Dispose();\r\n                    _pluginJob.Dispose();\r\n                }\r\n                catch (Exception) { }\r\n\r\n                _disposed = true;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/TCPRelay.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Net;\r\nusing System.Net.Sockets;\r\nusing System.Timers;\r\n\r\nusing NLog;\r\n\r\nusing Shadowsocks.Controller.Strategy;\r\nusing Shadowsocks.Encryption;\r\nusing Shadowsocks.Encryption.AEAD;\r\nusing Shadowsocks.Encryption.Exception;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Proxy;\r\nusing Shadowsocks.Util.Sockets;\r\n\r\nusing static Shadowsocks.Encryption.EncryptorBase;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    internal class TCPRelay : Listener.Service\r\n    {\r\n        public event EventHandler<SSTCPConnectedEventArgs> OnConnected;\r\n        public event EventHandler<SSTransmitEventArgs> OnInbound;\r\n        public event EventHandler<SSTransmitEventArgs> OnOutbound;\r\n        public event EventHandler<SSRelayEventArgs> OnFailed;\r\n\r\n        private static readonly Logger logger = LogManager.GetCurrentClassLogger();\r\n        private readonly ShadowsocksController _controller;\r\n        private DateTime _lastSweepTime;\r\n        private readonly Configuration _config;\r\n\r\n        public ISet<TCPHandler> Handlers { get; set; }\r\n\r\n        public TCPRelay(ShadowsocksController controller, Configuration conf)\r\n        {\r\n            _controller = controller;\r\n            _config = conf;\r\n            Handlers = new HashSet<TCPHandler>();\r\n            _lastSweepTime = DateTime.Now;\r\n        }\r\n\r\n        public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)\r\n        {\r\n            if (socket.ProtocolType != ProtocolType.Tcp\r\n                || (length < 2 || firstPacket[0] != 5))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);\r\n            TCPHandler handler = new TCPHandler(_controller, _config, socket);\r\n\r\n            handler.OnConnected += OnConnected;\r\n            handler.OnInbound += OnInbound;\r\n            handler.OnOutbound += OnOutbound;\r\n            handler.OnFailed += OnFailed;\r\n            handler.OnClosed += (h, arg) =>\r\n            {\r\n                lock (Handlers)\r\n                {\r\n                    Handlers.Remove(handler);\r\n                }\r\n            };\r\n\r\n            IList<TCPHandler> handlersToClose = new List<TCPHandler>();\r\n            lock (Handlers)\r\n            {\r\n                Handlers.Add(handler);\r\n                DateTime now = DateTime.Now;\r\n                if (now - _lastSweepTime > TimeSpan.FromSeconds(1))\r\n                {\r\n                    _lastSweepTime = now;\r\n                    foreach (TCPHandler handler1 in Handlers)\r\n                    {\r\n                        if (now - handler1.lastActivity > TimeSpan.FromSeconds(900))\r\n                        {\r\n                            handlersToClose.Add(handler1);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            foreach (TCPHandler handler1 in handlersToClose)\r\n            {\r\n                logger.Debug(\"Closing timed out TCP connection.\");\r\n                handler1.Close();\r\n            }\r\n\r\n            /*\r\n             * Start after we put it into Handlers set. Otherwise if it failed in handler.Start()\r\n             * then it will call handler.Close() before we add it into the set.\r\n             * Then the handler will never release until the next Handle call. Sometimes it will\r\n             * cause odd problems (especially during memory profiling).\r\n             */\r\n            handler.Start(firstPacket, length);\r\n\r\n            return true;\r\n        }\r\n\r\n        public override void Stop()\r\n        {\r\n            List<TCPHandler> handlersToClose = new List<TCPHandler>();\r\n            lock (Handlers)\r\n            {\r\n                handlersToClose.AddRange(Handlers);\r\n            }\r\n            handlersToClose.ForEach(h => h.Close());\r\n        }\r\n    }\r\n\r\n    public class SSRelayEventArgs : EventArgs\r\n    {\r\n        public readonly Server server;\r\n\r\n        public SSRelayEventArgs(Server server)\r\n        {\r\n            this.server = server;\r\n        }\r\n    }\r\n\r\n    public class SSTransmitEventArgs : SSRelayEventArgs\r\n    {\r\n        public readonly long length;\r\n        public SSTransmitEventArgs(Server server, long length) : base(server)\r\n        {\r\n            this.length = length;\r\n        }\r\n    }\r\n\r\n    public class SSTCPConnectedEventArgs : SSRelayEventArgs\r\n    {\r\n        public readonly TimeSpan latency;\r\n\r\n        public SSTCPConnectedEventArgs(Server server, TimeSpan latency) : base(server)\r\n        {\r\n            this.latency = latency;\r\n        }\r\n    }\r\n\r\n    internal class TCPHandler\r\n    {\r\n        public event EventHandler<SSTCPConnectedEventArgs> OnConnected;\r\n        public event EventHandler<SSTransmitEventArgs> OnInbound;\r\n        public event EventHandler<SSTransmitEventArgs> OnOutbound;\r\n        public event EventHandler<SSRelayEventArgs> OnClosed;\r\n        public event EventHandler<SSRelayEventArgs> OnFailed;\r\n\r\n        private class AsyncSession\r\n        {\r\n            public IProxy Remote { get; }\r\n\r\n            public AsyncSession(IProxy remote)\r\n            {\r\n                Remote = remote;\r\n            }\r\n        }\r\n\r\n        private class AsyncSession<T> : AsyncSession\r\n        {\r\n            public T State { get; set; }\r\n\r\n            public AsyncSession(IProxy remote, T state) : base(remote)\r\n            {\r\n                State = state;\r\n            }\r\n\r\n            public AsyncSession(AsyncSession session, T state) : base(session.Remote)\r\n            {\r\n                State = state;\r\n            }\r\n        }\r\n\r\n        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private readonly int _serverTimeout;\r\n        private readonly int _proxyTimeout;\r\n\r\n        // each recv size.\r\n        public const int RecvSize = 2048;\r\n\r\n        // overhead of one chunk, reserved for AEAD ciphers\r\n        public const int ChunkOverheadSize = 16 * 2 /* two tags */ + AEADEncryptor.CHUNK_LEN_BYTES;\r\n\r\n        // max chunk size\r\n        public const uint MaxChunkSize = AEADEncryptor.CHUNK_LEN_MASK + AEADEncryptor.CHUNK_LEN_BYTES + 16 * 2;\r\n\r\n        // In general, the ciphertext length, we should take overhead into account\r\n        public const int BufferSize = RecvSize + (int)MaxChunkSize + 32 /* max salt len */;\r\n\r\n        public DateTime lastActivity;\r\n\r\n        private readonly ShadowsocksController _controller;\r\n        private readonly ForwardProxyConfig _config;\r\n        private readonly Socket _connection;\r\n\r\n        private IEncryptor _encryptor;\r\n        private Server _server;\r\n\r\n        private AsyncSession _currentRemoteSession;\r\n\r\n        private bool _proxyConnected;\r\n        private bool _destConnected;\r\n\r\n        private byte _command;\r\n        private byte[] _firstPacket;\r\n        private int _firstPacketLength;\r\n\r\n        private const int CMD_CONNECT = 0x01;\r\n        private const int CMD_BIND = 0x02;\r\n        private const int CMD_UDP_ASSOC = 0x03;\r\n\r\n        private int _addrBufLength = -1;\r\n\r\n        private int _totalRead = 0;\r\n        private int _totalWrite = 0;\r\n\r\n        // remote -> local proxy (ciphertext, before decrypt)\r\n        private readonly byte[] _remoteRecvBuffer = new byte[BufferSize];\r\n\r\n        // client -> local proxy (plaintext, before encrypt)\r\n        private readonly byte[] _connetionRecvBuffer = new byte[BufferSize];\r\n\r\n        // local proxy -> remote (plaintext, after decrypt)\r\n        private readonly byte[] _remoteSendBuffer = new byte[BufferSize];\r\n\r\n        // local proxy -> client (ciphertext, before decrypt)\r\n        private readonly byte[] _connetionSendBuffer = new byte[BufferSize];\r\n\r\n        private bool _connectionShutdown = false;\r\n        private bool _remoteShutdown = false;\r\n        private bool _closed = false;\r\n\r\n        // instance-based lock without static\r\n        private readonly object _encryptionLock = new object();\r\n\r\n        private readonly object _decryptionLock = new object();\r\n        private readonly object _closeConnLock = new object();\r\n\r\n        private DateTime _startConnectTime;\r\n        private DateTime _startReceivingTime;\r\n        private DateTime _startSendingTime;\r\n\r\n        private EndPoint _destEndPoint = null;\r\n\r\n        // TODO: decouple controller\r\n        public TCPHandler(ShadowsocksController controller, Configuration config, Socket socket)\r\n        {\r\n            _controller = controller;\r\n            _config = config.proxy;\r\n            _connection = socket;\r\n            _proxyTimeout = config.proxy.proxyTimeout * 1000;\r\n            _serverTimeout = config.GetCurrentServer().timeout * 1000;\r\n\r\n            lastActivity = DateTime.Now;\r\n        }\r\n\r\n        public void CreateRemote()\r\n        {\r\n            Server server = _controller.GetAServer(IStrategyCallerType.TCP, (IPEndPoint)_connection.RemoteEndPoint,\r\n                _destEndPoint);\r\n            if (server == null || server.server == \"\")\r\n            {\r\n                throw new ArgumentException(\"No server configured\");\r\n            }\r\n\r\n            _encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);\r\n\r\n            _server = server;\r\n\r\n            /* prepare address buffer length for AEAD */\r\n            Logger.Trace($\"_addrBufLength={_addrBufLength}\");\r\n            _encryptor.AddrBufLength = _addrBufLength;\r\n        }\r\n\r\n        public void Start(byte[] firstPacket, int length)\r\n        {\r\n            _firstPacket = firstPacket;\r\n            _firstPacketLength = length;\r\n            HandshakeReceive();\r\n        }\r\n\r\n        private void CheckClose()\r\n        {\r\n            if (_connectionShutdown && _remoteShutdown)\r\n            {\r\n                Close();\r\n            }\r\n        }\r\n\r\n        private void ErrorClose(Exception e)\r\n        {\r\n            Logger.LogUsefulException(e);\r\n            Close();\r\n        }\r\n\r\n        public void Close()\r\n        {\r\n            lock (_closeConnLock)\r\n            {\r\n                if (_closed)\r\n                {\r\n                    return;\r\n                }\r\n\r\n                _closed = true;\r\n            }\r\n\r\n            OnClosed?.Invoke(this, new SSRelayEventArgs(_server));\r\n\r\n            try\r\n            {\r\n                _connection.Shutdown(SocketShutdown.Both);\r\n                _connection.Close();\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                Logger.LogUsefulException(e);\r\n            }\r\n\r\n            if (_currentRemoteSession != null)\r\n            {\r\n                try\r\n                {\r\n                    IProxy remote = _currentRemoteSession.Remote;\r\n                    remote.Shutdown(SocketShutdown.Both);\r\n                    remote.Close();\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    Logger.LogUsefulException(e);\r\n                }\r\n            }\r\n\r\n            lock (_encryptionLock)\r\n            {\r\n                lock (_decryptionLock)\r\n                {\r\n                    _encryptor?.Dispose();\r\n                }\r\n            }\r\n        }\r\n\r\n        private void HandshakeReceive()\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                int bytesRead = _firstPacketLength;\r\n                if (bytesRead > 1)\r\n                {\r\n                    byte[] response = { 5, 0 };\r\n                    if (_firstPacket[0] != 5)\r\n                    {\r\n                        // reject socks 4\r\n                        response = new byte[] { 0, 91 };\r\n                        Logger.Error(\"socks 5 protocol error\");\r\n                    }\r\n                    _connection.BeginSend(response, 0, response.Length, SocketFlags.None,\r\n                        HandshakeSendCallback, null);\r\n                }\r\n                else\r\n                {\r\n                    Close();\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void HandshakeSendCallback(IAsyncResult ar)\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                _connection.EndSend(ar);\r\n\r\n                // +-----+-----+-------+------+----------+----------+\r\n                // | VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |\r\n                // +-----+-----+-------+------+----------+----------+\r\n                // |  1  |  1  | X'00' |  1   | Variable |    2     |\r\n                // +-----+-----+-------+------+----------+----------+\r\n                // Skip first 3 bytes, and read 2 more bytes to analysis the address.\r\n                // 2 more bytes is designed if address is domain then we don't need to read once more to get the addr length.\r\n                // validate is unnecessary, we did it in first packet, but we can do it in future version\r\n                _connection.BeginReceive(_connetionRecvBuffer, 0, 3 + ADDR_ATYP_LEN + 1, SocketFlags.None,\r\n                    AddressReceiveCallback, null);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void AddressReceiveCallback(IAsyncResult ar)\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                int bytesRead = _connection.EndReceive(ar);\r\n                if (bytesRead >= 5)\r\n                {\r\n                    _command = _connetionRecvBuffer[1];\r\n                    switch (_command)\r\n                    {\r\n                        case CMD_CONNECT:\r\n\r\n                            // +----+-----+-------+------+----------+----------+\r\n                            // |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |\r\n                            // +----+-----+-------+------+----------+----------+\r\n                            // | 1  |  1  | X'00' |  1   | Variable |    2     |\r\n                            // +----+-----+-------+------+----------+----------+\r\n                            byte[] response = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 };\r\n                            _connection.BeginSend(response, 0, response.Length, SocketFlags.None,\r\n                                ConnectResponseCallback, null);\r\n                            break;\r\n                        case CMD_UDP_ASSOC:\r\n                            ReadAddress(HandleUDPAssociate);\r\n                            break;\r\n                        case CMD_BIND:  // not implemented\r\n                        default:\r\n                            Logger.Debug(\"Unsupported CMD=\" + _command);\r\n                            Close();\r\n                            break;\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    Logger.Debug(\r\n                        \"failed to recv data in Shadowsocks.Controller.TCPHandler.handshakeReceive2Callback()\");\r\n                    Close();\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void ConnectResponseCallback(IAsyncResult ar)\r\n        {\r\n            try\r\n            {\r\n                _connection.EndSend(ar);\r\n\r\n                ReadAddress(StartConnect);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void ReadAddress(Action onSuccess)\r\n        {\r\n            int atyp = _connetionRecvBuffer[3];\r\n\r\n            switch (atyp)\r\n            {\r\n                case ATYP_IPv4: // IPv4 address, 4 bytes\r\n                    ReadAddress(4 + ADDR_PORT_LEN - 1, onSuccess);\r\n                    break;\r\n                case ATYP_DOMAIN: // domain name, length + str\r\n                    int len = _connetionRecvBuffer[4];\r\n                    ReadAddress(len + ADDR_PORT_LEN, onSuccess);\r\n                    break;\r\n                case ATYP_IPv6: // IPv6 address, 16 bytes\r\n                    ReadAddress(16 + ADDR_PORT_LEN - 1, onSuccess);\r\n                    break;\r\n                default:\r\n                    Logger.Debug(\"Unsupported ATYP=\" + atyp);\r\n                    Close();\r\n                    break;\r\n            }\r\n        }\r\n\r\n        private void ReadAddress(int bytesRemain, Action onSuccess)\r\n        {\r\n            // drop [ VER | CMD |  RSV  ]\r\n            Array.Copy(_connetionRecvBuffer, 3, _connetionRecvBuffer, 0, ADDR_ATYP_LEN + 1);\r\n\r\n            // Read the remain address bytes\r\n            _connection.BeginReceive(_connetionRecvBuffer, 2, RecvSize - 2, SocketFlags.None, OnAddressFullyRead,\r\n                new object[] { bytesRemain, onSuccess });\r\n        }\r\n\r\n        private void OnAddressFullyRead(IAsyncResult ar)\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                int bytesRead = _connection.EndReceive(ar);\r\n\r\n                object[] states = (object[])ar.AsyncState;\r\n\r\n                int bytesRemain = (int)states[0];\r\n                Action onSuccess = (Action)states[1];\r\n\r\n                if (bytesRead >= bytesRemain)\r\n                {\r\n                    _firstPacketLength = bytesRead + 2;\r\n\r\n                    int atyp = _connetionRecvBuffer[0];\r\n\r\n                    string dstAddr = \"Unknown\";\r\n                    int dstPort = -1;\r\n                    switch (atyp)\r\n                    {\r\n                        case ATYP_IPv4: // IPv4 address, 4 bytes\r\n                            dstAddr = new IPAddress(_connetionRecvBuffer.Skip(1).Take(4).ToArray()).ToString();\r\n                            dstPort = (_connetionRecvBuffer[5] << 8) + _connetionRecvBuffer[6];\r\n\r\n                            _addrBufLength = ADDR_ATYP_LEN + 4 + ADDR_PORT_LEN;\r\n                            break;\r\n                        case ATYP_DOMAIN: // domain name, length + str\r\n                            int len = _connetionRecvBuffer[1];\r\n                            dstAddr = System.Text.Encoding.UTF8.GetString(_connetionRecvBuffer, 2, len);\r\n                            dstPort = (_connetionRecvBuffer[len + 2] << 8) + _connetionRecvBuffer[len + 3];\r\n\r\n                            _addrBufLength = ADDR_ATYP_LEN + 1 + len + ADDR_PORT_LEN;\r\n                            break;\r\n                        case ATYP_IPv6: // IPv6 address, 16 bytes\r\n                            dstAddr = $\"[{new IPAddress(_connetionRecvBuffer.Skip(1).Take(16).ToArray())}]\";\r\n                            dstPort = (_connetionRecvBuffer[17] << 8) + _connetionRecvBuffer[18];\r\n\r\n                            _addrBufLength = ADDR_ATYP_LEN + 16 + ADDR_PORT_LEN;\r\n                            break;\r\n                    }\r\n\r\n                    Logger.Debug($\"connect to {dstAddr}:{dstPort}\");\r\n\r\n                    _destEndPoint = SocketUtil.GetEndPoint(dstAddr, dstPort);\r\n\r\n                    onSuccess.Invoke(); /* StartConnect() */\r\n                }\r\n                else\r\n                {\r\n                    Logger.Debug(\"failed to recv data in Shadowsocks.Controller.TCPHandler.OnAddressFullyRead()\");\r\n                    Close();\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void HandleUDPAssociate()\r\n        {\r\n            IPEndPoint endPoint = (IPEndPoint)_connection.LocalEndPoint;\r\n            byte[] address = endPoint.Address.GetAddressBytes();\r\n            int port = endPoint.Port;\r\n            byte[] response = new byte[4 + address.Length + ADDR_PORT_LEN];\r\n            response[0] = 5;\r\n            switch (endPoint.AddressFamily)\r\n            {\r\n                case AddressFamily.InterNetwork:\r\n                    response[3] = ATYP_IPv4;\r\n                    break;\r\n                case AddressFamily.InterNetworkV6:\r\n                    response[3] = ATYP_IPv6;\r\n                    break;\r\n            }\r\n            address.CopyTo(response, 4);\r\n            response[response.Length - 1] = (byte)(port & 0xFF);\r\n            response[response.Length - 2] = (byte)((port >> 8) & 0xFF);\r\n            _connection.BeginSend(response, 0, response.Length, SocketFlags.None, ReadAll, true);\r\n        }\r\n\r\n        private void ReadAll(IAsyncResult ar)\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                if (ar.AsyncState != null)\r\n                {\r\n                    _connection.EndSend(ar);\r\n                    _connection.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None,\r\n                        ReadAll, null);\r\n                }\r\n                else\r\n                {\r\n                    int bytesRead = _connection.EndReceive(ar);\r\n                    if (bytesRead > 0)\r\n                    {\r\n                        _connection.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None,\r\n                            ReadAll, null);\r\n                    }\r\n                    else\r\n                    {\r\n                        Close();\r\n                    }\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        // inner class\r\n        private class ProxyTimer : Timer\r\n        {\r\n            public AsyncSession Session;\r\n\r\n            public EndPoint DestEndPoint;\r\n            public Server Server;\r\n\r\n            public ProxyTimer(int p) : base(p)\r\n            {\r\n            }\r\n        }\r\n\r\n        private class ServerTimer : Timer\r\n        {\r\n            public AsyncSession Session;\r\n\r\n            public Server Server;\r\n\r\n            public ServerTimer(int p) : base(p)\r\n            {\r\n            }\r\n        }\r\n\r\n        private void StartConnect()\r\n        {\r\n            try\r\n            {\r\n                CreateRemote();\r\n\r\n                // Setting up proxy\r\n                IProxy remote;\r\n                EndPoint proxyEP = null;\r\n                EndPoint serverEP = SocketUtil.GetEndPoint(_server.server, _server.server_port);\r\n                EndPoint pluginEP = _controller.GetPluginLocalEndPointIfConfigured(_server);\r\n\r\n                if (pluginEP != null)\r\n                {\r\n                    serverEP = pluginEP;\r\n                    remote = new DirectConnect();\r\n                }\r\n                else if (_config.useProxy)\r\n                {\r\n                    switch (_config.proxyType)\r\n                    {\r\n                        case ForwardProxyConfig.PROXY_SOCKS5:\r\n                            remote = new Socks5Proxy();\r\n                            break;\r\n                        case ForwardProxyConfig.PROXY_HTTP:\r\n                            remote = new HttpProxy();\r\n                            break;\r\n                        default:\r\n                            throw new NotSupportedException(\"Unknown forward proxy.\");\r\n                    }\r\n                    proxyEP = SocketUtil.GetEndPoint(_config.proxyServer, _config.proxyPort);\r\n                }\r\n                else\r\n                {\r\n                    remote = new DirectConnect();\r\n                }\r\n\r\n                AsyncSession session = new AsyncSession(remote);\r\n                lock (_closeConnLock)\r\n                {\r\n                    if (_closed)\r\n                    {\r\n                        remote.Close();\r\n                        return;\r\n                    }\r\n\r\n                    _currentRemoteSession = session;\r\n                }\r\n\r\n                ProxyTimer proxyTimer = new ProxyTimer(_proxyTimeout) { AutoReset = false };\r\n                proxyTimer.Elapsed += ProxyConnectTimer_Elapsed;\r\n                proxyTimer.Enabled = true;\r\n\r\n                proxyTimer.Session = session;\r\n                proxyTimer.DestEndPoint = serverEP;\r\n                proxyTimer.Server = _server;\r\n\r\n                _proxyConnected = false;\r\n\r\n                // Connect to the proxy server.\r\n                remote.BeginConnectProxy(proxyEP, ProxyConnectCallback,\r\n                    new AsyncSession<ProxyTimer>(remote, proxyTimer));\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void ProxyConnectTimer_Elapsed(object sender, ElapsedEventArgs e)\r\n        {\r\n            ProxyTimer timer = (ProxyTimer)sender;\r\n            timer.Elapsed -= ProxyConnectTimer_Elapsed;\r\n            timer.Enabled = false;\r\n            timer.Dispose();\r\n\r\n\r\n            if (_proxyConnected || _destConnected || _closed)\r\n            {\r\n                return;\r\n            }\r\n            IProxy proxy = timer.Session.Remote;\r\n\r\n            Logger.Info($\"Proxy {proxy.ProxyEndPoint} timed out\");\r\n            proxy.Close();\r\n            Close();\r\n        }\r\n\r\n        private void ProxyConnectCallback(IAsyncResult ar)\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n            try\r\n            {\r\n                AsyncSession<ProxyTimer> session = (AsyncSession<ProxyTimer>)ar.AsyncState;\r\n                ProxyTimer timer = session.State;\r\n                EndPoint destEndPoint = timer.DestEndPoint;\r\n                Server server = timer.Server;\r\n                timer.Elapsed -= ProxyConnectTimer_Elapsed;\r\n                timer.Enabled = false;\r\n                timer.Dispose();\r\n\r\n                IProxy remote = session.Remote;\r\n\r\n                // Complete the connection.\r\n                remote.EndConnectProxy(ar);\r\n\r\n                _proxyConnected = true;\r\n\r\n                if (!(remote is DirectConnect))\r\n                {\r\n                    Logger.Debug($\"Socket connected to proxy {remote.ProxyEndPoint}\");\r\n                }\r\n\r\n                _startConnectTime = DateTime.Now;\r\n                ServerTimer connectTimer = new ServerTimer(_serverTimeout) { AutoReset = false };\r\n                connectTimer.Elapsed += DestConnectTimer_Elapsed;\r\n                connectTimer.Enabled = true;\r\n                connectTimer.Session = session;\r\n                connectTimer.Server = server;\r\n\r\n                _destConnected = false;\r\n\r\n                NetworkCredential auth = null;\r\n                if (_config.useAuth)\r\n                {\r\n                    auth = new NetworkCredential(_config.authUser, _config.authPwd);\r\n                }\r\n\r\n                // Connect to the remote endpoint.\r\n                remote.BeginConnectDest(destEndPoint, ConnectCallback,\r\n                    new AsyncSession<ServerTimer>(session, connectTimer), auth);\r\n            }\r\n            catch (ArgumentException)\r\n            {\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void DestConnectTimer_Elapsed(object sender, ElapsedEventArgs e)\r\n        {\r\n            ServerTimer timer = (ServerTimer)sender;\r\n            timer.Elapsed -= DestConnectTimer_Elapsed;\r\n            timer.Enabled = false;\r\n            timer.Dispose();\r\n\r\n            if (_destConnected || _closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            AsyncSession session = timer.Session;\r\n            Server server = timer.Server;\r\n            OnFailed?.Invoke(this, new SSRelayEventArgs(_server));\r\n            Logger.Info($\"{server.ToString()} timed out\");\r\n            session.Remote.Close();\r\n            Close();\r\n        }\r\n\r\n        private void ConnectCallback(IAsyncResult ar)\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                AsyncSession<ServerTimer> session = (AsyncSession<ServerTimer>)ar.AsyncState;\r\n                ServerTimer timer = session.State;\r\n                _server = timer.Server;\r\n                timer.Elapsed -= DestConnectTimer_Elapsed;\r\n                timer.Enabled = false;\r\n                timer.Dispose();\r\n\r\n                IProxy remote = session.Remote;\r\n                // Complete the connection.\r\n                remote.EndConnectDest(ar);\r\n\r\n                _destConnected = true;\r\n\r\n                Logger.Debug($\"Socket connected to ss server: {_server.ToString()}\");\r\n\r\n                TimeSpan latency = DateTime.Now - _startConnectTime;\r\n\r\n                OnConnected?.Invoke(this, new SSTCPConnectedEventArgs(_server, latency));\r\n\r\n                StartPipe(session);\r\n            }\r\n            catch (ArgumentException)\r\n            {\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                if (_server != null)\r\n                {\r\n                    OnFailed?.Invoke(this, new SSRelayEventArgs(_server));\r\n                }\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void TryReadAvailableData()\r\n        {\r\n            int available = Math.Min(_connection.Available, RecvSize - _firstPacketLength);\r\n            if (available > 0)\r\n            {\r\n                int size = _connection.Receive(_connetionRecvBuffer, _firstPacketLength, available,\r\n                    SocketFlags.None);\r\n\r\n                _firstPacketLength += size;\r\n            }\r\n        }\r\n\r\n        private void StartPipe(AsyncSession session)\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                _startReceivingTime = DateTime.Now;\r\n                session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None,\r\n                    PipeRemoteReceiveCallback, session);\r\n\r\n                TryReadAvailableData();\r\n                Logger.Trace($\"_firstPacketLength = {_firstPacketLength}\");\r\n                SendToServer(_firstPacketLength, session);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void PipeRemoteReceiveCallback(IAsyncResult ar)\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                AsyncSession session = (AsyncSession)ar.AsyncState;\r\n                int bytesRead = session.Remote.EndReceive(ar);\r\n                _totalRead += bytesRead;\r\n\r\n                OnInbound?.Invoke(this, new SSTransmitEventArgs(_server, bytesRead));\r\n                if (bytesRead > 0)\r\n                {\r\n                    lastActivity = DateTime.Now;\r\n                    int bytesToSend = -1;\r\n                    lock (_decryptionLock)\r\n                    {\r\n                        try\r\n                        {\r\n                            _encryptor.Decrypt(_remoteRecvBuffer, bytesRead, _remoteSendBuffer, out bytesToSend);\r\n                        }\r\n                        catch (CryptoErrorException)\r\n                        {\r\n                            Logger.Error(\"decryption error\");\r\n                            Close();\r\n                            return;\r\n                        }\r\n                    }\r\n                    if (bytesToSend == 0)\r\n                    {\r\n                        // need more to decrypt\r\n                        Logger.Trace(\"Need more to decrypt\");\r\n                        session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None,\r\n                            PipeRemoteReceiveCallback, session);\r\n                        return;\r\n                    }\r\n                    Logger.Trace($\"start sending {bytesToSend}\");\r\n                    _connection.BeginSend(_remoteSendBuffer, 0, bytesToSend, SocketFlags.None,\r\n                        PipeConnectionSendCallback, new object[] { session, bytesToSend });\r\n                }\r\n                else\r\n                {\r\n                    _connection.Shutdown(SocketShutdown.Send);\r\n                    _connectionShutdown = true;\r\n                    CheckClose();\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void PipeConnectionReceiveCallback(IAsyncResult ar)\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                int bytesRead = _connection.EndReceive(ar);\r\n\r\n                AsyncSession session = (AsyncSession)ar.AsyncState;\r\n                IProxy remote = session.Remote;\r\n\r\n                if (bytesRead > 0)\r\n                {\r\n                    SendToServer(bytesRead, session);\r\n                }\r\n                else\r\n                {\r\n                    remote.Shutdown(SocketShutdown.Send);\r\n                    _remoteShutdown = true;\r\n                    CheckClose();\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        private void SendToServer(int length, AsyncSession session)\r\n        {\r\n            _totalWrite += length;\r\n            int bytesToSend;\r\n            lock (_encryptionLock)\r\n            {\r\n                try\r\n                {\r\n                    _encryptor.Encrypt(_connetionRecvBuffer, length, _connetionSendBuffer, out bytesToSend);\r\n                }\r\n                catch (CryptoErrorException)\r\n                {\r\n                    Logger.Debug(\"encryption error\");\r\n                    Close();\r\n                    return;\r\n                }\r\n            }\r\n\r\n            OnOutbound?.Invoke(this, new SSTransmitEventArgs(_server, bytesToSend));\r\n            _startSendingTime = DateTime.Now;\r\n            session.Remote.BeginSend(_connetionSendBuffer, 0, bytesToSend, SocketFlags.None,\r\n                PipeRemoteSendCallback, new object[] { session, bytesToSend });\r\n        }\r\n\r\n        private void PipeRemoteSendCallback(IAsyncResult ar)\r\n        {\r\n            if (_closed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                object[] container = (object[])ar.AsyncState;\r\n                AsyncSession session = (AsyncSession)container[0];\r\n                int bytesShouldSend = (int)container[1];\r\n                int bytesSent = session.Remote.EndSend(ar);\r\n\r\n                if (bytesSent > 0)\r\n                {\r\n                    lastActivity = DateTime.Now;\r\n                }\r\n\r\n                int bytesRemaining = bytesShouldSend - bytesSent;\r\n                if (bytesRemaining > 0)\r\n                {\r\n                    Logger.Info(\"reconstruct _connetionSendBuffer to re-send\");\r\n                    Buffer.BlockCopy(_connetionSendBuffer, bytesSent, _connetionSendBuffer, 0, bytesRemaining);\r\n                    session.Remote.BeginSend(_connetionSendBuffer, 0, bytesRemaining, SocketFlags.None,\r\n                        PipeRemoteSendCallback, new object[] { session, bytesRemaining });\r\n                    return;\r\n                }\r\n                _connection.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None,\r\n                    PipeConnectionReceiveCallback, session);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n\r\n        // In general, we assume there is no delay between local proxy and client, add this for sanity\r\n        private void PipeConnectionSendCallback(IAsyncResult ar)\r\n        {\r\n            try\r\n            {\r\n                object[] container = (object[])ar.AsyncState;\r\n                AsyncSession session = (AsyncSession)container[0];\r\n                int bytesShouldSend = (int)container[1];\r\n                int bytesSent = _connection.EndSend(ar);\r\n                int bytesRemaining = bytesShouldSend - bytesSent;\r\n                if (bytesRemaining > 0)\r\n                {\r\n                    Logger.Info(\"reconstruct _remoteSendBuffer to re-send\");\r\n                    Buffer.BlockCopy(_remoteSendBuffer, bytesSent, _remoteSendBuffer, 0, bytesRemaining);\r\n                    _connection.BeginSend(_remoteSendBuffer, 0, bytesRemaining, SocketFlags.None,\r\n                        PipeConnectionSendCallback, new object[] { session, bytesRemaining });\r\n                    return;\r\n                }\r\n                session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None,\r\n                    PipeRemoteReceiveCallback, session);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                ErrorClose(e);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/UDPRelay.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.Net;\r\nusing System.Net.Sockets;\r\nusing System.Runtime.CompilerServices;\r\nusing NLog;\r\nusing Shadowsocks.Controller.Strategy;\r\nusing Shadowsocks.Encryption;\r\nusing Shadowsocks.Model;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    class UDPRelay : Listener.Service\r\n    {\r\n        private ShadowsocksController _controller;\r\n\r\n        // TODO: choose a smart number\r\n        private LRUCache<IPEndPoint, UDPHandler> _cache = new LRUCache<IPEndPoint, UDPHandler>(512);\r\n\r\n        public long outbound = 0;\r\n        public long inbound = 0;\r\n\r\n        public UDPRelay(ShadowsocksController controller)\r\n        {\r\n            this._controller = controller;\r\n        }\r\n\r\n        public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)\r\n        {\r\n            if (socket.ProtocolType != ProtocolType.Udp)\r\n            {\r\n                return false;\r\n            }\r\n            if (length < 4)\r\n            {\r\n                return false;\r\n            }\r\n            Listener.UDPState udpState = (Listener.UDPState)state;\r\n            IPEndPoint remoteEndPoint = (IPEndPoint)udpState.remoteEndPoint;\r\n            UDPHandler handler = _cache.get(remoteEndPoint);\r\n            if (handler == null)\r\n            {\r\n                handler = new UDPHandler(socket, _controller.GetAServer(IStrategyCallerType.UDP, remoteEndPoint, null/*TODO: fix this*/), remoteEndPoint);\r\n                handler.Receive();\r\n                _cache.add(remoteEndPoint, handler);\r\n            }\r\n            handler.Send(firstPacket, length);\r\n            return true;\r\n        }\r\n\r\n        public class UDPHandler\r\n        {\r\n            private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n            private Socket _local;\r\n            private Socket _remote;\r\n\r\n            private Server _server;\r\n            private byte[] _buffer = new byte[65536];\r\n\r\n            private IPEndPoint _localEndPoint;\r\n            private IPEndPoint _remoteEndPoint;\r\n\r\n            private IPAddress GetIPAddress()\r\n            {\r\n                switch (_remote.AddressFamily)\r\n                {\r\n                    case AddressFamily.InterNetwork:\r\n                        return IPAddress.Any;\r\n                    case AddressFamily.InterNetworkV6:\r\n                        return IPAddress.IPv6Any;\r\n                    default:\r\n                        return IPAddress.Any;\r\n                }\r\n            }\r\n\r\n            public UDPHandler(Socket local, Server server, IPEndPoint localEndPoint)\r\n            {\r\n                _local = local;\r\n                _server = server;\r\n                _localEndPoint = localEndPoint;\r\n\r\n                // TODO async resolving\r\n                IPAddress ipAddress;\r\n                bool parsed = IPAddress.TryParse(server.server, out ipAddress);\r\n                if (!parsed)\r\n                {\r\n                    IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server);\r\n                    ipAddress = ipHostInfo.AddressList[0];\r\n                }\r\n                _remoteEndPoint = new IPEndPoint(ipAddress, server.server_port);\r\n                _remote = new Socket(_remoteEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);\r\n                _remote.Bind(new IPEndPoint(GetIPAddress(), 0));\r\n            }\r\n\r\n            public void Send(byte[] data, int length)\r\n            {\r\n                IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);\r\n                byte[] dataIn = new byte[length - 3];\r\n                Array.Copy(data, 3, dataIn, 0, length - 3);\r\n                byte[] dataOut = new byte[65536];  // enough space for AEAD ciphers\r\n                int outlen;\r\n                encryptor.EncryptUDP(dataIn, length - 3, dataOut, out outlen);\r\n                logger.Debug(_localEndPoint, _remoteEndPoint, outlen, \"UDP Relay\");\r\n                _remote?.SendTo(dataOut, outlen, SocketFlags.None, _remoteEndPoint);\r\n            }\r\n\r\n            public void Receive()\r\n            {\r\n                EndPoint remoteEndPoint = new IPEndPoint(GetIPAddress(), 0);\r\n                logger.Debug($\"++++++Receive Server Port, size:\" + _buffer.Length);\r\n                _remote?.BeginReceiveFrom(_buffer, 0, _buffer.Length, 0, ref remoteEndPoint, new AsyncCallback(RecvFromCallback), null);\r\n            }\r\n\r\n            public void RecvFromCallback(IAsyncResult ar)\r\n            {\r\n                try\r\n                {\r\n                    if (_remote == null) return;\r\n                    EndPoint remoteEndPoint = new IPEndPoint(GetIPAddress(), 0);\r\n                    int bytesRead = _remote.EndReceiveFrom(ar, ref remoteEndPoint);\r\n\r\n                    byte[] dataOut = new byte[bytesRead];\r\n                    int outlen;\r\n\r\n                    IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);\r\n                    encryptor.DecryptUDP(_buffer, bytesRead, dataOut, out outlen);\r\n\r\n                    byte[] sendBuf = new byte[outlen + 3];\r\n                    Array.Copy(dataOut, 0, sendBuf, 3, outlen);\r\n\r\n                    logger.Debug(_localEndPoint, _remoteEndPoint, outlen, \"UDP Relay\");\r\n                    _local?.SendTo(sendBuf, outlen + 3, 0, _localEndPoint);\r\n\r\n                    Receive();\r\n                }\r\n                catch (ObjectDisposedException)\r\n                {\r\n                    // TODO: handle the ObjectDisposedException\r\n                }\r\n                catch (Exception)\r\n                {\r\n                    // TODO: need more think about handle other Exceptions, or should remove this catch().\r\n                }\r\n                finally\r\n                {\r\n                    // No matter success or failed, we keep receiving\r\n\r\n                }\r\n            }\r\n\r\n            public void Close()\r\n            {\r\n                try\r\n                {\r\n                    _remote?.Close();\r\n                }\r\n                catch (ObjectDisposedException)\r\n                {\r\n                    // TODO: handle the ObjectDisposedException\r\n                }\r\n                catch (Exception)\r\n                {\r\n                    // TODO: need more think about handle other Exceptions, or should remove this catch().\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    #region LRU cache\r\n\r\n    // cc by-sa 3.0 http://stackoverflow.com/a/3719378/1124054\r\n    class LRUCache<K, V> where V : UDPRelay.UDPHandler\r\n    {\r\n        private int capacity;\r\n        private Dictionary<K, LinkedListNode<LRUCacheItem<K, V>>> cacheMap = new Dictionary<K, LinkedListNode<LRUCacheItem<K, V>>>();\r\n        private LinkedList<LRUCacheItem<K, V>> lruList = new LinkedList<LRUCacheItem<K, V>>();\r\n\r\n        public LRUCache(int capacity)\r\n        {\r\n            this.capacity = capacity;\r\n        }\r\n\r\n        [MethodImpl(MethodImplOptions.Synchronized)]\r\n        public V get(K key)\r\n        {\r\n            LinkedListNode<LRUCacheItem<K, V>> node;\r\n            if (cacheMap.TryGetValue(key, out node))\r\n            {\r\n                V value = node.Value.value;\r\n                lruList.Remove(node);\r\n                lruList.AddLast(node);\r\n                return value;\r\n            }\r\n            return default(V);\r\n        }\r\n\r\n        [MethodImpl(MethodImplOptions.Synchronized)]\r\n        public void add(K key, V val)\r\n        {\r\n            if (cacheMap.Count >= capacity)\r\n            {\r\n                RemoveFirst();\r\n            }\r\n\r\n            LRUCacheItem<K, V> cacheItem = new LRUCacheItem<K, V>(key, val);\r\n            LinkedListNode<LRUCacheItem<K, V>> node = new LinkedListNode<LRUCacheItem<K, V>>(cacheItem);\r\n            lruList.AddLast(node);\r\n            cacheMap.Add(key, node);\r\n        }\r\n\r\n        private void RemoveFirst()\r\n        {\r\n            // Remove from LRUPriority\r\n            LinkedListNode<LRUCacheItem<K, V>> node = lruList.First;\r\n            lruList.RemoveFirst();\r\n\r\n            // Remove from cache\r\n            cacheMap.Remove(node.Value.key);\r\n            node.Value.value.Close();\r\n        }\r\n    }\r\n\r\n    class LRUCacheItem<K, V>\r\n    {\r\n        public LRUCacheItem(K k, V v)\r\n        {\r\n            key = k;\r\n            value = v;\r\n        }\r\n        public K key;\r\n        public V value;\r\n    }\r\n\r\n    #endregion\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Service/UpdateChecker.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics;\r\nusing System.IO;\r\nusing System.Net;\r\nusing System.Net.Http;\r\nusing System.Text.RegularExpressions;\r\nusing System.Threading.Tasks;\r\nusing System.Windows;\r\nusing Newtonsoft.Json.Linq;\r\nusing NLog;\r\nusing Shadowsocks.Localization;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Util;\r\nusing Shadowsocks.Views;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    public class UpdateChecker\r\n    {\r\n        private readonly Logger logger;\r\n        private readonly HttpClient httpClient;\r\n\r\n        // https://developer.github.com/v3/repos/releases/\r\n        private const string UpdateURL = \"https://api.github.com/repos/shadowsocks/shadowsocks-windows/releases\";\r\n\r\n        private Configuration _config;\r\n        private Window versionUpdatePromptWindow;\r\n        private JToken _releaseObject;\r\n\r\n        public string NewReleaseVersion { get; private set; }\r\n        public string NewReleaseZipFilename { get; private set; }\r\n\r\n        public event EventHandler CheckUpdateCompleted;\r\n\r\n        public const string Version = \"4.4.1.0\";\r\n        private readonly Version _version;\r\n\r\n        public UpdateChecker()\r\n        {\r\n            logger = LogManager.GetCurrentClassLogger();\r\n            httpClient = Program.MainController.GetHttpClient();\r\n            _version = new Version(Version);\r\n            _config = Program.MainController.GetCurrentConfiguration();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Checks for updates and asks the user if updates are found.\r\n        /// </summary>\r\n        /// <param name=\"millisecondsDelay\">A delay in milliseconds before checking.</param>\r\n        /// <returns></returns>\r\n        public async Task CheckForVersionUpdate(int millisecondsDelay = 0)\r\n        {\r\n            // delay\r\n            logger.Info($\"Waiting for {millisecondsDelay}ms before checking for version update.\");\r\n            await Task.Delay(millisecondsDelay);\r\n            // update _config so we would know if the user checked or unchecked pre-release checks\r\n            _config = Program.MainController.GetCurrentConfiguration();\r\n            // start\r\n            logger.Info($\"Checking for version update.\");\r\n            try\r\n            {\r\n                // list releases via API\r\n                var releasesListJsonString = await httpClient.GetStringAsync(UpdateURL);\r\n                // parse\r\n                var releasesJArray = JArray.Parse(releasesListJsonString);\r\n                foreach (var releaseObject in releasesJArray)\r\n                {\r\n                    var releaseTagName = (string)releaseObject[\"tag_name\"];\r\n                    var releaseVersion = new Version(releaseTagName);\r\n                    if (releaseTagName == _config.skippedUpdateVersion) // finished checking\r\n                        break;\r\n                    if (releaseVersion.CompareTo(_version) > 0 &&\r\n                        (!(bool)releaseObject[\"prerelease\"] || _config.checkPreRelease && (bool)releaseObject[\"prerelease\"])) // selected\r\n                    {\r\n                        logger.Info($\"Found new version {releaseTagName}.\");\r\n                        _releaseObject = releaseObject;\r\n                        NewReleaseVersion = releaseTagName;\r\n                        AskToUpdate(releaseObject);\r\n                        return;\r\n                    }\r\n                }\r\n                logger.Info($\"No new versions found.\");\r\n                CheckUpdateCompleted?.Invoke(this, new EventArgs());\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Opens a window to show the update's information.\r\n        /// </summary>\r\n        /// <param name=\"releaseObject\">The update release object.</param>\r\n        private void AskToUpdate(JToken releaseObject)\r\n        {\r\n            if (versionUpdatePromptWindow == null)\r\n            {\r\n                versionUpdatePromptWindow = new Window()\r\n                {\r\n                    Title = LocalizationProvider.GetLocalizedValue<string>(\"VersionUpdate\"),\r\n                    Height = 480,\r\n                    Width = 640,\r\n                    MinHeight = 480,\r\n                    MinWidth = 640,\r\n                    Content = new VersionUpdatePromptView(releaseObject)\r\n                };\r\n                versionUpdatePromptWindow.Closed += VersionUpdatePromptWindow_Closed;\r\n                versionUpdatePromptWindow.Show();\r\n            }\r\n            versionUpdatePromptWindow.Activate();\r\n        }\r\n\r\n        private void VersionUpdatePromptWindow_Closed(object sender, EventArgs e)\r\n        {\r\n            versionUpdatePromptWindow = null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Downloads the selected update and notifies the user.\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        public async Task DoUpdate()\r\n        {\r\n            try\r\n            {\r\n                var assets = (JArray)_releaseObject[\"assets\"];\r\n                // download all assets\r\n                foreach (JObject asset in assets)\r\n                {\r\n                    var filename = (string)asset[\"name\"];\r\n                    var browser_download_url = (string)asset[\"browser_download_url\"];\r\n                    var response = await httpClient.GetAsync(browser_download_url);\r\n                    using (var downloadedFileStream = File.Create(Utils.GetTempPath(filename)))\r\n                        await response.Content.CopyToAsync(downloadedFileStream);\r\n                    logger.Info($\"Downloaded {filename}.\");\r\n                    // store .zip filename\r\n                    if (filename.EndsWith(\".zip\"))\r\n                        NewReleaseZipFilename = filename;\r\n                }\r\n                logger.Info(\"Finished downloading.\");\r\n                // notify user\r\n                CloseVersionUpdatePromptWindow();\r\n                Process.Start(\"explorer.exe\", $\"/select, \\\"{Utils.GetTempPath(NewReleaseZipFilename)}\\\"\");\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Saves the skipped update version.\r\n        /// </summary>\r\n        public void SkipUpdate()\r\n        {\r\n            var version = (string)_releaseObject[\"tag_name\"] ?? \"\";\r\n            _config.skippedUpdateVersion = version;\r\n            Program.MainController.SaveSkippedUpdateVerion(version);\r\n            logger.Info($\"The update {version} has been skipped and will be ignored next time.\");\r\n            CloseVersionUpdatePromptWindow();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Closes the update prompt window.\r\n        /// </summary>\r\n        public void CloseVersionUpdatePromptWindow()\r\n        {\r\n            if (versionUpdatePromptWindow != null)\r\n            {\r\n                versionUpdatePromptWindow.Close();\r\n                versionUpdatePromptWindow = null;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/ShadowsocksController.cs",
    "content": "﻿using System;\r\nusing System.Collections.Concurrent;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Net;\r\nusing System.Net.Http;\r\nusing System.Net.Sockets;\r\nusing System.Text;\r\nusing System.Threading;\r\nusing System.Threading.Tasks;\r\nusing System.Web;\r\nusing System.Windows.Forms;\r\nusing NLog;\r\nusing Shadowsocks.Controller.Service;\r\nusing Shadowsocks.Controller.Strategy;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Util;\r\nusing WPFLocalizeExtension.Engine;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    public class ShadowsocksController\r\n    {\r\n        private readonly Logger logger;\r\n        private readonly HttpClient httpClient;\r\n\r\n        // controller:\r\n        // handle user actions\r\n        // manipulates UI\r\n        // interacts with low level logic\r\n        #region Members definition\r\n        private Thread _trafficThread;\r\n\r\n        private Listener _listener;\r\n        private PACDaemon _pacDaemon;\r\n        private PACServer _pacServer;\r\n        private Configuration _config;\r\n        private StrategyManager _strategyManager;\r\n        private PrivoxyRunner privoxyRunner;\r\n        private readonly ConcurrentDictionary<Server, Sip003Plugin> _pluginsByServer;\r\n\r\n        private long _inboundCounter = 0;\r\n        private long _outboundCounter = 0;\r\n        public long InboundCounter => Interlocked.Read(ref _inboundCounter);\r\n        public long OutboundCounter => Interlocked.Read(ref _outboundCounter);\r\n        public Queue<TrafficPerSecond> trafficPerSecondQueue;\r\n\r\n        private bool stopped = false;\r\n\r\n        public class PathEventArgs : EventArgs\r\n        {\r\n            public string Path;\r\n        }\r\n\r\n        public class UpdatedEventArgs : EventArgs\r\n        {\r\n            public string OldVersion;\r\n            public string NewVersion;\r\n        }\r\n\r\n        public class TrafficPerSecond\r\n        {\r\n            public long inboundCounter;\r\n            public long outboundCounter;\r\n            public long inboundIncreasement;\r\n            public long outboundIncreasement;\r\n        }\r\n\r\n        public event EventHandler ConfigChanged;\r\n        public event EventHandler EnableStatusChanged;\r\n        public event EventHandler EnableGlobalChanged;\r\n        public event EventHandler ShareOverLANStatusChanged;\r\n        public event EventHandler VerboseLoggingStatusChanged;\r\n        public event EventHandler ShowPluginOutputChanged;\r\n        public event EventHandler TrafficChanged;\r\n\r\n        // when user clicked Edit PAC, and PAC file has already created\r\n        public event EventHandler<PathEventArgs> PACFileReadyToOpen;\r\n        public event EventHandler<PathEventArgs> UserRuleFileReadyToOpen;\r\n\r\n        public event EventHandler<GeositeResultEventArgs> UpdatePACFromGeositeCompleted;\r\n\r\n        public event ErrorEventHandler UpdatePACFromGeositeError;\r\n\r\n        public event ErrorEventHandler Errored;\r\n\r\n        // Invoked when controller.Start();\r\n        public event EventHandler<UpdatedEventArgs> ProgramUpdated;\r\n        #endregion\r\n\r\n        public ShadowsocksController()\r\n        {\r\n            logger = LogManager.GetCurrentClassLogger();\r\n            httpClient = new HttpClient();\r\n            _config = Configuration.Load();\r\n            Configuration.Process(ref _config);\r\n            _strategyManager = new StrategyManager(this);\r\n            _pluginsByServer = new ConcurrentDictionary<Server, Sip003Plugin>();\r\n            StartTrafficStatistics(61);\r\n\r\n            ProgramUpdated += (o, e) =>\r\n            {\r\n                // version update precedures\r\n                if (e.OldVersion == \"4.3.0.0\" || e.OldVersion == \"4.3.1.0\")\r\n                    _config.geositeDirectGroups.Add(\"private\");\r\n\r\n                logger.Info($\"Updated from {e.OldVersion} to {e.NewVersion}\");\r\n            };\r\n        }\r\n\r\n        #region Basic\r\n\r\n        public void Start(bool systemWakeUp = false)\r\n        {\r\n            if (_config.firstRunOnNewVersion && !systemWakeUp)\r\n            {\r\n                ProgramUpdated.Invoke(this, new UpdatedEventArgs()\r\n                {\r\n                    OldVersion = _config.version,\r\n                    NewVersion = UpdateChecker.Version,\r\n                });\r\n                // delete pac.txt when regeneratePacOnUpdate is true\r\n                if (_config.regeneratePacOnUpdate)\r\n                    try\r\n                    {\r\n                        File.Delete(PACDaemon.PAC_FILE);\r\n                        logger.Info(\"Deleted pac.txt from previous version.\");\r\n                    }\r\n                    catch (Exception e)\r\n                    {\r\n                        logger.LogUsefulException(e);\r\n                    }\r\n                // finish up first run of new version\r\n                _config.firstRunOnNewVersion = false;\r\n                _config.version = UpdateChecker.Version;\r\n                Configuration.Save(_config);\r\n            }\r\n            Reload();\r\n            if (!systemWakeUp)\r\n                HotkeyReg.RegAllHotkeys();\r\n        }\r\n\r\n        public void Stop()\r\n        {\r\n            if (stopped)\r\n            {\r\n                return;\r\n            }\r\n            stopped = true;\r\n            if (_listener != null)\r\n            {\r\n                _listener.Stop();\r\n            }\r\n            StopPlugins();\r\n            if (privoxyRunner != null)\r\n            {\r\n                privoxyRunner.Stop();\r\n            }\r\n            if (_config.enabled)\r\n            {\r\n                SystemProxy.Update(_config, true, null);\r\n            }\r\n            Encryption.RNG.Close();\r\n        }\r\n\r\n        protected void Reload()\r\n        {\r\n            Encryption.RNG.Reload();\r\n            // some logic in configuration updated the config when saving, we need to read it again\r\n            _config = Configuration.Load();\r\n            Configuration.Process(ref _config);\r\n\r\n            NLogConfig.LoadConfiguration();\r\n\r\n            logger.Info($\"WPF Localization Extension|Current culture: {LocalizeDictionary.CurrentCulture}\");\r\n\r\n            // set User-Agent for httpClient\r\n            try\r\n            {\r\n                if (!string.IsNullOrWhiteSpace(_config.userAgentString))\r\n                    httpClient.DefaultRequestHeaders.Add(\"User-Agent\", _config.userAgentString);\r\n            }\r\n            catch\r\n            {\r\n                // reset userAgent to default and reapply\r\n                Configuration.ResetUserAgent(_config);\r\n                httpClient.DefaultRequestHeaders.Add(\"User-Agent\", _config.userAgentString);\r\n            }\r\n\r\n            privoxyRunner = privoxyRunner ?? new PrivoxyRunner();\r\n\r\n            _pacDaemon = _pacDaemon ?? new PACDaemon(_config);\r\n            _pacDaemon.PACFileChanged += PacDaemon_PACFileChanged;\r\n            _pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged;\r\n            _pacServer = _pacServer ?? new PACServer(_pacDaemon);\r\n            _pacServer.UpdatePACURL(_config); // So PACServer works when system proxy disabled.\r\n\r\n            GeositeUpdater.ResetEvent();\r\n            GeositeUpdater.UpdateCompleted += PacServer_PACUpdateCompleted;\r\n            GeositeUpdater.Error += PacServer_PACUpdateError;\r\n\r\n            _listener?.Stop();\r\n            StopPlugins();\r\n\r\n            // don't put PrivoxyRunner.Start() before pacServer.Stop()\r\n            // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1\r\n            // though UseShellExecute is set to true now\r\n            // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open\r\n            privoxyRunner.Stop();\r\n            try\r\n            {\r\n                var strategy = GetCurrentStrategy();\r\n                strategy?.ReloadServers();\r\n\r\n                StartPlugin();\r\n                privoxyRunner.Start(_config);\r\n\r\n                TCPRelay tcpRelay = new TCPRelay(this, _config);\r\n                tcpRelay.OnInbound += UpdateInboundCounter;\r\n                tcpRelay.OnOutbound += UpdateOutboundCounter;\r\n                tcpRelay.OnFailed += (o, e) => GetCurrentStrategy()?.SetFailure(e.server);\r\n\r\n                UDPRelay udpRelay = new UDPRelay(this);\r\n                List<Listener.IService> services = new List<Listener.IService>\r\n                {\r\n                    tcpRelay,\r\n                    udpRelay,\r\n                    _pacServer,\r\n                    new PortForwarder(privoxyRunner.RunningPort)\r\n                };\r\n                _listener = new Listener(services);\r\n                _listener.Start(_config);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                // translate Microsoft language into human language\r\n                // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use\r\n                if (e is SocketException se)\r\n                {\r\n                    if (se.SocketErrorCode == SocketError.AddressAlreadyInUse)\r\n                    {\r\n                        e = new Exception(I18N.GetString(\"Port {0} already in use\", _config.localPort), e);\r\n                    }\r\n                    else if (se.SocketErrorCode == SocketError.AccessDenied)\r\n                    {\r\n                        e = new Exception(I18N.GetString(\"Port {0} is reserved by system\", _config.localPort), e);\r\n                    }\r\n                }\r\n                logger.LogUsefulException(e);\r\n                ReportError(e);\r\n            }\r\n\r\n            ConfigChanged?.Invoke(this, new EventArgs());\r\n            UpdateSystemProxy();\r\n        }\r\n\r\n        protected void SaveConfig(Configuration newConfig)\r\n        {\r\n            Configuration.Save(newConfig);\r\n            Reload();\r\n        }\r\n\r\n        protected void ReportError(Exception e)\r\n        {\r\n            Errored?.Invoke(this, new ErrorEventArgs(e));\r\n        }\r\n\r\n        public HttpClient GetHttpClient() => httpClient;\r\n        public Server GetCurrentServer() => _config.GetCurrentServer();\r\n        public Configuration GetCurrentConfiguration() => _config;\r\n\r\n        public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)\r\n        {\r\n            IStrategy strategy = GetCurrentStrategy();\r\n            if (strategy != null)\r\n            {\r\n                return strategy.GetAServer(type, localIPEndPoint, destEndPoint);\r\n            }\r\n            if (_config.index < 0)\r\n            {\r\n                _config.index = 0;\r\n            }\r\n            return GetCurrentServer();\r\n        }\r\n\r\n        public void SaveServers(List<Server> servers, int localPort, bool portableMode)\r\n        {\r\n            _config.configs = servers;\r\n            _config.localPort = localPort;\r\n            _config.portableMode = portableMode;\r\n            Configuration.Save(_config);\r\n        }\r\n\r\n        public void SelectServerIndex(int index)\r\n        {\r\n            _config.index = index;\r\n            _config.strategy = null;\r\n            SaveConfig(_config);\r\n        }\r\n\r\n        public void ToggleShareOverLAN(bool enabled)\r\n        {\r\n            _config.shareOverLan = enabled;\r\n            SaveConfig(_config);\r\n\r\n            ShareOverLANStatusChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region OS Proxy\r\n\r\n        public void ToggleEnable(bool enabled)\r\n        {\r\n            _config.enabled = enabled;\r\n            SaveConfig(_config);\r\n\r\n            EnableStatusChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        public void ToggleGlobal(bool global)\r\n        {\r\n            _config.global = global;\r\n            SaveConfig(_config);\r\n\r\n            EnableGlobalChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        public void SaveProxy(ForwardProxyConfig proxyConfig)\r\n        {\r\n            _config.proxy = proxyConfig;\r\n            SaveConfig(_config);\r\n        }\r\n\r\n        private void UpdateSystemProxy()\r\n        {\r\n            SystemProxy.Update(_config, false, _pacServer);\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region PAC\r\n\r\n        private void PacDaemon_PACFileChanged(object sender, EventArgs e)\r\n        {\r\n            UpdateSystemProxy();\r\n        }\r\n\r\n        private void PacServer_PACUpdateCompleted(object sender, GeositeResultEventArgs e)\r\n        {\r\n            UpdatePACFromGeositeCompleted?.Invoke(this, e);\r\n        }\r\n\r\n        private void PacServer_PACUpdateError(object sender, ErrorEventArgs e)\r\n        {\r\n            UpdatePACFromGeositeError?.Invoke(this, e);\r\n        }\r\n\r\n        private static readonly IEnumerable<char> IgnoredLineBegins = new[] { '!', '[' };\r\n        private void PacDaemon_UserRuleFileChanged(object sender, EventArgs e)\r\n        {\r\n            GeositeUpdater.MergeAndWritePACFile(_config.geositeDirectGroups, _config.geositeProxiedGroups, _config.geositePreferDirect);\r\n            UpdateSystemProxy();\r\n        }\r\n\r\n        public void CopyPacUrl()\r\n        {\r\n            Clipboard.SetDataObject(_pacServer.PacUrl);\r\n        }\r\n\r\n        public void SavePACUrl(string pacUrl)\r\n        {\r\n            _config.pacUrl = pacUrl;\r\n            SaveConfig(_config);\r\n\r\n            ConfigChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        public void UseOnlinePAC(bool useOnlinePac)\r\n        {\r\n            _config.useOnlinePac = useOnlinePac;\r\n            SaveConfig(_config);\r\n\r\n            ConfigChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        public void TouchPACFile()\r\n        {\r\n            string pacFilename = _pacDaemon.TouchPACFile();\r\n\r\n            PACFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = pacFilename });\r\n        }\r\n\r\n        public void TouchUserRuleFile()\r\n        {\r\n            string userRuleFilename = _pacDaemon.TouchUserRuleFile();\r\n\r\n            UserRuleFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = userRuleFilename });\r\n        }\r\n\r\n        public void ToggleSecureLocalPac(bool enabled)\r\n        {\r\n            _config.secureLocalPac = enabled;\r\n            SaveConfig(_config);\r\n\r\n            ConfigChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        public void ToggleRegeneratePacOnUpdate(bool enabled)\r\n        {\r\n            _config.regeneratePacOnUpdate = enabled;\r\n            SaveConfig(_config);\r\n            ConfigChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region  SIP002\r\n\r\n        public bool AskAddServerBySSURL(string ssURL)\r\n        {\r\n            var dr = MessageBox.Show(I18N.GetString(\"Import from URL: {0} ?\", ssURL), I18N.GetString(\"Shadowsocks\"), MessageBoxButtons.YesNo);\r\n            if (dr == DialogResult.Yes)\r\n            {\r\n                if (AddServerBySSURL(ssURL))\r\n                {\r\n                    MessageBox.Show(I18N.GetString(\"Successfully imported from {0}\", ssURL));\r\n                    return true;\r\n                }\r\n                else\r\n                {\r\n                    MessageBox.Show(I18N.GetString(\"Failed to import. Please check if the link is valid.\"));\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public bool AddServerBySSURL(string ssURL)\r\n        {\r\n            try\r\n            {\r\n                if (string.IsNullOrWhiteSpace(ssURL))\r\n                    return false;\r\n\r\n                var servers = Server.GetServers(ssURL);\r\n                if (servers == null || servers.Count == 0)\r\n                    return false;\r\n\r\n                foreach (var server in servers)\r\n                {\r\n                    _config.configs.Add(server);\r\n                    if (server.warnLegacyUrl)\r\n                        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()));\r\n                }\r\n                _config.index = _config.configs.Count - 1;\r\n                SaveConfig(_config);\r\n                return true;\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        public string GetServerURLForCurrentServer()\r\n        {\r\n            return GetCurrentServer().GetURL(_config.generateLegacyUrl);\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Misc\r\n\r\n        public void ToggleVerboseLogging(bool enabled)\r\n        {\r\n            _config.isVerboseLogging = enabled;\r\n            SaveConfig(_config);\r\n            NLogConfig.LoadConfiguration(); // reload nlog\r\n\r\n            VerboseLoggingStatusChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        public void ToggleCheckingUpdate(bool enabled)\r\n        {\r\n            _config.autoCheckUpdate = enabled;\r\n            Configuration.Save(_config);\r\n\r\n            ConfigChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        public void ToggleCheckingPreRelease(bool enabled)\r\n        {\r\n            _config.checkPreRelease = enabled;\r\n            Configuration.Save(_config);\r\n            ConfigChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        public void SaveSkippedUpdateVerion(string version)\r\n        {\r\n            _config.skippedUpdateVersion = version;\r\n            Configuration.Save(_config);\r\n        }\r\n\r\n        public void SaveLogViewerConfig(LogViewerConfig newConfig)\r\n        {\r\n            _config.logViewer = newConfig;\r\n            newConfig.SaveSize();\r\n            Configuration.Save(_config);\r\n\r\n            ConfigChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        public void SaveHotkeyConfig(HotkeyConfig newConfig)\r\n        {\r\n            _config.hotkey = newConfig;\r\n            SaveConfig(_config);\r\n\r\n            ConfigChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Strategy\r\n\r\n        public void SelectStrategy(string strategyID)\r\n        {\r\n            _config.index = -1;\r\n            _config.strategy = strategyID;\r\n            SaveConfig(_config);\r\n        }\r\n\r\n        public IList<IStrategy> GetStrategies()\r\n        {\r\n            return _strategyManager.GetStrategies();\r\n        }\r\n\r\n        public IStrategy GetCurrentStrategy()\r\n        {\r\n            foreach (var strategy in _strategyManager.GetStrategies())\r\n            {\r\n                if (strategy.ID == _config.strategy)\r\n                {\r\n                    return strategy;\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n\r\n        public void UpdateInboundCounter(object sender, SSTransmitEventArgs args)\r\n        {\r\n            GetCurrentStrategy()?.UpdateLastRead(args.server);\r\n            Interlocked.Add(ref _inboundCounter, args.length);\r\n        }\r\n\r\n        public void UpdateOutboundCounter(object sender, SSTransmitEventArgs args)\r\n        {\r\n            GetCurrentStrategy()?.UpdateLastWrite(args.server);\r\n            Interlocked.Add(ref _outboundCounter, args.length);\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region SIP003\r\n\r\n        private void StartPlugin()\r\n        {\r\n            var server = _config.GetCurrentServer();\r\n            GetPluginLocalEndPointIfConfigured(server);\r\n        }\r\n\r\n        private void StopPlugins()\r\n        {\r\n            foreach (var serverAndPlugin in _pluginsByServer)\r\n            {\r\n                serverAndPlugin.Value?.Dispose();\r\n            }\r\n            _pluginsByServer.Clear();\r\n        }\r\n\r\n        public EndPoint GetPluginLocalEndPointIfConfigured(Server server)\r\n        {\r\n            var plugin = _pluginsByServer.GetOrAdd(\r\n                server,\r\n                x => Sip003Plugin.CreateIfConfigured(x, _config.showPluginOutput));\r\n\r\n            if (plugin == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            try\r\n            {\r\n                if (plugin.StartIfNeeded())\r\n                {\r\n                    logger.Info(\r\n                        $\"Started SIP003 plugin for {server.Identifier()} on {plugin.LocalEndPoint} - PID: {plugin.ProcessId}\");\r\n                }\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                logger.Error(\"Failed to start SIP003 plugin: \" + ex.Message);\r\n                throw;\r\n            }\r\n\r\n            return plugin.LocalEndPoint;\r\n        }\r\n\r\n        public void ToggleShowPluginOutput(bool enabled)\r\n        {\r\n            _config.showPluginOutput = enabled;\r\n            SaveConfig(_config);\r\n\r\n            ShowPluginOutputChanged?.Invoke(this, new EventArgs());\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Traffic Statistics\r\n\r\n        private void StartTrafficStatistics(int queueMaxSize)\r\n        {\r\n            trafficPerSecondQueue = new Queue<TrafficPerSecond>();\r\n            for (int i = 0; i < queueMaxSize; i++)\r\n            {\r\n                trafficPerSecondQueue.Enqueue(new TrafficPerSecond());\r\n            }\r\n            _trafficThread = new Thread(new ThreadStart(() => TrafficStatistics(queueMaxSize)))\r\n            {\r\n                IsBackground = true\r\n            };\r\n            _trafficThread.Start();\r\n        }\r\n\r\n        private void TrafficStatistics(int queueMaxSize)\r\n        {\r\n            TrafficPerSecond previous, current;\r\n            while (true)\r\n            {\r\n                previous = trafficPerSecondQueue.Last();\r\n                current = new TrafficPerSecond\r\n                {\r\n                    inboundCounter = InboundCounter,\r\n                    outboundCounter = OutboundCounter\r\n                };\r\n                current.inboundIncreasement = current.inboundCounter - previous.inboundCounter;\r\n                current.outboundIncreasement = current.outboundCounter - previous.outboundCounter;\r\n\r\n                trafficPerSecondQueue.Enqueue(current);\r\n                if (trafficPerSecondQueue.Count > queueMaxSize)\r\n                    trafficPerSecondQueue.Dequeue();\r\n\r\n                TrafficChanged?.Invoke(this, new EventArgs());\r\n\r\n                Thread.Sleep(1000);\r\n            }\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region SIP008\r\n\r\n\r\n        public async Task<int> UpdateOnlineConfigInternal(string url)\r\n        {\r\n            var onlineServer = await OnlineConfigResolver.GetOnline(url);\r\n            _config.configs = Configuration.SortByOnlineConfig(\r\n                _config.configs\r\n                .Where(c => c.group != url)\r\n                .Concat(onlineServer)\r\n                );\r\n            logger.Info($\"updated {onlineServer.Count} server from {url}\");\r\n            return onlineServer.Count;\r\n        }\r\n\r\n        public async Task<bool> UpdateOnlineConfig(string url)\r\n        {\r\n            var selected = GetCurrentServer();\r\n            try\r\n            {\r\n                int count = await UpdateOnlineConfigInternal(url);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n                return false;\r\n            }\r\n            _config.index = _config.configs.IndexOf(selected);\r\n            SaveConfig(_config);\r\n            return true;\r\n        }\r\n\r\n        public async Task<List<string>> UpdateAllOnlineConfig()\r\n        {\r\n            var selected = GetCurrentServer();\r\n            var failedUrls = new List<string>();\r\n            foreach (var url in _config.onlineConfigSource)\r\n            {\r\n                try\r\n                {\r\n                    await UpdateOnlineConfigInternal(url);\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.LogUsefulException(e);\r\n                    failedUrls.Add(url);\r\n                }\r\n            }\r\n\r\n            _config.index = _config.configs.IndexOf(selected);\r\n            SaveConfig(_config);\r\n            return failedUrls;\r\n        }\r\n\r\n        public void SaveOnlineConfigSource(List<string> sources)\r\n        {\r\n            _config.onlineConfigSource = sources;\r\n            SaveConfig(_config);\r\n        }\r\n\r\n        public void RemoveOnlineConfig(string url)\r\n        {\r\n            _config.onlineConfigSource.RemoveAll(v => v == url);\r\n            _config.configs = Configuration.SortByOnlineConfig(\r\n                _config.configs.Where(c => c.group != url)\r\n                );\r\n            SaveConfig(_config);\r\n        }\r\n\r\n        #endregion\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Strategy/BalancingStrategy.cs",
    "content": "﻿using Shadowsocks.Controller;\r\nusing Shadowsocks.Model;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Net;\r\nusing System.Text;\r\n\r\nnamespace Shadowsocks.Controller.Strategy\r\n{\r\n    class BalancingStrategy : IStrategy\r\n    {\r\n        ShadowsocksController _controller;\r\n        Random _random;\r\n\r\n        public BalancingStrategy(ShadowsocksController controller)\r\n        {\r\n            _controller = controller;\r\n            _random = new Random();\r\n        }\r\n\r\n        public string Name\r\n        {\r\n            get { return I18N.GetString(\"Load Balance\"); }\r\n        }\r\n\r\n        public string ID\r\n        {\r\n            get { return \"com.shadowsocks.strategy.balancing\"; }\r\n        }\r\n\r\n        public void ReloadServers()\r\n        {\r\n            // do nothing\r\n        }\r\n\r\n        public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)\r\n        {\r\n            var configs = _controller.GetCurrentConfiguration().configs;\r\n            int index;\r\n            if (type == IStrategyCallerType.TCP)\r\n            {\r\n                index = _random.Next();\r\n            }\r\n            else\r\n            {\r\n                index = localIPEndPoint.GetHashCode();\r\n            }\r\n            return configs[index % configs.Count];\r\n        }\r\n\r\n        public void UpdateLatency(Model.Server server, TimeSpan latency)\r\n        {\r\n            // do nothing\r\n        }\r\n\r\n        public void UpdateLastRead(Model.Server server)\r\n        {\r\n            // do nothing\r\n        }\r\n\r\n        public void UpdateLastWrite(Model.Server server)\r\n        {\r\n            // do nothing\r\n        }\r\n\r\n        public void SetFailure(Model.Server server)\r\n        {\r\n            // do nothing\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Strategy/HighAvailabilityStrategy.cs",
    "content": "﻿using NLog;\r\nusing Shadowsocks.Model;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Net;\r\nusing System.Text;\r\n\r\nnamespace Shadowsocks.Controller.Strategy\r\n{\r\n    class HighAvailabilityStrategy : IStrategy\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        protected ServerStatus _currentServer;\r\n        protected Dictionary<Server, ServerStatus> _serverStatus;\r\n        ShadowsocksController _controller;\r\n        Random _random;\r\n\r\n        public class ServerStatus\r\n        {\r\n            // time interval between SYN and SYN+ACK\r\n            public TimeSpan latency;\r\n            public DateTime lastTimeDetectLatency;\r\n\r\n            // last time anything received\r\n            public DateTime lastRead;\r\n\r\n            // last time anything sent\r\n            public DateTime lastWrite;\r\n\r\n            // connection refused or closed before anything received\r\n            public DateTime lastFailure;\r\n\r\n            public Server server;\r\n\r\n            public double score;\r\n        }\r\n\r\n        public HighAvailabilityStrategy(ShadowsocksController controller)\r\n        {\r\n            _controller = controller;\r\n            _random = new Random();\r\n            _serverStatus = new Dictionary<Server, ServerStatus>();\r\n        }\r\n\r\n        public string Name\r\n        {\r\n            get { return I18N.GetString(\"High Availability\"); }\r\n        }\r\n\r\n        public string ID\r\n        {\r\n            get { return \"com.shadowsocks.strategy.ha\"; }\r\n        }\r\n\r\n        public void ReloadServers()\r\n        {\r\n            // make a copy to avoid locking\r\n            var newServerStatus = new Dictionary<Server, ServerStatus>(_serverStatus);\r\n\r\n            foreach (var server in _controller.GetCurrentConfiguration().configs)\r\n            {\r\n                if (!newServerStatus.ContainsKey(server))\r\n                {\r\n                    var status = new ServerStatus();\r\n                    status.server = server;\r\n                    status.lastFailure = DateTime.MinValue;\r\n                    status.lastRead = DateTime.Now;\r\n                    status.lastWrite = DateTime.Now;\r\n                    status.latency = new TimeSpan(0, 0, 0, 0, 10);\r\n                    status.lastTimeDetectLatency = DateTime.Now;\r\n                    newServerStatus[server] = status;\r\n                }\r\n                else\r\n                {\r\n                    // update settings for existing server\r\n                    newServerStatus[server].server = server;\r\n                }\r\n            }\r\n            _serverStatus = newServerStatus;\r\n\r\n            ChooseNewServer();\r\n        }\r\n\r\n        public Server GetAServer(IStrategyCallerType type, System.Net.IPEndPoint localIPEndPoint, EndPoint destEndPoint)\r\n        {\r\n            if (type == IStrategyCallerType.TCP)\r\n            {\r\n                ChooseNewServer();\r\n            }\r\n            if (_currentServer == null)\r\n            {\r\n                return null;\r\n            }\r\n            return _currentServer.server;\r\n        }\r\n\r\n        /**\r\n         * once failed, try after 5 min\r\n         * and (last write - last read) < 5s\r\n         * and (now - last read) <  5s  // means not stuck\r\n         * and latency < 200ms, try after 30s\r\n         */\r\n        public void ChooseNewServer()\r\n        {\r\n            ServerStatus oldServer = _currentServer;\r\n            List<ServerStatus> servers = new List<ServerStatus>(_serverStatus.Values);\r\n            DateTime now = DateTime.Now;\r\n            foreach (var status in servers)\r\n            {\r\n                // all of failure, latency, (lastread - lastwrite) normalized to 1000, then\r\n                // 100 * failure - 2 * latency - 0.5 * (lastread - lastwrite)\r\n                status.score =\r\n                    100 * 1000 * Math.Min(5 * 60, (now - status.lastFailure).TotalSeconds)\r\n                    -2 * 5 * (Math.Min(2000, status.latency.TotalMilliseconds) / (1 + (now - status.lastTimeDetectLatency).TotalSeconds / 30 / 10) +\r\n                    -0.5 * 200 * Math.Min(5, (status.lastRead - status.lastWrite).TotalSeconds));\r\n                logger.Debug(String.Format(\"server: {0} latency:{1} score: {2}\", status.server.ToString(), status.latency, status.score));\r\n            }\r\n            ServerStatus max = null;\r\n            foreach (var status in servers)\r\n            {\r\n                if (max == null)\r\n                {\r\n                    max = status;\r\n                }\r\n                else\r\n                {\r\n                    if (status.score >= max.score)\r\n                    {\r\n                        max = status;\r\n                    }\r\n                }\r\n            }\r\n            if (max != null)\r\n            {\r\n                if (_currentServer == null || max.score - _currentServer.score > 200)\r\n                {\r\n                    _currentServer = max;\r\n                    logger.Info($\"HA switching to server: {_currentServer.server.ToString()}\");\r\n                }\r\n            }\r\n        }\r\n\r\n        public void UpdateLatency(Model.Server server, TimeSpan latency)\r\n        {\r\n            logger.Debug($\"latency: {server.ToString()} {latency}\");\r\n\r\n            ServerStatus status;\r\n            if (_serverStatus.TryGetValue(server, out status))\r\n            {\r\n                status.latency = latency;\r\n                status.lastTimeDetectLatency = DateTime.Now;\r\n            }\r\n        }\r\n\r\n        public void UpdateLastRead(Model.Server server)\r\n        {\r\n            logger.Debug($\"last read: {server.ToString()}\");\r\n\r\n            ServerStatus status;\r\n            if (_serverStatus.TryGetValue(server, out status))\r\n            {\r\n                status.lastRead = DateTime.Now;\r\n            }\r\n        }\r\n\r\n        public void UpdateLastWrite(Model.Server server)\r\n        {\r\n            logger.Debug($\"last write: {server.ToString()}\");\r\n\r\n            ServerStatus status;\r\n            if (_serverStatus.TryGetValue(server, out status))\r\n            {\r\n                status.lastWrite = DateTime.Now;\r\n            }\r\n        }\r\n\r\n        public void SetFailure(Model.Server server)\r\n        {\r\n            logger.Debug($\"failure: {server.ToString()}\");\r\n\r\n            ServerStatus status;\r\n            if (_serverStatus.TryGetValue(server, out status))\r\n            {\r\n                status.lastFailure = DateTime.Now;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Strategy/IStrategy.cs",
    "content": "﻿using Shadowsocks.Model;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Net;\r\nusing System.Text;\r\n\r\nnamespace Shadowsocks.Controller.Strategy\r\n{\r\n    public enum IStrategyCallerType\r\n    {\r\n        TCP,\r\n        UDP\r\n    }\r\n\r\n    /*\r\n     * IStrategy\r\n     *\r\n     * Subclasses must be thread-safe\r\n     */\r\n    public interface IStrategy\r\n    {\r\n        string Name { get; }\r\n\r\n        string ID { get; }\r\n\r\n        /*\r\n         * Called when servers need to be reloaded, i.e. new configuration saved\r\n         */\r\n        void ReloadServers();\r\n\r\n        /*\r\n         * Get a new server to use in TCPRelay or UDPRelay\r\n         */\r\n        Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint);\r\n\r\n        /*\r\n         * TCPRelay will call this when latency of a server detected\r\n         */\r\n        void UpdateLatency(Server server, TimeSpan latency);\r\n\r\n        /*\r\n         * TCPRelay will call this when reading from a server\r\n         */\r\n        void UpdateLastRead(Server server);\r\n\r\n        /*\r\n         * TCPRelay will call this when writing to a server\r\n         */\r\n        void UpdateLastWrite(Server server);\r\n\r\n        /*\r\n         * TCPRelay will call this when fatal failure detected\r\n         */\r\n        void SetFailure(Server server);\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/Strategy/StrategyManager.cs",
    "content": "﻿using Shadowsocks.Controller;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Shadowsocks.Controller.Strategy\r\n{\r\n    class StrategyManager\r\n    {\r\n        List<IStrategy> _strategies;\r\n        public StrategyManager(ShadowsocksController controller)\r\n        {\r\n            _strategies = new List<IStrategy>();\r\n            _strategies.Add(new BalancingStrategy(controller));\r\n            _strategies.Add(new HighAvailabilityStrategy(controller));\r\n            // TODO: load DLL plugins\r\n        }\r\n        public IList<IStrategy> GetStrategies()\r\n        {\r\n            return _strategies;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/System/AutoStartup.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Runtime.InteropServices;\r\nusing Microsoft.Win32;\r\nusing NLog;\r\nusing Shadowsocks.Util;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    static class AutoStartup\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        // Don't use Application.ExecutablePath\r\n        // see https://stackoverflow.com/questions/12945805/odd-c-sharp-path-issue\r\n\r\n        private static string Key = \"Shadowsocks_\" + Program.ExecutablePath.GetHashCode();\r\n\r\n        public static bool Set(bool enabled)\r\n        {\r\n            RegistryKey runKey = null;\r\n            try\r\n            {\r\n                runKey = Utils.OpenRegKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Run\", true);\r\n                if (runKey == null)\r\n                {\r\n                    logger.Error(@\"Cannot find HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\");\r\n                    return false;\r\n                }\r\n                if (enabled)\r\n                {\r\n                    runKey.SetValue(Key, Program.ExecutablePath);\r\n                }\r\n                else\r\n                {\r\n                    runKey.DeleteValue(Key);\r\n                }\r\n                // When autostartup setting change, change RegisterForRestart state to avoid start 2 times\r\n                RegisterForRestart(!enabled);\r\n                return true;\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n                return false;\r\n            }\r\n            finally\r\n            {\r\n                if (runKey != null)\r\n                {\r\n                    try\r\n                    {\r\n                        runKey.Close();\r\n                        runKey.Dispose();\r\n                    }\r\n                    catch (Exception e)\r\n                    { logger.LogUsefulException(e); }\r\n                }\r\n            }\r\n        }\r\n\r\n        public static bool Check()\r\n        {\r\n            RegistryKey runKey = null;\r\n            try\r\n            {\r\n                runKey = Utils.OpenRegKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Run\", true);\r\n                if (runKey == null)\r\n                {\r\n                    logger.Error(@\"Cannot find HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\");\r\n                    return false;\r\n                }\r\n                var check = false;\r\n                foreach (var valueName in runKey.GetValueNames())\r\n                {\r\n                    if (valueName.Equals(Key, StringComparison.InvariantCultureIgnoreCase))\r\n                    {\r\n                        check = true;\r\n                        continue;\r\n                    }\r\n\r\n                    // Remove other startup keys with the same executable path. fixes #3011 and also assures compatibility with older versions\r\n                    if (Program.ExecutablePath.Equals(runKey.GetValue(valueName).ToString(), StringComparison.InvariantCultureIgnoreCase))\r\n                    {\r\n                        runKey.DeleteValue(valueName);\r\n                        runKey.SetValue(Key, Program.ExecutablePath);\r\n                        check = true;\r\n                    }\r\n                }\r\n                return check;\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n                return false;\r\n            }\r\n            finally\r\n            {\r\n                if (runKey != null)\r\n                {\r\n                    try\r\n                    {\r\n                        runKey.Close();\r\n                        runKey.Dispose();\r\n                    }\r\n                    catch (Exception e)\r\n                    { logger.LogUsefulException(e); }\r\n                }\r\n            }\r\n        }\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true)]\r\n        static extern int RegisterApplicationRestart([MarshalAs(UnmanagedType.LPWStr)] string commandLineArgs, int Flags);\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true)]\r\n        static extern int UnregisterApplicationRestart();\r\n\r\n        [Flags]\r\n        enum ApplicationRestartFlags\r\n        {\r\n            RESTART_ALWAYS = 0,\r\n            RESTART_NO_CRASH = 1,\r\n            RESTART_NO_HANG = 2,\r\n            RESTART_NO_PATCH = 4,\r\n            RESTART_NO_REBOOT = 8,\r\n        }\r\n\r\n        // register restart after system reboot/update\r\n        public static void RegisterForRestart(bool register)\r\n        {\r\n            // requested register and not autostartup\r\n            if (register && !Check())\r\n            {\r\n                // escape command line parameter\r\n                string[] args = new List<string>(Program.Args)\r\n                    .Select(p => p.Replace(\"\\\"\", \"\\\\\\\"\"))                   // escape \" to \\\"\r\n                    .Select(p => p.IndexOf(\" \") >= 0 ? \"\\\"\" + p + \"\\\"\" : p) // encapsule with \"\r\n                    .ToArray();\r\n                string cmdline = string.Join(\" \", args);\r\n                // first parameter is process command line parameter\r\n                // needn't include the name of the executable in the command line\r\n                RegisterApplicationRestart(cmdline, (int)(ApplicationRestartFlags.RESTART_NO_CRASH | ApplicationRestartFlags.RESTART_NO_HANG));\r\n                logger.Debug(\"Register restart after system reboot, command line:\" + cmdline);\r\n            }\r\n            // requested unregister, which has no side effect\r\n            else if (!register)\r\n            {\r\n                UnregisterApplicationRestart();\r\n                logger.Debug(\"Unregister restart after system reboot\");\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/System/Hotkeys/HotkeyCallbacks.cs",
    "content": "﻿using System;\nusing System.Reflection;\n\nnamespace Shadowsocks.Controller.Hotkeys\n{\n    public class HotkeyCallbacks\n    {\n\n        public static void InitInstance(ShadowsocksController controller)\n        {\n            if (Instance != null)\n            {\n                return;\n            }\n\n            Instance = new HotkeyCallbacks(controller);\n        }\n\n        /// <summary>\n        /// Create hotkey callback handler delegate based on callback name\n        /// </summary>\n        /// <param name=\"methodname\"></param>\n        /// <returns></returns>\n        public static Delegate GetCallback(string methodname)\n        {\n            if (string.IsNullOrEmpty(methodname)) throw new ArgumentException(nameof(methodname));\n            MethodInfo dynMethod = typeof(HotkeyCallbacks).GetMethod(methodname,\n                BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase);\n            return dynMethod == null ? null : Delegate.CreateDelegate(typeof(HotKeys.HotKeyCallBackHandler), Instance, dynMethod);\n        }\n\n        #region Singleton \n        \n        private static HotkeyCallbacks Instance { get; set; }\n\n        private readonly ShadowsocksController _controller;\n\n        private HotkeyCallbacks(ShadowsocksController controller)\n        {\n            _controller = controller;\n        }\n\n        #endregion\n\n        #region Callbacks\n\n        private void SwitchSystemProxyCallback()\n        {\n            bool enabled = _controller.GetCurrentConfiguration().enabled;\n            _controller.ToggleEnable(!enabled);\n        }\n\n        private void SwitchSystemProxyModeCallback()\n        {\n            var config = _controller.GetCurrentConfiguration();\n            if (config.enabled)\n                _controller.ToggleGlobal(!config.global);\n        }\n\n        private void SwitchAllowLanCallback()\n        {\n            var status = _controller.GetCurrentConfiguration().shareOverLan;\n            _controller.ToggleShareOverLAN(!status);\n        }\n\n        private void ShowLogsCallback()\n        {\n            Program.MenuController.ShowLogForm_HotKey();\n        }\n\n        private void ServerMoveUpCallback()\n        {\n            int currIndex;\n            int serverCount;\n            GetCurrServerInfo(out currIndex, out serverCount);\n            if (currIndex - 1 < 0)\n            {\n                // revert to last server\n                currIndex = serverCount - 1;\n            }\n            else\n            {\n                currIndex -= 1;\n            }\n            _controller.SelectServerIndex(currIndex);\n        }\n\n        private void ServerMoveDownCallback()\n        {\n            int currIndex;\n            int serverCount;\n            GetCurrServerInfo(out currIndex, out serverCount);\n            if (currIndex + 1 == serverCount)\n            {\n                // revert to first server\n                currIndex = 0;\n            }\n            else\n            {\n                currIndex += 1;\n            }\n            _controller.SelectServerIndex(currIndex);\n        }\n\n        private void GetCurrServerInfo(out int currIndex, out int serverCount)\n        {\n            var currConfig = _controller.GetCurrentConfiguration();\n            currIndex = currConfig.index;\n            serverCount = currConfig.configs.Count;\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/System/Hotkeys/Hotkeys.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Windows.Input;\nusing GlobalHotKey;\n\nnamespace Shadowsocks.Controller.Hotkeys\n{\n    public static class HotKeys\n    {\n        private static HotKeyManager _hotKeyManager;\n\n        public delegate void HotKeyCallBackHandler();\n        // map key and corresponding handler function\n        private static Dictionary<HotKey, HotKeyCallBackHandler> _keymap = new Dictionary<HotKey, HotKeyCallBackHandler>();\n\n        public static void Init(ShadowsocksController controller)\n        {\n            _hotKeyManager = new HotKeyManager();\n            _hotKeyManager.KeyPressed += HotKeyManagerPressed;\n\n            HotkeyCallbacks.InitInstance(controller);\n        }\n\n        public static void Destroy()\n        {\n            _hotKeyManager.KeyPressed -= HotKeyManagerPressed;\n            _hotKeyManager.Dispose();\n        }\n\n        private static void HotKeyManagerPressed(object sender, KeyPressedEventArgs e)\n        {\n            var hotkey = e.HotKey;\n            HotKeyCallBackHandler callback;\n            if (_keymap.TryGetValue(hotkey, out callback))\n                callback();\n        }\n\n        public static bool RegHotkey(HotKey hotkey, HotKeyCallBackHandler callback)\n        {\n            UnregExistingHotkey(callback);\n            return Register(hotkey, callback);\n        }\n\n        public static bool UnregExistingHotkey(HotKeys.HotKeyCallBackHandler cb)\n        {\n            HotKey existingHotKey;\n            if (IsCallbackExists(cb, out existingHotKey))\n            {\n                // unregister existing one\n                Unregister(existingHotKey);\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        public static bool IsHotkeyExists( HotKey hotKey )\n        {\n            if (hotKey == null) throw new ArgumentNullException(nameof(hotKey));\n            return _keymap.Any( v => v.Key.Equals( hotKey ) );\n        }\n\n        public static bool IsCallbackExists( HotKeyCallBackHandler cb, out HotKey hotkey)\n        {\n            if (cb == null) throw new ArgumentNullException(nameof(cb));\n            if (_keymap.Any(v => v.Value == cb))\n            {\n                hotkey = _keymap.First(v => v.Value == cb).Key;\n                return true;\n            }\n            else\n            {\n                hotkey = null;\n                return false;\n            }\n        }\n\n        #region Converters\n\n        public static string HotKey2Str( HotKey key )\n        {\n            if (key == null) throw new ArgumentNullException(nameof(key));\n            return HotKey2Str( key.Key, key.Modifiers );\n        }\n\n        public static string HotKey2Str( Key key, ModifierKeys modifier )\n        {\n            if (!Enum.IsDefined(typeof(Key), key))\n                throw new InvalidEnumArgumentException(nameof(key), (int) key, typeof(Key));\n            try\n            {\n                ModifierKeysConverter mkc = new ModifierKeysConverter();\n                var keyStr = Enum.GetName(typeof(Key), key);\n                var modifierStr = mkc.ConvertToInvariantString(modifier);\n\n                return $\"{modifierStr}+{keyStr}\";\n            }\n            catch (NotSupportedException)\n            {\n                // converter exception\n                return null;\n            }\n        }\n\n        public static HotKey Str2HotKey(string s)\n        {\n            try\n            {\n                if (string.IsNullOrEmpty(s)) return null;\n                int offset = s.LastIndexOf(\"+\", StringComparison.OrdinalIgnoreCase);\n                if (offset <= 0) return null;\n                string modifierStr = s.Substring(0, offset).Trim();\n                string keyStr = s.Substring(offset + 1).Trim();\n\n                KeyConverter kc = new KeyConverter();\n                ModifierKeysConverter mkc = new ModifierKeysConverter();\n                Key key = (Key) kc.ConvertFrom(keyStr.ToUpper());\n                ModifierKeys modifier = (ModifierKeys) mkc.ConvertFrom(modifierStr.ToUpper());\n\n                return new HotKey(key, modifier);\n            }\n            catch (NotSupportedException)\n            {\n                // converter exception\n                return null;\n            }\n            catch (NullReferenceException)\n            {\n                return null;\n            }\n        }\n\n        #endregion\n\n        private static bool Register(HotKey key, HotKeyCallBackHandler callBack)\n        {\n            if (key == null)\n                throw new ArgumentNullException(nameof(key));\n            if (callBack == null)\n                throw new ArgumentNullException(nameof(callBack));\n            try\n            {\n                _hotKeyManager.Register(key);\n                _keymap[key] = callBack;\n                return true;\n            }\n            catch (ArgumentException)\n            {\n                // already called this method with the specific hotkey\n                // return success silently\n                return true;\n            }\n            catch (Win32Exception)\n            {\n                // this hotkey already registered by other programs\n                // notify user to change key\n                return false;\n            }\n        }\n\n        private static void Unregister(HotKey key)\n        {\n            if (key == null)\n                throw new ArgumentNullException(nameof(key));\n            _hotKeyManager.Unregister(key);\n            if(_keymap.ContainsKey(key))\n                _keymap.Remove(key);\n        }\n    }\n}"
  },
  {
    "path": "shadowsocks-csharp/Controller/System/ProtocolHandler.cs",
    "content": "﻿using Microsoft.Win32;\nusing NLog;\nusing Shadowsocks.Util;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Shadowsocks.Controller\n{\n    static class ProtocolHandler\n    {\n        const string ssURLRegKey = @\"SOFTWARE\\Classes\\ss\";\n\n        private static Logger logger = LogManager.GetCurrentClassLogger();\n\n        public static bool Set(bool enabled)\n        {\n            RegistryKey ssURLAssociation = null;\n\n            try\n            {\n                ssURLAssociation = Registry.CurrentUser.CreateSubKey(ssURLRegKey, RegistryKeyPermissionCheck.ReadWriteSubTree);\n                if (ssURLAssociation == null)\n                {\n                    logger.Error(@\"Failed to create HKCU\\SOFTWARE\\Classes\\ss to register ss:// association.\");\n                    return false;\n                }\n                if (enabled)\n                {\n                    ssURLAssociation.SetValue(\"\", \"URL:Shadowsocks\");\n                    ssURLAssociation.SetValue(\"URL Protocol\", \"\");\n                    var shellOpen = ssURLAssociation.CreateSubKey(\"shell\").CreateSubKey(\"open\").CreateSubKey(\"command\");\n                    shellOpen.SetValue(\"\", $\"{Program.ExecutablePath} --open-url %1\");\n                    logger.Info(@\"Successfully added ss:// association.\");\n                }\n                else\n                {\n                    Registry.CurrentUser.DeleteSubKeyTree(ssURLRegKey);\n                    logger.Info(@\"Successfully removed ss:// association.\");\n                }\n                return true;\n            }\n            catch (Exception e)\n            {\n                logger.LogUsefulException(e);\n                return false;\n            }\n            finally\n            {\n                if (ssURLAssociation != null)\n                {\n                    try\n                    {\n                        ssURLAssociation.Close();\n                        ssURLAssociation.Dispose();\n                    }\n                    catch (Exception e)\n                    { logger.LogUsefulException(e); }\n                }\n            }\n        }\n\n        public static bool Check()\n        {\n            RegistryKey ssURLAssociation = null;\n            try\n            {\n                ssURLAssociation = Registry.CurrentUser.OpenSubKey(ssURLRegKey, true);\n                if (ssURLAssociation == null)\n                {\n                    //logger.Info(@\"ss:// links not associated.\");\n                    return false;\n                }\n\n                var shellOpen = ssURLAssociation.OpenSubKey(\"shell\").OpenSubKey(\"open\").OpenSubKey(\"command\");\n                return (string)shellOpen.GetValue(\"\") == $\"{Program.ExecutablePath} --open-url %1\";\n            }\n            catch (Exception e)\n            {\n                logger.LogUsefulException(e);\n                return false;\n            }\n            finally\n            {\n                if (ssURLAssociation != null)\n                {\n                    try\n                    {\n                        ssURLAssociation.Close();\n                        ssURLAssociation.Dispose();\n                    }\n                    catch (Exception e)\n                    { logger.LogUsefulException(e); }\n                }\n            }\n        }\n\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Controller/System/SystemProxy.cs",
    "content": "﻿using System;\r\nusing System.Windows.Forms;\r\nusing NLog;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Util.SystemProxy;\r\n\r\nnamespace Shadowsocks.Controller\r\n{\r\n    public static class SystemProxy\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private static string GetTimestamp(DateTime value)\r\n        {\r\n            return value.ToString(\"yyyyMMddHHmmssfff\");\r\n        }\r\n\r\n        public static void Update(Configuration config, bool forceDisable, PACServer pacSrv, bool noRetry = false)\r\n        {\r\n            bool global = config.global;\r\n            bool enabled = config.enabled;\r\n\r\n            if (forceDisable)\r\n            {\r\n                enabled = false;\r\n            }\r\n\r\n            try\r\n            {\r\n                if (enabled)\r\n                {\r\n                    if (global)\r\n                    {\r\n                        Sysproxy.SetIEProxy(true, true, \"localhost:\" + config.localPort.ToString(), null);\r\n                    }\r\n                    else\r\n                    {\r\n                        string pacUrl;\r\n                        if (config.useOnlinePac && !string.IsNullOrEmpty(config.pacUrl))\r\n                        {\r\n                            pacUrl = config.pacUrl;\r\n                        }\r\n                        else\r\n                        {\r\n\r\n                            pacUrl = pacSrv.PacUrl;\r\n                        }\r\n                        Sysproxy.SetIEProxy(true, false, null, pacUrl);\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    Sysproxy.SetIEProxy(false, false, null, null);\r\n                }\r\n            }\r\n            catch (ProxyException ex)\r\n            {\r\n                logger.LogUsefulException(ex);\r\n                if (ex.Type != ProxyExceptionType.Unspecific && !noRetry)\r\n                {\r\n                    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);\r\n                    if (ret == DialogResult.Yes)\r\n                    {\r\n                        Sysproxy.ResetIEProxy();\r\n                        Update(config, forceDisable, pacSrv, true);\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    MessageBox.Show(I18N.GetString(\"Unrecoverable proxy setting error occured, see log for detail\"), I18N.GetString(\"Shadowsocks\"), MessageBoxButtons.OK, MessageBoxIcon.Error);\r\n                }\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Data/NLog.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<!-- Warning: Configuration may reset after shadowsocks upgrade. -->\r\n<!-- If you messed it up, delete this file and Shadowsocks will create a new one. -->\r\n<nlog xmlns=\"http://www.nlog-project.org/schemas/NLog.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n  <targets>\r\n    <!-- This line is managed by Shadowsocks. Do not modify it unless you know what you are doing.-->\r\n    <target name=\"file\" xsi:type=\"File\" fileName=\"ss_win_temp\\shadowsocks.log\" writeBom=\"false\" encoding=\"utf-8\"/>\r\n  </targets>\r\n  <rules>\r\n    <!-- This line is managed by Shadowsocks. Do not modify it unless you know what you are doing. -->\r\n    <logger name=\"*\" minlevel=\"Info\" writeTo=\"file\"/>\r\n  </rules>\r\n</nlog>"
  },
  {
    "path": "shadowsocks-csharp/Data/abp.js",
    "content": "/* eslint-disable */\r\n// Was generated by gfwlist2pac in precise mode\r\n// https://github.com/clowwindy/gfwlist2pac\r\n\r\n// 2019-10-06: More 'javascript' way to interaction with main program\r\n// 2019-02-08: Updated to support shadowsocks-windows user rules.\r\n\r\nvar proxy = __PROXY__;\r\nvar userrules = [];\r\nvar rules = [];\r\n\r\n// convert to abp grammar\r\nvar re = /^(@@)?\\|\\|.*?[^\\^]$/;\r\nfor (var i = 0; i < __RULES__.length; i++) {\r\n    var s = __RULES__[i];\r\n    if (s.match(re)) s += \"^\";\r\n    rules.push(s);\r\n}\r\n\r\nfor (var i = 0; i < __USERRULES__.length; i++) {\r\n    var s = __USERRULES__[i];\r\n    if (s.match(re))  s += \"^\";\r\n    userrules.push(s);\r\n}\r\n\r\n/*\r\n* This file is part of Adblock Plus <http://adblockplus.org/>,\r\n* Copyright (C) 2006-2014 Eyeo GmbH\r\n*\r\n* Adblock Plus is free software: you can redistribute it and/or modify\r\n* it under the terms of the GNU General Public License version 3 as\r\n* published by the Free Software Foundation.\r\n*\r\n* Adblock Plus is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n* GNU General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU General Public License\r\n* along with Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\nfunction createDict()\r\n{\r\n    var result = {};\r\n    result.__proto__ = null;\r\n    return result;\r\n}\r\n\r\nfunction getOwnPropertyDescriptor(obj, key)\r\n{\r\n    if (obj.hasOwnProperty(key))\r\n    {\r\n        return obj[key];\r\n    }\r\n    return null;\r\n}\r\n\r\nfunction extend(subclass, superclass, definition)\r\n{\r\n    if (Object.__proto__)\r\n    {\r\n        definition.__proto__ = superclass.prototype;\r\n        subclass.prototype = definition;\r\n    }\r\n    else\r\n    {\r\n        var tmpclass = function(){}, ret;\r\n        tmpclass.prototype = superclass.prototype;\r\n        subclass.prototype = new tmpclass();\r\n        subclass.prototype.constructor = superclass;\r\n        for (var i in definition)\r\n        {\r\n            if (definition.hasOwnProperty(i))\r\n            {\r\n                subclass.prototype[i] = definition[i];\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nfunction Filter(text)\r\n{\r\n    this.text = text;\r\n    this.subscriptions = [];\r\n}\r\nFilter.prototype = {\r\n    text: null,\r\n    subscriptions: null,\r\n    toString: function()\r\n    {\r\n        return this.text;\r\n    }\r\n};\r\nFilter.knownFilters = createDict();\r\nFilter.elemhideRegExp = /^([^\\/\\*\\|\\@\"!]*?)#(\\@)?(?:([\\w\\-]+|\\*)((?:\\([\\w\\-]+(?:[$^*]?=[^\\(\\)\"]*)?\\))*)|#([^{}]+))$/;\r\nFilter.regexpRegExp = /^(@@)?\\/.*\\/(?:\\$~?[\\w\\-]+(?:=[^,\\s]+)?(?:,~?[\\w\\-]+(?:=[^,\\s]+)?)*)?$/;\r\nFilter.optionsRegExp = /\\$(~?[\\w\\-]+(?:=[^,\\s]+)?(?:,~?[\\w\\-]+(?:=[^,\\s]+)?)*)$/;\r\nFilter.fromText = function(text)\r\n{\r\n    if (text in Filter.knownFilters)\r\n    {\r\n        return Filter.knownFilters[text];\r\n    }\r\n    var ret;\r\n    if (text.charAt(0) == \"!\")\r\n    {\r\n        ret = new CommentFilter(text);\r\n    }\r\n    else\r\n    {\r\n        ret = RegExpFilter.fromText(text);\r\n    }\r\n    Filter.knownFilters[ret.text] = ret;\r\n    return ret;\r\n};\r\n\r\nfunction InvalidFilter(text, reason)\r\n{\r\n    Filter.call(this, text);\r\n    this.reason = reason;\r\n}\r\nextend(InvalidFilter, Filter, {\r\n    reason: null\r\n});\r\n\r\nfunction CommentFilter(text)\r\n{\r\n    Filter.call(this, text);\r\n}\r\nextend(CommentFilter, Filter, {\r\n});\r\n\r\nfunction ActiveFilter(text, domains)\r\n{\r\n    Filter.call(this, text);\r\n    this.domainSource = domains;\r\n}\r\nextend(ActiveFilter, Filter, {\r\n    domainSource: null,\r\n    domainSeparator: null,\r\n    ignoreTrailingDot: true,\r\n    domainSourceIsUpperCase: false,\r\n    getDomains: function()\r\n    {\r\n        var prop = getOwnPropertyDescriptor(this, \"domains\");\r\n        if (prop)\r\n        {\r\n            return prop;\r\n        }\r\n        var domains = null;\r\n        if (this.domainSource)\r\n        {\r\n            var source = this.domainSource;\r\n            if (!this.domainSourceIsUpperCase)\r\n            {\r\n                source = source.toUpperCase();\r\n            }\r\n            var list = source.split(this.domainSeparator);\r\n            if (list.length == 1 && (list[0]).charAt(0) != \"~\")\r\n            {\r\n                domains = createDict();\r\n                domains[\"\"] = false;\r\n                if (this.ignoreTrailingDot)\r\n                {\r\n                    list[0] = list[0].replace(/\\.+$/, \"\");\r\n                }\r\n                domains[list[0]] = true;\r\n            }\r\n            else\r\n            {\r\n                var hasIncludes = false;\r\n                for (var i = 0; i < list.length; i++)\r\n                {\r\n                    var domain = list[i];\r\n                    if (this.ignoreTrailingDot)\r\n                    {\r\n                        domain = domain.replace(/\\.+$/, \"\");\r\n                    }\r\n                    if (domain == \"\")\r\n                    {\r\n                        continue;\r\n                    }\r\n                    var include;\r\n                    if (domain.charAt(0) == \"~\")\r\n                    {\r\n                        include = false;\r\n                        domain = domain.substr(1);\r\n                    }\r\n                    else\r\n                    {\r\n                        include = true;\r\n                        hasIncludes = true;\r\n                    }\r\n                    if (!domains)\r\n                    {\r\n                        domains = createDict();\r\n                    }\r\n                    domains[domain] = include;\r\n                }\r\n                domains[\"\"] = !hasIncludes;\r\n            }\r\n            this.domainSource = null;\r\n        }\r\n        return this.domains;\r\n    },\r\n    sitekeys: null,\r\n    isActiveOnDomain: function(docDomain, sitekey)\r\n    {\r\n        if (this.getSitekeys() && (!sitekey || this.getSitekeys().indexOf(sitekey.toUpperCase()) < 0))\r\n        {\r\n            return false;\r\n        }\r\n        if (!this.getDomains())\r\n        {\r\n            return true;\r\n        }\r\n        if (!docDomain)\r\n        {\r\n            return this.getDomains()[\"\"];\r\n        }\r\n        if (this.ignoreTrailingDot)\r\n        {\r\n            docDomain = docDomain.replace(/\\.+$/, \"\");\r\n        }\r\n        docDomain = docDomain.toUpperCase();\r\n        while (true)\r\n        {\r\n            if (docDomain in this.getDomains())\r\n            {\r\n                return this.domains[docDomain];\r\n            }\r\n            var nextDot = docDomain.indexOf(\".\");\r\n            if (nextDot < 0)\r\n            {\r\n                break;\r\n            }\r\n            docDomain = docDomain.substr(nextDot + 1);\r\n        }\r\n        return this.domains[\"\"];\r\n    },\r\n    isActiveOnlyOnDomain: function(docDomain)\r\n    {\r\n        if (!docDomain || !this.getDomains() || this.getDomains()[\"\"])\r\n        {\r\n            return false;\r\n        }\r\n        if (this.ignoreTrailingDot)\r\n        {\r\n            docDomain = docDomain.replace(/\\.+$/, \"\");\r\n        }\r\n        docDomain = docDomain.toUpperCase();\r\n        for (var domain in this.getDomains())\r\n        {\r\n            if (this.domains[domain] && domain != docDomain && (domain.length <= docDomain.length || domain.indexOf(\".\" + docDomain) != domain.length - docDomain.length - 1))\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n        return true;\r\n    }\r\n});\r\n\r\nfunction RegExpFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys)\r\n{\r\n    ActiveFilter.call(this, text, domains, sitekeys);\r\n    if (contentType != null)\r\n    {\r\n        this.contentType = contentType;\r\n    }\r\n    if (matchCase)\r\n    {\r\n        this.matchCase = matchCase;\r\n    }\r\n    if (thirdParty != null)\r\n    {\r\n        this.thirdParty = thirdParty;\r\n    }\r\n    if (sitekeys != null)\r\n    {\r\n        this.sitekeySource = sitekeys;\r\n    }\r\n    if (regexpSource.length >= 2 && regexpSource.charAt(0) == \"/\" && regexpSource.charAt(regexpSource.length - 1) == \"/\")\r\n    {\r\n        var regexp = new RegExp(regexpSource.substr(1, regexpSource.length - 2), this.matchCase ? \"\" : \"i\");\r\n        this.regexp = regexp;\r\n    }\r\n    else\r\n    {\r\n        this.regexpSource = regexpSource;\r\n    }\r\n}\r\nextend(RegExpFilter, ActiveFilter, {\r\n    domainSourceIsUpperCase: true,\r\n    length: 1,\r\n    domainSeparator: \"|\",\r\n    regexpSource: null,\r\n    getRegexp: function()\r\n    {\r\n        var prop = getOwnPropertyDescriptor(this, \"regexp\");\r\n        if (prop)\r\n        {\r\n            return prop;\r\n        }\r\n        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(/(\\.\\*)$/, \"\");\r\n        var regexp = new RegExp(source, this.matchCase ? \"\" : \"i\");\r\n        this.regexp = regexp;\r\n        return regexp;\r\n    },\r\n    contentType: 2147483647,\r\n    matchCase: false,\r\n    thirdParty: null,\r\n    sitekeySource: null,\r\n    getSitekeys: function()\r\n    {\r\n        var prop = getOwnPropertyDescriptor(this, \"sitekeys\");\r\n        if (prop)\r\n        {\r\n            return prop;\r\n        }\r\n        var sitekeys = null;\r\n        if (this.sitekeySource)\r\n        {\r\n            sitekeys = this.sitekeySource.split(\"|\");\r\n            this.sitekeySource = null;\r\n        }\r\n        this.sitekeys = sitekeys;\r\n        return this.sitekeys;\r\n    },\r\n    matches: function(location, contentType, docDomain, thirdParty, sitekey)\r\n    {\r\n        if (this.getRegexp().test(location) && this.isActiveOnDomain(docDomain, sitekey))\r\n        {\r\n            return true;\r\n        }\r\n        return false;\r\n    }\r\n});\r\nRegExpFilter.prototype[\"0\"] = \"#this\";\r\nRegExpFilter.fromText = function(text)\r\n{\r\n    var blocking = true;\r\n    var origText = text;\r\n    if (text.indexOf(\"@@\") == 0)\r\n    {\r\n        blocking = false;\r\n        text = text.substr(2);\r\n    }\r\n    var contentType = null;\r\n    var matchCase = null;\r\n    var domains = null;\r\n    var sitekeys = null;\r\n    var thirdParty = null;\r\n    var collapse = null;\r\n    var options;\r\n    var match = text.indexOf(\"$\") >= 0 ? Filter.optionsRegExp.exec(text) : null;\r\n    if (match)\r\n    {\r\n        options = match[1].toUpperCase().split(\",\");\r\n        text = match.input.substr(0, match.index);\r\n        for (var _loopIndex6 = 0; _loopIndex6 < options.length; ++_loopIndex6)\r\n        {\r\n            var option = options[_loopIndex6];\r\n            var value = null;\r\n            var separatorIndex = option.indexOf(\"=\");\r\n            if (separatorIndex >= 0)\r\n            {\r\n                value = option.substr(separatorIndex + 1);\r\n                option = option.substr(0, separatorIndex);\r\n            }\r\n            option = option.replace(/-/, \"_\");\r\n            if (option in RegExpFilter.typeMap)\r\n            {\r\n                if (contentType == null)\r\n                {\r\n                    contentType = 0;\r\n                }\r\n                contentType |= RegExpFilter.typeMap[option];\r\n            }\r\n            else if (option.charAt(0) == \"~\" && option.substr(1) in RegExpFilter.typeMap)\r\n            {\r\n                if (contentType == null)\r\n                {\r\n                    contentType = RegExpFilter.prototype.contentType;\r\n                }\r\n                contentType &= ~RegExpFilter.typeMap[option.substr(1)];\r\n            }\r\n            else if (option == \"MATCH_CASE\")\r\n            {\r\n                matchCase = true;\r\n            }\r\n            else if (option == \"~MATCH_CASE\")\r\n            {\r\n                matchCase = false;\r\n            }\r\n            else if (option == \"DOMAIN\" && typeof value != \"undefined\")\r\n            {\r\n                domains = value;\r\n            }\r\n            else if (option == \"THIRD_PARTY\")\r\n            {\r\n                thirdParty = true;\r\n            }\r\n            else if (option == \"~THIRD_PARTY\")\r\n            {\r\n                thirdParty = false;\r\n            }\r\n            else if (option == \"COLLAPSE\")\r\n            {\r\n                collapse = true;\r\n            }\r\n            else if (option == \"~COLLAPSE\")\r\n            {\r\n                collapse = false;\r\n            }\r\n            else if (option == \"SITEKEY\" && typeof value != \"undefined\")\r\n            {\r\n                sitekeys = value;\r\n            }\r\n            else\r\n            {\r\n                return new InvalidFilter(origText, \"Unknown option \" + option.toLowerCase());\r\n            }\r\n        }\r\n    }\r\n    if (!blocking && (contentType == null || contentType & RegExpFilter.typeMap.DOCUMENT) && (!options || options.indexOf(\"DOCUMENT\") < 0) && !/^\\|?[\\w\\-]+:/.test(text))\r\n    {\r\n        if (contentType == null)\r\n        {\r\n            contentType = RegExpFilter.prototype.contentType;\r\n        }\r\n        contentType &= ~RegExpFilter.typeMap.DOCUMENT;\r\n    }\r\n    try\r\n    {\r\n        if (blocking)\r\n        {\r\n            return new BlockingFilter(origText, text, contentType, matchCase, domains, thirdParty, sitekeys, collapse);\r\n        }\r\n        else\r\n        {\r\n            return new WhitelistFilter(origText, text, contentType, matchCase, domains, thirdParty, sitekeys);\r\n        }\r\n    }\r\n    catch (e)\r\n    {\r\n        return new InvalidFilter(origText, e);\r\n    }\r\n};\r\nRegExpFilter.typeMap = {\r\n    OTHER: 1,\r\n    SCRIPT: 2,\r\n    IMAGE: 4,\r\n    STYLESHEET: 8,\r\n    OBJECT: 16,\r\n    SUBDOCUMENT: 32,\r\n    DOCUMENT: 64,\r\n    XBL: 1,\r\n    PING: 1,\r\n    XMLHTTPREQUEST: 2048,\r\n    OBJECT_SUBREQUEST: 4096,\r\n    DTD: 1,\r\n    MEDIA: 16384,\r\n    FONT: 32768,\r\n    BACKGROUND: 4,\r\n    POPUP: 268435456,\r\n    ELEMHIDE: 1073741824\r\n};\r\nRegExpFilter.prototype.contentType &= ~ (RegExpFilter.typeMap.ELEMHIDE | RegExpFilter.typeMap.POPUP);\r\n\r\nfunction BlockingFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys, collapse)\r\n{\r\n    RegExpFilter.call(this, text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys);\r\n    this.collapse = collapse;\r\n}\r\nextend(BlockingFilter, RegExpFilter, {\r\n    collapse: null\r\n});\r\n\r\nfunction WhitelistFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys)\r\n{\r\n    RegExpFilter.call(this, text, regexpSource, contentType, matchCase, domains, thirdParty, sitekeys);\r\n}\r\nextend(WhitelistFilter, RegExpFilter, {\r\n});\r\n\r\nfunction Matcher()\r\n{\r\n    this.clear();\r\n}\r\nMatcher.prototype = {\r\n    filterByKeyword: null,\r\n    keywordByFilter: null,\r\n    clear: function()\r\n    {\r\n        this.filterByKeyword = createDict();\r\n        this.keywordByFilter = createDict();\r\n    },\r\n    add: function(filter)\r\n    {\r\n        if (filter.text in this.keywordByFilter)\r\n        {\r\n            return;\r\n        }\r\n        var keyword = this.findKeyword(filter);\r\n        var oldEntry = this.filterByKeyword[keyword];\r\n        if (typeof oldEntry == \"undefined\")\r\n        {\r\n            this.filterByKeyword[keyword] = filter;\r\n        }\r\n        else if (oldEntry.length == 1)\r\n        {\r\n            this.filterByKeyword[keyword] = [oldEntry, filter];\r\n        }\r\n        else\r\n        {\r\n            oldEntry.push(filter);\r\n        }\r\n        this.keywordByFilter[filter.text] = keyword;\r\n    },\r\n    remove: function(filter)\r\n    {\r\n        if (!(filter.text in this.keywordByFilter))\r\n        {\r\n            return;\r\n        }\r\n        var keyword = this.keywordByFilter[filter.text];\r\n        var list = this.filterByKeyword[keyword];\r\n        if (list.length <= 1)\r\n        {\r\n            delete this.filterByKeyword[keyword];\r\n        }\r\n        else\r\n        {\r\n            var index = list.indexOf(filter);\r\n            if (index >= 0)\r\n            {\r\n                list.splice(index, 1);\r\n                if (list.length == 1)\r\n                {\r\n                    this.filterByKeyword[keyword] = list[0];\r\n                }\r\n            }\r\n        }\r\n        delete this.keywordByFilter[filter.text];\r\n    },\r\n    findKeyword: function(filter)\r\n    {\r\n        var result = \"\";\r\n        var text = filter.text;\r\n        if (Filter.regexpRegExp.test(text))\r\n        {\r\n            return result;\r\n        }\r\n        var match = Filter.optionsRegExp.exec(text);\r\n        if (match)\r\n        {\r\n            text = match.input.substr(0, match.index);\r\n        }\r\n        if (text.substr(0, 2) == \"@@\")\r\n        {\r\n            text = text.substr(2);\r\n        }\r\n        var candidates = text.toLowerCase().match(/[^a-z0-9%*][a-z0-9%]{3,}(?=[^a-z0-9%*])/g);\r\n        if (!candidates)\r\n        {\r\n            return result;\r\n        }\r\n        var hash = this.filterByKeyword;\r\n        var resultCount = 16777215;\r\n        var resultLength = 0;\r\n        for (var i = 0, l = candidates.length; i < l; i++)\r\n        {\r\n            var candidate = candidates[i].substr(1);\r\n            var count = candidate in hash ? hash[candidate].length : 0;\r\n            if (count < resultCount || count == resultCount && candidate.length > resultLength)\r\n            {\r\n                result = candidate;\r\n                resultCount = count;\r\n                resultLength = candidate.length;\r\n            }\r\n        }\r\n        return result;\r\n    },\r\n    hasFilter: function(filter)\r\n    {\r\n        return filter.text in this.keywordByFilter;\r\n    },\r\n    getKeywordForFilter: function(filter)\r\n    {\r\n        if (filter.text in this.keywordByFilter)\r\n        {\r\n            return this.keywordByFilter[filter.text];\r\n        }\r\n        else\r\n        {\r\n            return null;\r\n        }\r\n    },\r\n    _checkEntryMatch: function(keyword, location, contentType, docDomain, thirdParty, sitekey)\r\n    {\r\n        var list = this.filterByKeyword[keyword];\r\n        for (var i = 0; i < list.length; i++)\r\n        {\r\n            var filter = list[i];\r\n            if (filter == \"#this\")\r\n            {\r\n                filter = list;\r\n            }\r\n            if (filter.matches(location, contentType, docDomain, thirdParty, sitekey))\r\n            {\r\n                return filter;\r\n            }\r\n        }\r\n        return null;\r\n    },\r\n    matchesAny: function(location, contentType, docDomain, thirdParty, sitekey)\r\n    {\r\n        var candidates = location.toLowerCase().match(/[a-z0-9%]{3,}/g);\r\n        if (candidates === null)\r\n        {\r\n            candidates = [];\r\n        }\r\n        candidates.push(\"\");\r\n        for (var i = 0, l = candidates.length; i < l; i++)\r\n        {\r\n            var substr = candidates[i];\r\n            if (substr in this.filterByKeyword)\r\n            {\r\n                var result = this._checkEntryMatch(substr, location, contentType, docDomain, thirdParty, sitekey);\r\n                if (result)\r\n                {\r\n                    return result;\r\n                }\r\n            }\r\n        }\r\n        return null;\r\n    }\r\n};\r\n\r\nfunction CombinedMatcher()\r\n{\r\n    this.blacklist = new Matcher();\r\n    this.whitelist = new Matcher();\r\n    this.resultCache = createDict();\r\n}\r\nCombinedMatcher.maxCacheEntries = 1000;\r\nCombinedMatcher.prototype = {\r\n    blacklist: null,\r\n    whitelist: null,\r\n    resultCache: null,\r\n    cacheEntries: 0,\r\n    clear: function()\r\n    {\r\n        this.blacklist.clear();\r\n        this.whitelist.clear();\r\n        this.resultCache = createDict();\r\n        this.cacheEntries = 0;\r\n    },\r\n    add: function(filter)\r\n    {\r\n        if (filter instanceof WhitelistFilter)\r\n        {\r\n            this.whitelist.add(filter);\r\n        }\r\n        else\r\n        {\r\n            this.blacklist.add(filter);\r\n        }\r\n        if (this.cacheEntries > 0)\r\n        {\r\n            this.resultCache = createDict();\r\n            this.cacheEntries = 0;\r\n        }\r\n    },\r\n    remove: function(filter)\r\n    {\r\n        if (filter instanceof WhitelistFilter)\r\n        {\r\n            this.whitelist.remove(filter);\r\n        }\r\n        else\r\n        {\r\n            this.blacklist.remove(filter);\r\n        }\r\n        if (this.cacheEntries > 0)\r\n        {\r\n            this.resultCache = createDict();\r\n            this.cacheEntries = 0;\r\n        }\r\n    },\r\n    findKeyword: function(filter)\r\n    {\r\n        if (filter instanceof WhitelistFilter)\r\n        {\r\n            return this.whitelist.findKeyword(filter);\r\n        }\r\n        else\r\n        {\r\n            return this.blacklist.findKeyword(filter);\r\n        }\r\n    },\r\n    hasFilter: function(filter)\r\n    {\r\n        if (filter instanceof WhitelistFilter)\r\n        {\r\n            return this.whitelist.hasFilter(filter);\r\n        }\r\n        else\r\n        {\r\n            return this.blacklist.hasFilter(filter);\r\n        }\r\n    },\r\n    getKeywordForFilter: function(filter)\r\n    {\r\n        if (filter instanceof WhitelistFilter)\r\n        {\r\n            return this.whitelist.getKeywordForFilter(filter);\r\n        }\r\n        else\r\n        {\r\n            return this.blacklist.getKeywordForFilter(filter);\r\n        }\r\n    },\r\n    isSlowFilter: function(filter)\r\n    {\r\n        var matcher = filter instanceof WhitelistFilter ? this.whitelist : this.blacklist;\r\n        if (matcher.hasFilter(filter))\r\n        {\r\n            return !matcher.getKeywordForFilter(filter);\r\n        }\r\n        else\r\n        {\r\n            return !matcher.findKeyword(filter);\r\n        }\r\n    },\r\n    matchesAnyInternal: function(location, contentType, docDomain, thirdParty, sitekey)\r\n    {\r\n        var candidates = location.toLowerCase().match(/[a-z0-9%]{3,}/g);\r\n        if (candidates === null)\r\n        {\r\n            candidates = [];\r\n        }\r\n        candidates.push(\"\");\r\n        var blacklistHit = null;\r\n        for (var i = 0, l = candidates.length; i < l; i++)\r\n        {\r\n            var substr = candidates[i];\r\n            if (substr in this.whitelist.filterByKeyword)\r\n            {\r\n                var result = this.whitelist._checkEntryMatch(substr, location, contentType, docDomain, thirdParty, sitekey);\r\n                if (result)\r\n                {\r\n                    return result;\r\n                }\r\n            }\r\n            if (substr in this.blacklist.filterByKeyword && blacklistHit === null)\r\n            {\r\n                blacklistHit = this.blacklist._checkEntryMatch(substr, location, contentType, docDomain, thirdParty, sitekey);\r\n            }\r\n        }\r\n        return blacklistHit;\r\n    },\r\n    matchesAny: function(location, docDomain)\r\n    {\r\n        var key = location + \" \" + docDomain + \" \";\r\n        if (key in this.resultCache)\r\n        {\r\n            return this.resultCache[key];\r\n        }\r\n        var result = this.matchesAnyInternal(location, 0, docDomain, null, null);\r\n        if (this.cacheEntries >= CombinedMatcher.maxCacheEntries)\r\n        {\r\n            this.resultCache = createDict();\r\n            this.cacheEntries = 0;\r\n        }\r\n        this.resultCache[key] = result;\r\n        this.cacheEntries++;\r\n        return result;\r\n    }\r\n};\r\n\r\nvar userrulesMatcher = new CombinedMatcher();\r\nvar defaultMatcher = new CombinedMatcher();\r\n\r\nvar direct = 'DIRECT;';\r\n\r\nfor (var i = 0; i < userrules.length; i++) {\r\n    userrulesMatcher.add(Filter.fromText(userrules[i]));\r\n}\r\n\r\nfor (var i = 0; i < rules.length; i++) {\r\n    defaultMatcher.add(Filter.fromText(rules[i]));\r\n}\r\n\r\n// PAC has no v6 support, it sucks\r\nvar ip4Re = /^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$/\r\n\r\nvar privateNet = [\r\n    [\"10.0.0.0\", \"255.0.0.0\"],\r\n    [\"127.0.0.0\", \"255.0.0.0\"],\r\n    [\"172.16.0.0\", \"255.240.0.0\"],\r\n    [\"192.168.0.0\", \"255.255.0.0\"],\r\n]\r\n\r\nfunction FindProxyForURL(url, host) {\r\n    if (host.match(ip4Re)) {\r\n        for (var i = 0; i < privateNet.length; i++) {\r\n            if (isInNet(host, privateNet[i][0], privateNet[i][1])) return direct;\r\n        }\r\n    }\r\n    if (userrulesMatcher.matchesAny(url, host) instanceof BlockingFilter) {\r\n        return proxy;\r\n    }\r\n    if (userrulesMatcher.matchesAny(url, host) instanceof WhitelistFilter) {\r\n        return direct;\r\n    }\r\n    // Hack for Geosite, it provides a whitelist...\r\n    if (defaultMatcher.matchesAny(url, host) instanceof WhitelistFilter) {\r\n        return direct;\r\n    }\r\n    if (defaultMatcher.matchesAny(url, host) instanceof BlockingFilter) {\r\n        return proxy;\r\n    }\r\n    return direct;\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Data/i18n.csv",
    "content": "﻿en,ru-RU,zh-CN,zh-TW,ja,ko,fr\r\n#Restart program to apply translation,,,,,,\r\n#This is comment line,,,,,,\r\n#Always keep language name at head of file,,,,,,\r\n#Language name is output in log,,,,,,\r\n\"#You can find it by search \"\"Current language is:\"\"\",,,,,,\r\n#Please use UTF-8 with BOM encoding so we can edit it in Excel,,,,,,\r\n,,,,,,\r\nShadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks\r\n,,,,,,\r\n#Menu,,,,,,\r\n,,,,,,\r\nSystem Proxy,Системный прокси-сервер,系统代理,系統代理,システムプロキシ,시스템 프록시,Proxy système\r\nDisable,Отключен,禁用,禁用,無効,비활성화,Désactiver\r\nPAC,Сценарий настройки (PAC),PAC 模式,PAC 模式,PACモード,프록시 자동 구성 (PAC),PAC\r\nGlobal,Для всей системы,全局模式,全局模式,グローバルプロキシ,전역,Global\r\nServers,Серверы,服务器,伺服器,サーバー,서버,Serveurs\r\nEdit Servers...,Редактировать серверы…,编辑服务器...,編輯伺服器...,サーバーの編集...,서버 수정…,Éditer serveurs…\r\nOnline Config...,,在线配置...,線上配置...,,,\r\nStart on Boot,Автозагрузка,开机启动,開機啟動,システム起動時に実行,시스템 시작 시에 시작하기,Démarrage automatique\r\nAssociate ss:// Links,Ассоциированный ss:// Ссылки,关联 ss:// 链接,關聯 ss:// 鏈接,ss:// リンクの関連付け,ss:// 링크 연결,\r\nForward Proxy...,Прямой прокси…,正向代理设置...,正向 Proxy 設定...,フォワードプロキシの設定...,포워드 프록시,Forward-proxy…\r\nAllow other Devices to connect,Общий доступ к подключению,允许其他设备连入,允許其他裝置連入,他のデバイスからの接続を許可する,다른 기기에서 연결 허용,Autoriser d'autres appareils à se connecter\r\nLocal PAC,Локальный PAC,使用本地 PAC,使用本機 PAC,ローカル PAC,로컬 프록시 자동 구성,PAC local\r\nOnline PAC,Удаленный PAC,使用在线 PAC,使用線上 PAC,オンライン PAC,온라인 프록시 자동 구성,PAC en ligne\r\nEdit Local PAC File...,Редактировать локальный PAC…,编辑本地 PAC 文件...,編輯本機 PAC 檔案...,ローカル PAC ファイルの編集...,로컬 프록시 자동 구성 파일 수정,Modifier le fichier PAC local ...\r\nUpdate Local PAC from Geosite,Обновить локальный PAC из Geosite,从 Geosite 更新本地 PAC,從 Geosite 更新本機 PAC,Geosite からローカル PAC を更新,Geosite에서 로컬 프록시 자동 구성 파일 업데이트,Mettre à jour le PAC local à partir de Geosite\r\nEdit User Rule for Geosite...,Редактировать свои правила для Geosite,编辑 Geosite 的用户规则...,編輯 Geosite 的使用者規則...,ユーザールールの編集...,Geosite 사용자 수정,Modifier la règle utilisateur pour Geosite ...\r\nSecure Local PAC,Безопасный URL локального PAC,保护本地 PAC,安全本機 PAC,ローカル PAC を保護,로컬 프록시 자동 구성 파일 암호화,Sécuriser PAC local\r\nRegenerate local PAC on version update,,版本更新后重新生成本地 PAC,版本更新後重新生成本地 PAC,,,\r\nCopy Local PAC URL,Копировать URL локального PAC,复制本地 PAC 网址,複製本機 PAC 網址,ローカル PAC URL をコピー,로컬 프록시 자동 구성 파일 URL 복사,Copier l'URL du PAC local\r\nShare Server Config...,Поделиться конфигурацией сервера…,分享服务器配置...,分享伺服器設定檔...,サーバーの設定を共有...,서버 설정 공유,Partager la configuration du serveur ...\r\nScan QRCode from Screen...,Сканировать QRCode с экрана…,扫描屏幕上的二维码...,掃描螢幕上的 QR 碼...,画面から QR コードをスキャン...,화면에서 QR코드 스캔,Scanner le QRCode à partir de l'écran ...\r\nImport URL from Clipboard...,Импорт адреса из буфера обмена…,从剪贴板导入URL...,從剪貼簿匯入 URL...,クリップボードから URL をインポート...,클립보드에서 URL 가져오기…,Importer l'URL du presse-papiers ...\r\nAvailability Statistics,Статистика доступности,统计可用性,統計可用性,可用性の統計,가용성 통계,Statistiques de disponibilité\r\nShow Logs...,Показать журнал…,显示日志...,顯示記錄檔...,ログの表示...,로그 보기…,Afficher les journaux ...\r\nVerbose Logging,Подробный журнал,详细记录日志,詳細資訊記錄,詳細なログを記録,자세한 로깅 사용,Journalisation détaillée\r\nUpdates...,Обновления…,更新...,更新...,アップデート...,업데이트…,Mettre à jour…\r\nCheck for Updates...,Проверить обновления…,检查更新,檢查更新,アップデートを確認...,업데이트 확인하기…,Vérifier les mises à jour ...\r\nCheck for Updates at Startup,Проверять при запуске,启动时检查更新,啟動時檢查更新,起動時にアップデートを確認,시스템 시작 시 업데이트 확인하기,Vérifier les mises à jour au démarrage\r\nCheck Pre-release Version,Проверять предрелизные версии,检查测试版更新,檢查發行前版本更新,ベータ版のアップデートも確認,개발 버전 업데이트 확인하기,Vérifier la version préliminaire\r\nEdit Hotkeys...,Горячие клавиши…,编辑快捷键...,編輯快速鍵...,ホットキーの編集...,단축키 수정…,Modifier les raccourcis clavier ...\r\nAbout...,О программе…,关于...,關於...,Shadowsocks について...,정보…,A propos\r\nHelp,Помощь,帮助,說明,ヘルプ,도움말,Aide\r\nQuit,Выход,退出,結束,終了,종료,Quitter\r\nEdit Servers,Редактирование серверов,编辑服务器,編輯伺服器,サーバーの編集,서버 수정,Éditer serveurs\r\nLoad Balance,Балансировка нагрузки,负载均衡,負載平衡,サーバーロードバランス,로드밸런싱,Répartition de charge\r\nHigh Availability,Высокая доступность,高可用,高可用性,高可用性,고가용성,Haute disponibilité\r\nShow Plugin Output,События плагинов в журнале,显示插件输出,,プラグインの出力情報を表示,플러그인 출력 보이기,Afficher la sortie du plugin\r\nWrite translation template,Создать шаблон для перевода,写入翻译模板,,翻訳テンプレートファイルを書き込む,번역 템플릿 쓰기,Écrire un modèle de traduction\r\n,,,,,,\r\n# Config Form,,,,,,\r\n,,,,,,\r\nStatistics configuration,Настройки статистики,统计配置,,統計の設定,통계 설정,Configuration des statistiques\r\n&Add,Добавить,添加(&A),新增 (&A),新規 (&A),추가 (&A),Ajouter\r\n&Delete,Удалить,删除(&D),移除 (&D),削除 (&D),삭제 (&D),Supprimer\r\nDupli&cate,Дублир-ть,复制(&C),複製 (&C),コピー (&C),복제 (&C),Dupliquer\r\nServer,Сервер,服务器,伺服器,サーバー,서버,Serveur\r\nServer IP,IP-адрес,服务器地址,伺服器位址,サーバーアドレス,서버 IP,Serveur IP\r\nServer Port,Порт,服务器端口,伺服器連接埠,サーバーポート,서버 포트,Port de serveur\r\nPassword,Пароль,密码,密碼,パスワード,비밀번호,Mot de passe\r\nShow Password,Показать пароль,显示密码,顯示密碼,パスワードを表示する,비밀번호 보이기,Montrer le mot de passe\r\nEncryption,Шифрование,加密,加密,暗号化,암호화,Chiffrement\r\nPlugin Program,Плагин,插件程序,外掛程式,プラグインプログラム,플러그인 프로그램,Programme de plugin\r\nPlugin Options,Опции плагина,插件选项,外掛程式選項,プラグインのオプション,플러그인 설정,Options de plugin\r\nNeed Plugin Argument,Требуются аргументы,需要命令行参数,,コマンドライン引数を有効にする,플러그인 인자가 필요함,Besoin d'un argument de plugin\r\nPlugin Arguments,Аргументы,插件参数,外掛程式參數,プラグインの引数,플러그인 인자,Arguments du plugin\r\nProxy Port,Порт прокси,代理端口,Proxy 連接埠,プロキシポート,프록시 포트,Port proxy\r\nPortable Mode,Переносимый режим,便携模式,便攜模式,ポータブルモード,포터블 모드,Mode portable\r\nRestart required,Требуется перезапуск программы,需要重新启动SS,需要重新啟動SS,再起動が必要,재시작이 필요합니다,Redémarrage nécessaire\r\nRemarks,Примечания,备注,註解,付記,알림,Remarques\r\nTimeout(Sec),Таймаут(сек),超时(秒),逾時 (秒),タイムアウト (秒),시간 초과 (초),Délai d'attente(sec)\r\nOK,ОК,确定,確定,OK,확인,OK\r\nCancel,Отмена,取消,取消,キャンセル,취소,Annuler\r\nApply,Применить,应用,應用,適用,적용,Appliquer\r\nNew server,Новый сервер,未配置的服务器,新伺服器,新規サーバー,새 서버,Nouveau serveur\r\nMove &Up,Выше,上移(&U),上移 (&U),上に移動 (&U),위로 (&U),Monter\r\nMove D&own,Ниже,下移(&O),下移 (&O),下に移動 (&O),아래로 (&O),Descendre\r\ndeprecated,Устаревшее,不推荐,不推薦,非推奨,더 이상 사용되지 않음,Obsolète\r\n\"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}\"\r\n,,,,,,\r\n# Log Form,,,,,,\r\n,,,,,,\r\n&File,Файл,文件(&F),檔案 (&F),ファイル (&F),파일 (&F),Fichier\r\n&Open Location,Расположение файла,在资源管理器中打开(&O),在檔案總管中開啟 (&O),ファイルの場所を開く (&O),위치 열기 (&O),Ouvrier\r\nE&xit,Выход,退出(&X),結束 (&X),終了 (&X),종료 (&X),Quitter\r\n&View,Вид,视图(&V),檢視 (&V),表示 (&V),보기 (&V),Afficher\r\n&Clear Logs,Очистить журнал,清空日志(&C),清除記錄檔 (&C),ログの削除 (&C),로그 초기화 (&C),Effacer les journaux\r\nChange &Font,Шрифт…,设置字体(&F),變更字型 (&F),フォント (&F),글꼴 변경 (&F),Définir la police\r\n&Wrap Text,Перенос строк,自动换行(&W),自動換行 (&W),右端で折り返す (&W),텍스트 감싸기 (&W),Retour à la ligne\r\n&Top Most,Поверх всех окон,置顶(&T),置頂 (&T),常に最前面に表示 (&T),상단 우선 (Top Most) (&T),Metter en haut\r\n&Show Toolbar,Панель инструментов,显示工具栏(&S),顯示工具列 (&S),ツールバーの表示 (&S),툴바 보여주기 (&S),Afficher la barre d'outils\r\nLog Viewer,Просмотр журнала,日志查看器,記錄檔檢視器,ログビューア,로그 뷰어,Visionneuse de journaux\r\nInbound,Входящая,入站,輸入,受信,\"인바운드 (Rx, 다운로드)\",Entrant\r\nOutbound,Исходящая,出站,輸出,送信,\"아웃바운드 (Tx, 업로드)\",Sortant\r\n,,,,,,\r\n# QRCode Form,,,,,,\r\n,,,,,,\r\nQRCode and URL,QRCode и URL,二维码与 URL,QR 碼與 URL,QR コードと URL,QR코드와 URL,QRCode et URL\r\n,,,,,,\r\n# PAC Url Form,,,,,,\r\n,,,,,,\r\nEdit Online PAC URL,Изменение URL удаленного PAC,编辑在线 PAC 网址,編輯線上 PAC 網址,オンライン PAC URL の編集,온라인 프록시 자동 구성 URL 수정,Modifier l'URL du PAC en ligne\r\nEdit Online PAC URL...,Редактировать URL удаленного PAC…,编辑在线 PAC 网址...,編輯線上 PAC 網址...,オンライン PAC URL の編集...,온라인 프록시 자동 구성 URL 수정…,Modifier l'URL du PAC en ligne ...\r\nPlease input PAC Url,Введите URL адрес для PAC-файла,请输入 PAC 网址,請輸入 PAC 網址,PAC URLを入力して下さい,프록시 자동 구성 URL을 입력하세요,Veuillez saisir l'URL PAC\r\n,,,,,,\r\n# Messages,,,,,,\r\n,,,,,,\r\nShadowsocks Error: {0},Ошибка Shadowsocks: {0},Shadowsocks 错误: {0},Shadowsocks 錯誤: {0},Shadowsocks エラー: {0},Shadowsocks 오류: {0},Erreur shadowsocks: {0}\r\nPort {0} already in use,Порт {0} уже используется,端口 {0} 已被占用,連接埠號碼 {0} 已被使用,ポート番号 {0} は既に使用されています。,{0}번 포트는 이미 사용 중입니다.,Port {0} déjà utilisé\r\nPort {0} is reserved by system,Порт {0} зарезервирован системой,端口 {0} 是系统保留端口,連接埠號碼 {0} 由系統保留, ポート番号 {0} はシステムによって予約されています,{0}번 포트는 시스템에서 사용 중입니다.,Port {0} réservé par le système\r\nInvalid server address,Неверный адрес сервера,非法服务器地址,無效伺服器位址,サーバーアドレスが無効です。,올바르지 않은 서버 주소입니다.,Adresse de serveur non valide\r\nIllegal port number format,Неверный числовой формат порта,非法端口格式,無效連接埠號碼格式,ポート番号のフォーマットが無効です。,올바르지 않은 포트 번호 형식입니다.,Format de numéro de port illégal\r\nIllegal timeout format,Неверный формат таймаута,非法超时格式,無效逾時格式,タイムアウト値のフォーマットが無効です。,올바르지 않은 시간 초과 형식입니다.,Format de délai d'attente illégal\r\nServer IP can not be blank,IP-адрес сервера не может быть пустым,服务器 IP 不能为空,伺服器 IP 不能為空,サーバー IP が指定されていません。,서버 IP는 비어있으면 안됩니다.,L'adresse IP du serveur ne peut pas être vide\r\nPassword can not be blank,Пароль не может быть пустым,密码不能为空,密碼不能為空,パスワードが指定されていません。,비밀번호는 비어있으면 안됩니다.,Le mot de passe ne peut pas être vide\r\nPort out of range,Порт выходит за допустимый диапазон,端口超出范围,連接埠號碼超出範圍,ポート番号は範囲外です。,올바른 포트 범위가 아닙니다.,Port hors de portée\r\nPort can't be 8123,Адрес порта 8123 не может быть использован,端口不能为 8123,連接埠號碼不能為 8123,8123 番以外のポート番号を指定して下さい。,8123번 포트는 사용할 수 없습니다.,Le port ne peut pas être 8123\r\nNo update is available,Обновлений не обнаружено,没有可用的更新,沒有可用的更新,お使いのバージョンは最新です。,사용 가능한 업데이트가 없습니다.,Aucune mise à jour n'est disponible\r\nShadowsocks is here,Shadowsocks находится здесь,Shadowsocks 在这里,Shadowsocks 在這裡,Shadowsocks はここです。,Shadowsocks는 여기에 있습니다,Veuillez trouver Shadowsocks ici\r\nYou can turn on/off Shadowsocks in the context menu,Вы можете управлять Shadowsocks из контекстного меню,可以在右键菜单中开关 Shadowsocks,可以在右鍵選項單中開關 Shadowsocks,コンテキストメニューを使って、Shadowsocks を有効または無効にすることができます。,프로그램 메뉴에서 Shadowsocks를 끄고 켤 수 있습니다.,Vous pouvez activer / désactiver Shadowsocks dans le menu contextuel\r\nSystem Proxy Enabled,Системный прокси включен,系统代理已启用,系統 Proxy 已啟用,システム プロキシが有効です。,시스템 프록시가 활성화되었습니다.,Proxy système activé\r\nSystem Proxy Disabled,Системный прокси отключен,系统代理未启用,系統 Proxy 未啟用,システム プロキシが無効です。,시스템 프록시가 비활성화되었습니다.,Proxy système désactivé\r\nFailed to update PAC file ,Не удалось обновить PAC файл,更新 PAC 文件失败,更新 PAC 檔案失敗,PAC の更新に失敗しました。,프록시 자동 구성 파일을 업데이트하는데 실패했습니다.,Impossible de mettre à jour le fichier PAC\r\nPAC updated,PAC файл обновлен,更新 PAC 成功,更新 PAC 成功,PAC を更新しました。,프록시 자동 구성 파일이 업데이트되었습니다.,PAC mis à jour\r\nNo 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.\r\nNo 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.\r\nShadowsocks is already running.,Shadowsocks уже запущен.,Shadowsocks 已经在运行。,Shadowsocks 已經在執行。,Shadowsocks 実行中,Shadowsocks가 이미 실행 중입니다.,Shadowsocks est déjà en cours d'exécution.\r\nFind Shadowsocks icon in your notify tray.,Значок Shadowsocks можно найти в области уведомлений.,请在任务栏里寻找 Shadowsocks 图标。,請在工作列裡尋找 Shadowsocks 圖示。,通知領域には Shadowsocks のアイコンがあります。,트레이에서 Shadowsocks를 찾아주세요.,Trouvez l'icône Shadowsocks dans votre barre de notification.\r\n\"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.\"\r\nInvalid QR Code content: {0},,无效二维码内容: {0},無效二維碼內容: {0},,,\r\nFailed to update registry,Не удалось обновить запись в реестре,无法修改注册表,無法修改登錄檔,レジストリの更新に失敗しました。,레지스트리를 업데이트하는데에 실패했습니다.,Impossible de mettre à jour de la base de registre\r\nImport from URL: {0} ?,импортировать из адреса: {0} ?,从URL导入: {0} ?,從URL匯入: {0} ?,{0}：このURLからインポートしますか？,,\r\nSuccessfully imported from {0},Успешно импортировано из {0},导入成功：{0},導入成功：{0},{0}：インポートしました。,,\r\nFailed to import. Please check if the link is valid.,,导入失败，请检查链接是否有效。,導入失敗，請檢查鏈接是否有效。,インポートに失敗しました。リンクの有効性を確認してください。,,\r\nWarning: 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 移除，请及时更新你的链接。,,,,\r\nSystem Proxy On: ,Системный прокси:,系统代理已启用：,系統 Proxy 已啟用：,システム プロキシが有効：,시스템 프록시 활성화됨: ,Proxy système activé:\r\nRunning: Port {0},Запущен на порту {0},正在运行：端口 {0},正在執行：連接埠號碼 {0},実行中：ポート {0},실행 중: 포트 {0}번,En cours d'exécution: port {0}\r\n\"Unexpected error, shadowsocks will exit. Please report to\",\"Непредвиденная ошибка, пожалуйста сообщите на\",非预期错误，Shadowsocks将退出。请提交此错误到,非預期錯誤，Shadowsocks 將結束。請報告此錯誤至,予想外のエラーが発生したため、Shadowsocks を終了します。詳しくは下記までお問い合わせ下さい：,알 수 없는 오류로 Shadowsocks가 종료될 것입니다. 오류를 여기로 제보해주세요:,Shadowsocks va quitter en présence d/érreur inattendue. Veuillez signaler à\r\n\"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.\"\r\n\"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.\"\r\nProxy request failed,Не удалось выполнить запрос,代理请求失败,Proxy 要求失敗,プロキシリクエストが失敗しました。,프록시 요청에 실패했습니다.,Échec de la demande de proxy\r\nProxy handshake failed,Не удалось выполнить хэндшейк,代理握手失败,Proxy 交握失敗,プロキシ ハンドシェイクに失敗しました。,프록시 핸드쉐이크에 실패했습니다.,Échec de la prise de contact par proxy\r\nRegister hotkey failed,Не удалось применить настройки горячих клавиш,注册快捷键失败,註冊快速鍵失敗,ホットキーの登錄に失敗しました。,단축키 등록에 실패했습니다.,Échec de l'enregistrement du raccourci clavier\r\nCannot parse hotkey: {0},Не удалось распознать следующие горячие клавиши: {0},解析快捷键失败: {0},剖析快速鍵失敗: {0},ホットキーを解析できません: {0},단축키를 해석할 수 없습니다: {0},Impossible d'analyser le raccourci clavier: {0}\r\n\"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}\"\r\nCannot find the plugin program file,Файл плагина не найден,找不到插件程序文件,找不到外掛程式文件,プラグインプログラムが見つかりません,플러그인 프로그램 파일을 찾을 수 없습니다.,Impossible de trouver le fichier du programme du plugin\r\n,,,,,,\r\nOperation failure,Операция завершилась неудачей,操作失败,,操作に失敗しました,작업에 실패했습니다.,Operation failure\r\nAuto save failed,Автоматическое сохранение не удалось,自动保存失败,,オートセーブに失敗しました,자동 저장에 실패했습니다.,Échec de l'enregistrement automatique\r\nWhether to discard unconfigured servers,Внесенные изменения будут утеряны,是否丢弃未配置的服务器,,未設定のサーバーを破棄しますか,구성되지 않은 서버 설정 변경 사항을 폐기하시겠습니까?,Eliminer les serveurs non configurés ou non\r\n\"Invalid server address, Cannot automatically save or discard changes\",Неверный адрес сервера. Невозможно сохранить или отменить изменения,非法服务器地址，无法自动保存，是否丢弃修改,,サーバーアドレスが無効なため、オートセーブできません。変更を破棄しますか,\"서버 주소가 올바르지 않아 자동 저장 할 수 없습니다, 변경 사항을 폐기하시겠습니까?\",\"Adresse de serveur invalide, impossible d'enregistrer ou d'annuler automatiquement les modifications\"\r\n\"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\"\r\n\"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\"\r\n\"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\"\r\n,,,,タイムアウト値のフォーマットが無効なため、オートセーブできません。変更を破棄しますか,,\r\n\"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?\r\n\"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\"\r\n"
  },
  {
    "path": "shadowsocks-csharp/Data/privoxy_conf.txt",
    "content": "listen-address __PRIVOXY_BIND_IP__:__PRIVOXY_BIND_PORT__\r\ntoggle 0\r\nlogfile ss_privoxy.log\r\nshow-on-task-bar 0\r\nactivity-animation 0\r\nforward-socks5 / __SOCKS_HOST__:__SOCKS_PORT__ .\r\nmax-client-connections 2048\r\nhide-console\r\n"
  },
  {
    "path": "shadowsocks-csharp/Data/user-rule.txt",
    "content": "﻿! Put user rules line by line in this file.\r\n! See https://adblockplus.org/en/filter-cheatsheet\r\n"
  },
  {
    "path": "shadowsocks-csharp/Encryption/AEAD/AEADEncryptor.cs",
    "content": "﻿using NLog;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics;\r\nusing System.Net;\r\nusing System.Text;\r\nusing Shadowsocks.Encryption.CircularBuffer;\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Encryption.Exception;\r\n\r\nnamespace Shadowsocks.Encryption.AEAD\r\n{\r\n    public abstract class AEADEncryptor\r\n        : EncryptorBase\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n        // We are using the same saltLen and keyLen\r\n        private const string Info = \"ss-subkey\";\r\n        private static readonly byte[] InfoBytes = Encoding.ASCII.GetBytes(Info);\r\n\r\n        // for UDP only\r\n        protected static byte[] _udpTmpBuf = new byte[65536];\r\n\r\n        // every connection should create its own buffer\r\n        private ByteCircularBuffer _encCircularBuffer = new ByteCircularBuffer(MAX_INPUT_SIZE * 2);\r\n        private ByteCircularBuffer _decCircularBuffer = new ByteCircularBuffer(MAX_INPUT_SIZE * 2);\r\n\r\n        public const int CHUNK_LEN_BYTES = 2;\r\n        public const uint CHUNK_LEN_MASK = 0x3FFFu;\r\n\r\n        protected Dictionary<string, EncryptorInfo> ciphers;\r\n\r\n        protected string _method;\r\n        protected int _cipher;\r\n        // internal name in the crypto library\r\n        protected string _innerLibName;\r\n        protected EncryptorInfo CipherInfo;\r\n        protected static byte[] _Masterkey = null;\r\n        protected byte[] _sessionKey;\r\n        protected int keyLen;\r\n        protected int saltLen;\r\n        protected int tagLen;\r\n        protected int nonceLen;\r\n\r\n        protected byte[] _encryptSalt;\r\n        protected byte[] _decryptSalt;\r\n\r\n        protected object _nonceIncrementLock = new object();\r\n        protected byte[] _encNonce;\r\n        protected byte[] _decNonce;\r\n        // Is first packet\r\n        protected bool _decryptSaltReceived;\r\n        protected bool _encryptSaltSent;\r\n\r\n        // Is first chunk(tcp request)\r\n        protected bool _tcpRequestSent;\r\n\r\n        public AEADEncryptor(string method, string password)\r\n            : base(method, password)\r\n        {\r\n            InitEncryptorInfo(method);\r\n            InitKey(password);\r\n            // Initialize all-zero nonce for each connection\r\n            _encNonce = new byte[nonceLen];\r\n            _decNonce = new byte[nonceLen];\r\n        }\r\n\r\n        protected abstract Dictionary<string, EncryptorInfo> getCiphers();\r\n\r\n        protected void InitEncryptorInfo(string method)\r\n        {\r\n            method = method.ToLower();\r\n            _method = method;\r\n            ciphers = getCiphers();\r\n            CipherInfo = ciphers[_method];\r\n            _innerLibName = CipherInfo.InnerLibName;\r\n            _cipher = CipherInfo.Type;\r\n            if (_cipher == 0) {\r\n                throw new System.Exception(\"method not found\");\r\n            }\r\n            keyLen = CipherInfo.KeySize;\r\n            saltLen = CipherInfo.SaltSize;\r\n            tagLen = CipherInfo.TagSize;\r\n            nonceLen = CipherInfo.NonceSize;\r\n        }\r\n\r\n        protected void InitKey(string password)\r\n        {\r\n            byte[] passbuf = Encoding.UTF8.GetBytes(password);\r\n            // init master key\r\n            if (_Masterkey == null) _Masterkey = new byte[keyLen];\r\n            if (_Masterkey.Length != keyLen) Array.Resize(ref _Masterkey, keyLen);\r\n            DeriveKey(passbuf, _Masterkey, keyLen);\r\n            // init session key\r\n            if (_sessionKey == null) _sessionKey = new byte[keyLen];\r\n        }\r\n\r\n        public void DeriveKey(byte[] password, byte[] key, int keylen)\r\n        {\r\n            byte[] result = new byte[password.Length + MD5_LEN];\r\n            int i = 0;\r\n            byte[] md5sum = null;\r\n            while (i < keylen)\r\n            {\r\n                if (i == 0)\r\n                {\r\n                    md5sum = MbedTLS.MD5(password);\r\n                }\r\n                else\r\n                {\r\n                    Array.Copy(md5sum, 0, result, 0, MD5_LEN);\r\n                    Array.Copy(password, 0, result, MD5_LEN, password.Length);\r\n                    md5sum = MbedTLS.MD5(result);\r\n                }\r\n                Array.Copy(md5sum, 0, key, i, Math.Min(MD5_LEN, keylen - i));\r\n                i += MD5_LEN;\r\n            }\r\n        }\r\n\r\n        public void DeriveSessionKey(byte[] salt, byte[] masterKey, byte[] sessionKey)\r\n        {\r\n            int ret = MbedTLS.hkdf(salt, saltLen, masterKey, keyLen, InfoBytes, InfoBytes.Length, sessionKey,\r\n                keyLen);\r\n            if (ret != 0) throw new System.Exception(\"failed to generate session key\");\r\n        }\r\n\r\n        protected void IncrementNonce(bool isEncrypt)\r\n        {\r\n            lock (_nonceIncrementLock) {\r\n                Sodium.sodium_increment(isEncrypt ? _encNonce : _decNonce, nonceLen);\r\n            }\r\n        }\r\n\r\n        public virtual void InitCipher(byte[] salt, bool isEncrypt, bool isUdp)\r\n        {\r\n            if (isEncrypt) {\r\n                _encryptSalt = new byte[saltLen];\r\n                Array.Copy(salt, _encryptSalt, saltLen);\r\n            } else {\r\n                _decryptSalt = new byte[saltLen];\r\n                Array.Copy(salt, _decryptSalt, saltLen);\r\n            }\r\n            logger.Dump(\"Salt\", salt, saltLen);\r\n        }\r\n\r\n        public static void randBytes(byte[] buf, int length) { RNG.GetBytes(buf, length); }\r\n\r\n        public abstract void cipherEncrypt(byte[] plaintext, uint plen, byte[] ciphertext, ref uint clen);\r\n\r\n        public abstract void cipherDecrypt(byte[] ciphertext, uint clen, byte[] plaintext, ref uint plen);\r\n\r\n        #region TCP\r\n\r\n        public override void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength)\r\n        {\r\n            Debug.Assert(_encCircularBuffer != null, \"_encCircularBuffer != null\");\r\n\r\n            _encCircularBuffer.Put(buf, 0, length);\r\n            outlength = 0;\r\n            logger.Trace(\"---Start Encryption\");\r\n            if (! _encryptSaltSent) {\r\n                _encryptSaltSent = true;\r\n                // Generate salt\r\n                byte[] saltBytes = new byte[saltLen];\r\n                randBytes(saltBytes, saltLen);\r\n                InitCipher(saltBytes, true, false);\r\n                Array.Copy(saltBytes, 0, outbuf, 0, saltLen);\r\n                outlength = saltLen;\r\n                logger.Trace($\"_encryptSaltSent outlength {outlength}\");\r\n            }\r\n\r\n            if (! _tcpRequestSent) {\r\n                _tcpRequestSent = true;\r\n                // The first TCP request\r\n                int encAddrBufLength;\r\n                byte[] encAddrBufBytes = new byte[AddrBufLength + tagLen * 2 + CHUNK_LEN_BYTES];\r\n                byte[] addrBytes = _encCircularBuffer.Get(AddrBufLength);\r\n                ChunkEncrypt(addrBytes, AddrBufLength, encAddrBufBytes, out encAddrBufLength);\r\n                Debug.Assert(encAddrBufLength == AddrBufLength + tagLen * 2 + CHUNK_LEN_BYTES);\r\n                Array.Copy(encAddrBufBytes, 0, outbuf, outlength, encAddrBufLength);\r\n                outlength += encAddrBufLength;\r\n                logger.Trace($\"_tcpRequestSent outlength {outlength}\");\r\n            }\r\n\r\n            // handle other chunks\r\n            while (true) {\r\n                uint bufSize = (uint)_encCircularBuffer.Size;\r\n                if (bufSize <= 0) return;\r\n                var chunklength = (int)Math.Min(bufSize, CHUNK_LEN_MASK);\r\n                byte[] chunkBytes = _encCircularBuffer.Get(chunklength);\r\n                int encChunkLength;\r\n                byte[] encChunkBytes = new byte[chunklength + tagLen * 2 + CHUNK_LEN_BYTES];\r\n                ChunkEncrypt(chunkBytes, chunklength, encChunkBytes, out encChunkLength);\r\n                Debug.Assert(encChunkLength == chunklength + tagLen * 2 + CHUNK_LEN_BYTES);\r\n                Buffer.BlockCopy(encChunkBytes, 0, outbuf, outlength, encChunkLength);\r\n                outlength += encChunkLength;\r\n                logger.Trace(\"chunks enc outlength \" + outlength);\r\n                // check if we have enough space for outbuf\r\n                if (outlength + TCPHandler.ChunkOverheadSize > TCPHandler.BufferSize) {\r\n                    logger.Trace(\"enc outbuf almost full, giving up\");\r\n                    return;\r\n                }\r\n                bufSize = (uint)_encCircularBuffer.Size;\r\n                if (bufSize <= 0) {\r\n                    logger.Trace(\"No more data to encrypt, leaving\");\r\n                    return;\r\n                }\r\n            }\r\n        }\r\n\r\n\r\n        public override void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength)\r\n        {\r\n            Debug.Assert(_decCircularBuffer != null, \"_decCircularBuffer != null\");\r\n            int bufSize;\r\n            outlength = 0;\r\n            // drop all into buffer\r\n            _decCircularBuffer.Put(buf, 0, length);\r\n\r\n            logger.Trace(\"---Start Decryption\");\r\n            if (! _decryptSaltReceived) {\r\n                bufSize = _decCircularBuffer.Size;\r\n                // check if we get the leading salt\r\n                if (bufSize <= saltLen) {\r\n                    // need more\r\n                    return;\r\n                }\r\n                _decryptSaltReceived = true;\r\n                byte[] salt = _decCircularBuffer.Get(saltLen);\r\n                InitCipher(salt, false, false);\r\n                logger.Trace(\"get salt len \" + saltLen);\r\n            }\r\n\r\n            // handle chunks\r\n            while (true) {\r\n                bufSize = _decCircularBuffer.Size;\r\n                // check if we have any data\r\n                if (bufSize <= 0) {\r\n                    logger.Trace(\"No data in _decCircularBuffer\");\r\n                    return;\r\n                }\r\n\r\n                // first get chunk length\r\n                if (bufSize <= CHUNK_LEN_BYTES + tagLen) {\r\n                    // so we only have chunk length and its tag?\r\n                    return;\r\n                }\r\n\r\n                #region Chunk Decryption\r\n\r\n                byte[] encLenBytes = _decCircularBuffer.Peek(CHUNK_LEN_BYTES + tagLen);\r\n                uint decChunkLenLength = 0;\r\n                byte[] decChunkLenBytes = new byte[CHUNK_LEN_BYTES];\r\n                // try to dec chunk len\r\n                cipherDecrypt(encLenBytes, CHUNK_LEN_BYTES + (uint)tagLen, decChunkLenBytes, ref decChunkLenLength);\r\n                Debug.Assert(decChunkLenLength == CHUNK_LEN_BYTES);\r\n                // finally we get the real chunk len\r\n                ushort chunkLen = (ushort) IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(decChunkLenBytes, 0));\r\n                if (chunkLen > CHUNK_LEN_MASK)\r\n                {\r\n                    // we get invalid chunk\r\n                    logger.Error($\"Invalid chunk length: {chunkLen}\");\r\n                    throw new CryptoErrorException();\r\n                }\r\n                logger.Trace(\"Get the real chunk len:\" + chunkLen);\r\n                bufSize = _decCircularBuffer.Size;\r\n                if (bufSize < CHUNK_LEN_BYTES + tagLen /* we haven't remove them */+ chunkLen + tagLen) {\r\n                    logger.Trace(\"No more data to decrypt one chunk\");\r\n                    return;\r\n                }\r\n                IncrementNonce(false);\r\n\r\n                // we have enough data to decrypt one chunk\r\n                // drop chunk len and its tag from buffer\r\n                _decCircularBuffer.Skip(CHUNK_LEN_BYTES + tagLen);\r\n                byte[] encChunkBytes = _decCircularBuffer.Get(chunkLen + tagLen);\r\n                byte[] decChunkBytes = new byte[chunkLen];\r\n                uint decChunkLen = 0;\r\n                cipherDecrypt(encChunkBytes, chunkLen + (uint)tagLen, decChunkBytes, ref decChunkLen);\r\n                Debug.Assert(decChunkLen == chunkLen);\r\n                IncrementNonce(false);\r\n\r\n                #endregion\r\n\r\n                // output to outbuf\r\n                Buffer.BlockCopy(decChunkBytes, 0, outbuf, outlength, (int) decChunkLen);\r\n                outlength += (int)decChunkLen;\r\n                logger.Trace(\"aead dec outlength \" + outlength);\r\n                if (outlength + 100 > TCPHandler.BufferSize)\r\n                {\r\n                    logger.Trace(\"dec outbuf almost full, giving up\");\r\n                    return;\r\n                }\r\n                bufSize = _decCircularBuffer.Size;\r\n                // check if we already done all of them\r\n                if (bufSize <= 0) {\r\n                    logger.Trace(\"No data in _decCircularBuffer, already all done\");\r\n                    return;\r\n                }\r\n            }\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region UDP\r\n\r\n        public override void EncryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)\r\n        {\r\n            // Generate salt\r\n            randBytes(outbuf, saltLen);\r\n            InitCipher(outbuf, true, true);\r\n            uint olen = 0;\r\n            lock (_udpTmpBuf) {\r\n                cipherEncrypt(buf, (uint) length, _udpTmpBuf, ref olen);\r\n                Debug.Assert(olen == length + tagLen);\r\n                Buffer.BlockCopy(_udpTmpBuf, 0, outbuf, saltLen, (int) olen);\r\n                outlength = (int) (saltLen + olen);\r\n            }\r\n        }\r\n\r\n        public override void DecryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)\r\n        {\r\n            InitCipher(buf, false, true);\r\n            uint olen = 0;\r\n            lock (_udpTmpBuf) {\r\n                // copy remaining data to first pos\r\n                Buffer.BlockCopy(buf, saltLen, buf, 0, length - saltLen);\r\n                cipherDecrypt(buf, (uint) (length - saltLen), _udpTmpBuf, ref olen);\r\n                Buffer.BlockCopy(_udpTmpBuf, 0, outbuf, 0, (int) olen);\r\n                outlength = (int) olen;\r\n            }\r\n        }\r\n\r\n        #endregion\r\n\r\n        // we know the plaintext length before encryption, so we can do it in one operation\r\n        private void ChunkEncrypt(byte[] plaintext, int plainLen, byte[] ciphertext, out int cipherLen)\r\n        {\r\n            if (plainLen > CHUNK_LEN_MASK) {\r\n                logger.Error(\"enc chunk too big\");\r\n                throw new CryptoErrorException();\r\n            }\r\n\r\n            // encrypt len\r\n            byte[] encLenBytes = new byte[CHUNK_LEN_BYTES + tagLen];\r\n            uint encChunkLenLength = 0;\r\n            byte[] lenbuf = BitConverter.GetBytes((ushort) IPAddress.HostToNetworkOrder((short)plainLen));\r\n            cipherEncrypt(lenbuf, CHUNK_LEN_BYTES, encLenBytes, ref encChunkLenLength);\r\n            Debug.Assert(encChunkLenLength == CHUNK_LEN_BYTES + tagLen);\r\n            IncrementNonce(true);\r\n\r\n            // encrypt corresponding data\r\n            byte[] encBytes = new byte[plainLen + tagLen];\r\n            uint encBufLength = 0;\r\n            cipherEncrypt(plaintext, (uint) plainLen, encBytes, ref encBufLength);\r\n            Debug.Assert(encBufLength == plainLen + tagLen);\r\n            IncrementNonce(true);\r\n\r\n            // construct outbuf\r\n            Array.Copy(encLenBytes, 0, ciphertext, 0, (int) encChunkLenLength);\r\n            Buffer.BlockCopy(encBytes, 0, ciphertext, (int) encChunkLenLength, (int) encBufLength);\r\n            cipherLen = (int) (encChunkLenLength + encBufLength);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/AEAD/AEADMbedTLSEncryptor.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics;\r\nusing System.Runtime.InteropServices;\r\nusing Shadowsocks.Encryption.Exception;\r\n\r\nnamespace Shadowsocks.Encryption.AEAD\r\n{\r\n    public class AEADMbedTLSEncryptor\r\n        : AEADEncryptor, IDisposable\r\n    {\r\n        const int CIPHER_AES = 1;\r\n\r\n        private IntPtr _encryptCtx = IntPtr.Zero;\r\n        private IntPtr _decryptCtx = IntPtr.Zero;\r\n\r\n        public AEADMbedTLSEncryptor(string method, string password)\r\n            : base(method, password)\r\n        {\r\n        }\r\n\r\n        private static readonly Dictionary<string, EncryptorInfo> _ciphers = new Dictionary<string, EncryptorInfo>\r\n        {\r\n            {\"aes-128-gcm\", new EncryptorInfo(\"AES-128-GCM\", 16, 16, 12, 16, CIPHER_AES)},\r\n            {\"aes-192-gcm\", new EncryptorInfo(\"AES-192-GCM\", 24, 24, 12, 16, CIPHER_AES)},\r\n            {\"aes-256-gcm\", new EncryptorInfo(\"AES-256-GCM\", 32, 32, 12, 16, CIPHER_AES)},\r\n        };\r\n\r\n        public static List<string> SupportedCiphers()\r\n        {\r\n            return new List<string>(_ciphers.Keys);\r\n        }\r\n\r\n        protected override Dictionary<string, EncryptorInfo> getCiphers()\r\n        {\r\n            return _ciphers;\r\n        }\r\n\r\n        public override void InitCipher(byte[] salt, bool isEncrypt, bool isUdp)\r\n        {\r\n            base.InitCipher(salt, isEncrypt, isUdp);\r\n            IntPtr ctx = Marshal.AllocHGlobal(MbedTLS.cipher_get_size_ex());\r\n            if (isEncrypt)\r\n            {\r\n                _encryptCtx = ctx;\r\n            }\r\n            else\r\n            {\r\n                _decryptCtx = ctx;\r\n            }\r\n\r\n            MbedTLS.cipher_init(ctx);\r\n            if (MbedTLS.cipher_setup(ctx, MbedTLS.cipher_info_from_string(_innerLibName)) != 0)\r\n                throw new System.Exception(\"Cannot initialize mbed TLS cipher context\");\r\n\r\n            DeriveSessionKey(isEncrypt ? _encryptSalt : _decryptSalt,\r\n                _Masterkey, _sessionKey);\r\n            CipherSetKey(isEncrypt, _sessionKey);\r\n        }\r\n\r\n        private void CipherSetKey(bool isEncrypt, byte[] key)\r\n        {\r\n            IntPtr ctx = isEncrypt ? _encryptCtx : _decryptCtx;\r\n            int ret = MbedTLS.cipher_setkey(ctx, key, keyLen * 8,\r\n                isEncrypt ? MbedTLS.MBEDTLS_ENCRYPT : MbedTLS.MBEDTLS_DECRYPT);\r\n            if (ret != 0) throw new System.Exception(\"failed to set key\");\r\n            ret = MbedTLS.cipher_reset(ctx);\r\n            if (ret != 0) throw new System.Exception(\"failed to finish preparation\");\r\n        }\r\n\r\n        public override void cipherEncrypt(byte[] plaintext, uint plen, byte[] ciphertext, ref uint clen)\r\n        {\r\n            // buf: all plaintext\r\n            // outbuf: ciphertext + tag\r\n            int ret;\r\n            byte[] tagbuf = new byte[tagLen];\r\n            uint olen = 0;\r\n            switch (_cipher)\r\n            {\r\n                case CIPHER_AES:\r\n                    ret = MbedTLS.cipher_auth_encrypt(_encryptCtx,\r\n                        /* nonce */\r\n                        _encNonce, (uint) nonceLen,\r\n                        /* AD */\r\n                        IntPtr.Zero, 0,\r\n                        /* plain */\r\n                        plaintext, plen,\r\n                        /* cipher */\r\n                        ciphertext, ref olen,\r\n                        tagbuf, (uint) tagLen);\r\n                    if (ret != 0) throw new CryptoErrorException(String.Format(\"ret is {0}\", ret));\r\n                    Debug.Assert(olen == plen);\r\n                    // attach tag to ciphertext\r\n                    Array.Copy(tagbuf, 0, ciphertext, (int) plen, tagLen);\r\n                    clen = olen + (uint) tagLen;\r\n                    break;\r\n                default:\r\n                    throw new System.Exception(\"not implemented\");\r\n            }\r\n        }\r\n\r\n        public override void cipherDecrypt(byte[] ciphertext, uint clen, byte[] plaintext, ref uint plen)\r\n        {\r\n            // buf: ciphertext + tag\r\n            // outbuf: plaintext\r\n            int ret;\r\n            uint olen = 0;\r\n            // split tag\r\n            byte[] tagbuf = new byte[tagLen];\r\n            Array.Copy(ciphertext, (int) (clen - tagLen), tagbuf, 0, tagLen);\r\n            switch (_cipher)\r\n            {\r\n                case CIPHER_AES:\r\n                    ret = MbedTLS.cipher_auth_decrypt(_decryptCtx,\r\n                        _decNonce, (uint) nonceLen,\r\n                        IntPtr.Zero, 0,\r\n                        ciphertext, (uint) (clen - tagLen),\r\n                        plaintext, ref olen,\r\n                        tagbuf, (uint) tagLen);\r\n                    if (ret != 0) throw new CryptoErrorException(String.Format(\"ret is {0}\", ret));\r\n                    Debug.Assert(olen == clen - tagLen);\r\n                    plen = olen;\r\n                    break;\r\n                default:\r\n                    throw new System.Exception(\"not implemented\");\r\n            }\r\n        }\r\n\r\n        #region IDisposable\r\n\r\n        private bool _disposed;\r\n\r\n        // instance based lock\r\n        private readonly object _lock = new object();\r\n\r\n        public override void Dispose()\r\n        {\r\n            Dispose(true);\r\n            GC.SuppressFinalize(this);\r\n        }\r\n\r\n        ~AEADMbedTLSEncryptor()\r\n        {\r\n            Dispose(false);\r\n        }\r\n\r\n        protected virtual void Dispose(bool disposing)\r\n        {\r\n            lock (_lock)\r\n            {\r\n                if (_disposed) return;\r\n                _disposed = true;\r\n            }\r\n\r\n            if (disposing)\r\n            {\r\n                // free managed objects\r\n            }\r\n\r\n            // free unmanaged objects\r\n            if (_encryptCtx != IntPtr.Zero)\r\n            {\r\n                MbedTLS.cipher_free(_encryptCtx);\r\n                Marshal.FreeHGlobal(_encryptCtx);\r\n                _encryptCtx = IntPtr.Zero;\r\n            }\r\n\r\n            if (_decryptCtx != IntPtr.Zero)\r\n            {\r\n                MbedTLS.cipher_free(_decryptCtx);\r\n                Marshal.FreeHGlobal(_decryptCtx);\r\n                _decryptCtx = IntPtr.Zero;\r\n            }\r\n        }\r\n\r\n        #endregion\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/AEAD/AEADOpenSSLEncryptor.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing Shadowsocks.Encryption.Exception;\r\n\r\nnamespace Shadowsocks.Encryption.AEAD\r\n{\r\n    public class AEADOpenSSLEncryptor\r\n        : AEADEncryptor, IDisposable\r\n    {\r\n        const int CIPHER_AES = 1;\r\n        const int CIPHER_CHACHA20IETFPOLY1305 = 2;\r\n\r\n        private byte[] _opensslEncSubkey;\r\n        private byte[] _opensslDecSubkey;\r\n\r\n        private IntPtr _encryptCtx = IntPtr.Zero;\r\n        private IntPtr _decryptCtx = IntPtr.Zero;\r\n\r\n        private IntPtr _cipherInfoPtr = IntPtr.Zero;\r\n\r\n        public AEADOpenSSLEncryptor(string method, string password)\r\n            : base(method, password)\r\n        {\r\n            _opensslEncSubkey = new byte[keyLen];\r\n            _opensslDecSubkey = new byte[keyLen];\r\n        }\r\n\r\n        private static readonly Dictionary<string, EncryptorInfo> _ciphers = new Dictionary<string, EncryptorInfo>\r\n        {\r\n            {\"aes-128-gcm\", new EncryptorInfo(\"aes-128-gcm\", 16, 16, 12, 16, CIPHER_AES)},\r\n            {\"aes-192-gcm\", new EncryptorInfo(\"aes-192-gcm\", 24, 24, 12, 16, CIPHER_AES)},\r\n            {\"aes-256-gcm\", new EncryptorInfo(\"aes-256-gcm\", 32, 32, 12, 16, CIPHER_AES)},\r\n            {\"chacha20-ietf-poly1305\", new EncryptorInfo(\"chacha20-poly1305\", 32, 32, 12, 16, CIPHER_CHACHA20IETFPOLY1305)}\r\n        };\r\n\r\n        public static List<string> SupportedCiphers()\r\n        {\r\n            return new List<string>(_ciphers.Keys);\r\n        }\r\n\r\n        protected override Dictionary<string, EncryptorInfo> getCiphers()\r\n        {\r\n            return _ciphers;\r\n        }\r\n\r\n        public override void InitCipher(byte[] salt, bool isEncrypt, bool isUdp)\r\n        {\r\n            base.InitCipher(salt, isEncrypt, isUdp);\r\n            _cipherInfoPtr = OpenSSL.GetCipherInfo(_innerLibName);\r\n            if (_cipherInfoPtr == IntPtr.Zero) throw new System.Exception(\"openssl: cipher not found\");\r\n            IntPtr ctx = OpenSSL.EVP_CIPHER_CTX_new();\r\n            if (ctx == IntPtr.Zero) throw new System.Exception(\"openssl: fail to create ctx\");\r\n\r\n            if (isEncrypt)\r\n            {\r\n                _encryptCtx = ctx;\r\n            }\r\n            else\r\n            {\r\n                _decryptCtx = ctx;\r\n            }\r\n\r\n            DeriveSessionKey(isEncrypt ? _encryptSalt : _decryptSalt, _Masterkey,\r\n                isEncrypt ? _opensslEncSubkey : _opensslDecSubkey);\r\n\r\n            var ret = OpenSSL.EVP_CipherInit_ex(ctx, _cipherInfoPtr, IntPtr.Zero, null, null,\r\n                isEncrypt ? OpenSSL.OPENSSL_ENCRYPT : OpenSSL.OPENSSL_DECRYPT);\r\n            if (ret != 1) throw new System.Exception(\"openssl: fail to init ctx\");\r\n\r\n            ret = OpenSSL.EVP_CIPHER_CTX_set_key_length(ctx, keyLen);\r\n            if (ret != 1) throw new System.Exception(\"openssl: fail to set key length\");\r\n\r\n            ret = OpenSSL.EVP_CIPHER_CTX_ctrl(ctx, OpenSSL.EVP_CTRL_AEAD_SET_IVLEN,\r\n                nonceLen, IntPtr.Zero);\r\n            if (ret != 1) throw new System.Exception(\"openssl: fail to set AEAD nonce length\");\r\n\r\n            ret = OpenSSL.EVP_CipherInit_ex(ctx, IntPtr.Zero, IntPtr.Zero,\r\n                isEncrypt ? _opensslEncSubkey : _opensslDecSubkey,\r\n                null,\r\n                isEncrypt ? OpenSSL.OPENSSL_ENCRYPT : OpenSSL.OPENSSL_DECRYPT);\r\n            if (ret != 1) throw new System.Exception(\"openssl: cannot set key\");\r\n            OpenSSL.EVP_CIPHER_CTX_set_padding(ctx, 0);\r\n        }\r\n\r\n        public override void cipherEncrypt(byte[] plaintext, uint plen, byte[] ciphertext, ref uint clen)\r\n        {\r\n            OpenSSL.SetCtxNonce(_encryptCtx, _encNonce, true);\r\n            // buf: all plaintext\r\n            // outbuf: ciphertext + tag\r\n            int ret;\r\n            int tmpLen = 0;\r\n            clen = 0;\r\n            var tagBuf = new byte[tagLen];\r\n\r\n            ret = OpenSSL.EVP_CipherUpdate(_encryptCtx, ciphertext, out tmpLen,\r\n                plaintext, (int) plen);\r\n            if (ret != 1) throw new CryptoErrorException(\"openssl: fail to encrypt AEAD\");\r\n            clen += (uint) tmpLen;\r\n            // For AEAD cipher, it should not output anything\r\n            ret = OpenSSL.EVP_CipherFinal_ex(_encryptCtx, ciphertext, ref tmpLen);\r\n            if (ret != 1) throw new CryptoErrorException(\"openssl: fail to finalize AEAD\");\r\n            if (tmpLen > 0)\r\n            {\r\n                throw new System.Exception(\"openssl: fail to finish AEAD\");\r\n            }\r\n\r\n            OpenSSL.AEADGetTag(_encryptCtx, tagBuf, tagLen);\r\n            Array.Copy(tagBuf, 0, ciphertext, clen, tagLen);\r\n            clen += (uint) tagLen;\r\n        }\r\n\r\n        public override void cipherDecrypt(byte[] ciphertext, uint clen, byte[] plaintext, ref uint plen)\r\n        {\r\n            OpenSSL.SetCtxNonce(_decryptCtx, _decNonce, false);\r\n            // buf: ciphertext + tag\r\n            // outbuf: plaintext\r\n            int ret;\r\n            int tmpLen = 0;\r\n            plen = 0;\r\n\r\n            // split tag\r\n            byte[] tagbuf = new byte[tagLen];\r\n            Array.Copy(ciphertext, (int) (clen - tagLen), tagbuf, 0, tagLen);\r\n            OpenSSL.AEADSetTag(_decryptCtx, tagbuf, tagLen);\r\n\r\n            ret = OpenSSL.EVP_CipherUpdate(_decryptCtx,\r\n                plaintext, out tmpLen, ciphertext, (int) (clen - tagLen));\r\n            if (ret != 1) throw new CryptoErrorException(\"openssl: fail to decrypt AEAD\");\r\n            plen += (uint) tmpLen;\r\n\r\n            // For AEAD cipher, it should not output anything\r\n            ret = OpenSSL.EVP_CipherFinal_ex(_decryptCtx, plaintext, ref tmpLen);\r\n            if (ret <= 0)\r\n            {\r\n                // If this is not successful authenticated\r\n                throw new CryptoErrorException(String.Format(\"ret is {0}\", ret));\r\n            }\r\n\r\n            if (tmpLen > 0)\r\n            {\r\n                throw new System.Exception(\"openssl: fail to finish AEAD\");\r\n            }\r\n        }\r\n\r\n        #region IDisposable\r\n\r\n        private bool _disposed;\r\n\r\n        // instance based lock\r\n        private readonly object _lock = new object();\r\n\r\n        public override void Dispose()\r\n        {\r\n            Dispose(true);\r\n            GC.SuppressFinalize(this);\r\n        }\r\n\r\n        ~AEADOpenSSLEncryptor()\r\n        {\r\n            Dispose(false);\r\n        }\r\n\r\n        protected virtual void Dispose(bool disposing)\r\n        {\r\n            lock (_lock)\r\n            {\r\n                if (_disposed) return;\r\n                _disposed = true;\r\n            }\r\n\r\n            if (disposing)\r\n            {\r\n                // free managed objects\r\n            }\r\n\r\n            // free unmanaged objects\r\n            if (_encryptCtx != IntPtr.Zero)\r\n            {\r\n                OpenSSL.EVP_CIPHER_CTX_free(_encryptCtx);\r\n                _encryptCtx = IntPtr.Zero;\r\n            }\r\n\r\n            if (_decryptCtx != IntPtr.Zero)\r\n            {\r\n                OpenSSL.EVP_CIPHER_CTX_free(_decryptCtx);\r\n                _decryptCtx = IntPtr.Zero;\r\n            }\r\n        }\r\n\r\n        #endregion\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/AEAD/AEADSodiumEncryptor.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics;\r\nusing NLog;\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Encryption.Exception;\r\n\r\nnamespace Shadowsocks.Encryption.AEAD\r\n{\r\n    public class AEADSodiumEncryptor\r\n        : AEADEncryptor, IDisposable\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private const int CIPHER_CHACHA20IETFPOLY1305 = 1;\r\n        private const int CIPHER_XCHACHA20IETFPOLY1305 = 2;\r\n        private const int CIPHER_AES256GCM = 3;\r\n\r\n        private byte[] _sodiumEncSubkey;\r\n        private byte[] _sodiumDecSubkey;\r\n\r\n        public AEADSodiumEncryptor(string method, string password)\r\n            : base(method, password)\r\n        {\r\n            _sodiumEncSubkey = new byte[keyLen];\r\n            _sodiumDecSubkey = new byte[keyLen];\r\n        }\r\n\r\n        private static readonly Dictionary<string, EncryptorInfo> _ciphers = new Dictionary<string, EncryptorInfo>\r\n        {\r\n            {\"chacha20-ietf-poly1305\", new EncryptorInfo(32, 32, 12, 16, CIPHER_CHACHA20IETFPOLY1305)},\r\n            {\"xchacha20-ietf-poly1305\", new EncryptorInfo(32, 32, 24, 16, CIPHER_XCHACHA20IETFPOLY1305)},\r\n            {\"aes-256-gcm\", new EncryptorInfo(32, 32, 12, 16, CIPHER_AES256GCM)},\r\n        };\r\n\r\n        public static List<string> SupportedCiphers()\r\n        {\r\n            return new List<string>(_ciphers.Keys);\r\n        }\r\n\r\n        protected override Dictionary<string, EncryptorInfo> getCiphers()\r\n        {\r\n            return _ciphers;\r\n        }\r\n\r\n        public override void InitCipher(byte[] salt, bool isEncrypt, bool isUdp)\r\n        {\r\n            base.InitCipher(salt, isEncrypt, isUdp);\r\n            DeriveSessionKey(isEncrypt ? _encryptSalt : _decryptSalt, _Masterkey,\r\n                isEncrypt ? _sodiumEncSubkey : _sodiumDecSubkey);\r\n        }\r\n\r\n\r\n        public override void cipherEncrypt(byte[] plaintext, uint plen, byte[] ciphertext, ref uint clen)\r\n        {\r\n            Debug.Assert(_sodiumEncSubkey != null);\r\n            // buf: all plaintext\r\n            // outbuf: ciphertext + tag\r\n            int ret;\r\n            ulong encClen = 0;\r\n            logger.Dump(\"_encNonce before enc\", _encNonce, nonceLen);\r\n            logger.Dump(\"_sodiumEncSubkey\", _sodiumEncSubkey, keyLen);\r\n            logger.Dump(\"before cipherEncrypt: plain\", plaintext, (int) plen);\r\n            switch (_cipher)\r\n            {\r\n                case CIPHER_CHACHA20IETFPOLY1305:\r\n                    ret = Sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, ref encClen,\r\n                        plaintext, (ulong) plen,\r\n                        null, 0,\r\n                        null, _encNonce,\r\n                        _sodiumEncSubkey);\r\n                    break;\r\n                case CIPHER_XCHACHA20IETFPOLY1305:\r\n                    ret = Sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(ciphertext, ref encClen,\r\n                        plaintext, (ulong)plen,\r\n                        null, 0,\r\n                        null, _encNonce,\r\n                        _sodiumEncSubkey);\r\n                    break;\r\n                case CIPHER_AES256GCM:\r\n                    ret = Sodium.crypto_aead_aes256gcm_encrypt(ciphertext, ref encClen,\r\n                        plaintext, (ulong)plen,\r\n                        null, 0,\r\n                        null, _encNonce,\r\n                        _sodiumEncSubkey);\r\n                    break;\r\n                default:\r\n                    throw new System.Exception(\"not implemented\");\r\n            }\r\n            if (ret != 0) throw new CryptoErrorException(String.Format(\"ret is {0}\", ret));\r\n            logger.Dump(\"after cipherEncrypt: cipher\", ciphertext, (int) encClen);\r\n            clen = (uint) encClen;\r\n        }\r\n\r\n        public override void cipherDecrypt(byte[] ciphertext, uint clen, byte[] plaintext, ref uint plen)\r\n        {\r\n            Debug.Assert(_sodiumDecSubkey != null);\r\n            // buf: ciphertext + tag\r\n            // outbuf: plaintext\r\n            int ret;\r\n            ulong decPlen = 0;\r\n            logger.Dump(\"_decNonce before dec\", _decNonce, nonceLen);\r\n            logger.Dump(\"_sodiumDecSubkey\", _sodiumDecSubkey, keyLen);\r\n            logger.Dump(\"before cipherDecrypt: cipher\", ciphertext, (int) clen);\r\n            switch (_cipher)\r\n            {\r\n                case CIPHER_CHACHA20IETFPOLY1305:\r\n                    ret = Sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, ref decPlen,\r\n                        null,\r\n                        ciphertext, (ulong) clen,\r\n                        null, 0,\r\n                        _decNonce, _sodiumDecSubkey);\r\n                    break;\r\n                case CIPHER_XCHACHA20IETFPOLY1305:\r\n                    ret = Sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(plaintext, ref decPlen,\r\n                        null,\r\n                        ciphertext, (ulong)clen,\r\n                        null, 0,\r\n                        _decNonce, _sodiumDecSubkey);\r\n                    break;\r\n                case CIPHER_AES256GCM:\r\n                    ret = Sodium.crypto_aead_aes256gcm_decrypt(plaintext, ref decPlen,\r\n                        null,\r\n                        ciphertext, (ulong)clen,\r\n                        null, 0,\r\n                        _decNonce, _sodiumDecSubkey);\r\n                    break;\r\n                default:\r\n                    throw new System.Exception(\"not implemented\");\r\n            }\r\n\r\n            if (ret != 0) throw new CryptoErrorException(String.Format(\"ret is {0}\", ret));\r\n            logger.Dump(\"after cipherDecrypt: plain\", plaintext, (int) decPlen);\r\n            plen = (uint) decPlen;\r\n        }\r\n\r\n        public override void Dispose()\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/CircularBuffer/ByteCircularBuffer.cs",
    "content": "﻿#region Original License\r\n\r\n//New BSD License(BSD)\r\n//\r\n//Copyright(c) 2014-2015 Cyotek Ltd\r\n//Copyright(c) 2012, Alex Regueiro\r\n//All rights reserved.\r\n//\r\n//Redistribution and use in source and binary forms, with or without\r\n//modification, are permitted provided that the following conditions are met:\r\n//    * Redistributions of source code must retain the above copyright\r\n//      notice, this list of conditions and the following disclaimer.\r\n//    * Redistributions in binary form must reproduce the above copyright\r\n//      notice, this list of conditions and the following disclaimer in the\r\n//      documentation and/or other materials provided with the distribution.\r\n//    * Neither the name of Cyotek nor the\r\n//      names of its contributors may be used to endorse or promote products\r\n//      derived from this software without specific prior written permission.\r\n//\r\n//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n//DISCLAIMED.IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\r\n//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n#endregion\r\n\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace Shadowsocks.Encryption.CircularBuffer\r\n{\r\n    /// <summary>\r\n    /// Represents a first-in, first-out collection of objects using a fixed buffer.\r\n    /// </summary>\r\n    /// <remarks>\r\n    /// <para>The capacity of a <see cref=\"ByteCircularBuffer\" /> is the number of elements the <see cref=\"ByteCircularBuffer\"/> can hold. </para>\r\n    /// <para>ByteCircularBuffer accepts <c>null</c> as a valid value for reference types and allows duplicate elements.</para>\r\n    /// <para>The <see cref=\"Get()\"/> methods will remove the items that are returned from the ByteCircularBuffer. To view the contents of the ByteCircularBuffer without removing items, use the <see cref=\"Peek()\"/> or <see cref=\"PeekLast\"/> methods.</para>\r\n    /// </remarks>\r\n    public class ByteCircularBuffer\r\n    {\r\n        // based on http://circularbuffer.codeplex.com/\r\n        // http://en.wikipedia.org/wiki/Circular_buffer\r\n        // modified from https://github.com/cyotek/Cyotek.Collections.Generic.CircularBuffer\r\n        // some code taken from https://github.com/xorxornop/RingBuffer\r\n        // and https://github.com/xorxornop/PerfCopy\r\n\r\n        #region Instance Fields\r\n\r\n        private byte[] _buffer;\r\n\r\n        private int _capacity;\r\n\r\n        #endregion\r\n\r\n        #region Public Constructors\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ByteCircularBuffer\"/> class that is empty and has the specified initial capacity.\r\n        /// </summary>\r\n        /// <param name=\"capacity\">The maximum capcity of the buffer.</param>\r\n        /// <exception cref=\"System.ArgumentException\">Thown if the <paramref name=\"capacity\"/> is less than zero.</exception>\r\n        public ByteCircularBuffer(int capacity)\r\n        {\r\n            if (capacity < 0)\r\n            {\r\n                throw new ArgumentException(\"The buffer capacity must be greater than or equal to zero.\",\r\n                    nameof(capacity));\r\n            }\r\n\r\n            _buffer = new byte[capacity];\r\n            this.Capacity = capacity;\r\n            this.Size = 0;\r\n            this.Head = 0;\r\n            this.Tail = 0;\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Public Properties\r\n\r\n        /// <summary>\r\n        /// Gets or sets the total number of elements the internal data structure can hold.\r\n        /// </summary>\r\n        /// <value>The total number of elements that the <see cref=\"ByteCircularBuffer\"/> can contain.</value>\r\n        /// <exception cref=\"System.ArgumentOutOfRangeException\">Thrown if the specified new capacity is smaller than the current contents of the buffer.</exception>\r\n        public int Capacity\r\n        {\r\n            get { return _capacity; }\r\n            set\r\n            {\r\n                if (value != _capacity)\r\n                {\r\n                    if (value < this.Size)\r\n                    {\r\n                        throw new ArgumentOutOfRangeException(nameof(value), value,\r\n                            \"The new capacity must be greater than or equal to the buffer size.\");\r\n                    }\r\n\r\n                    var newBuffer = new byte[value];\r\n                    if (this.Size > 0)\r\n                    {\r\n                        this.CopyTo(newBuffer);\r\n                    }\r\n\r\n                    _buffer = newBuffer;\r\n\r\n                    _capacity = value;\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the index of the beginning of the buffer data.\r\n        /// </summary>\r\n        /// <value>The index of the first element in the buffer.</value>\r\n        public int Head { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the buffer is empty.\r\n        /// </summary>\r\n        /// <value><c>true</c> if buffer is empty; otherwise, <c>false</c>.</value>\r\n        public virtual bool IsEmpty => this.Size == 0;\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the buffer is full.\r\n        /// </summary>\r\n        /// <value><c>true</c> if the buffer is full; otherwise, <c>false</c>.</value>\r\n        /// <remarks>The <see cref=\"IsFull\"/> property always returns <c>false</c> if the <see cref=\"AllowOverwrite\"/> property is set to <c>true</c>.</remarks>\r\n        public virtual bool IsFull => this.Size == this.Capacity;\r\n\r\n        /// <summary>\r\n        /// Gets the number of elements contained in the <see cref=\"ByteCircularBuffer\"/>.\r\n        /// </summary>\r\n        /// <value>The number of elements contained in the <see cref=\"ByteCircularBuffer\"/>.</value>\r\n        public int Size { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets the index of the end of the buffer data.\r\n        /// </summary>\r\n        /// <value>The index of the last element in the buffer.</value>\r\n        public int Tail { get; protected set; }\r\n\r\n        #endregion\r\n\r\n        #region Public Members\r\n\r\n        /// <summary>\r\n        /// Removes all items from the <see cref=\"ByteCircularBuffer\" />.\r\n        /// </summary>\r\n        public void Clear()\r\n        {\r\n            this.Size = 0;\r\n            this.Head = 0;\r\n            this.Tail = 0;\r\n            _buffer = new byte[this.Capacity];\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the <see cref=\"ByteCircularBuffer\" /> contains a specific value.\r\n        /// </summary>\r\n        /// <param name=\"item\">The object to locate in the <see cref=\"ByteCircularBuffer\" />.</param>\r\n        /// <returns><c>true</c> if <paramref name=\"item\" /> is found in the <see cref=\"ByteCircularBuffer\" />; otherwise, <c>false</c>.</returns>\r\n        public bool Contains(byte item)\r\n        {\r\n            var bufferIndex = this.Head;\r\n            var comparer = EqualityComparer<byte>.Default;\r\n            var result = false;\r\n\r\n            for (int i = 0; i < this.Size; i++, bufferIndex++)\r\n            {\r\n                if (bufferIndex == this.Capacity)\r\n                {\r\n                    bufferIndex = 0;\r\n                }\r\n\r\n                if (comparer.Equals(_buffer[bufferIndex], item))\r\n                {\r\n                    result = true;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            return result;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies the entire <see cref=\"ByteCircularBuffer\"/> to a compatible one-dimensional array, starting at the beginning of the target array.\r\n        /// </summary>\r\n        /// <param name=\"array\">The one-dimensional <see cref=\"Array\"/> that is the destination of the elements copied from <see cref=\"ByteCircularBuffer\"/>. The <see cref=\"Array\"/> must have zero-based indexing.</param>\r\n        public void CopyTo(byte[] array)\r\n        {\r\n            this.CopyTo(array, 0);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies the entire <see cref=\"ByteCircularBuffer\"/> to a compatible one-dimensional array, starting at the specified index of the target array.\r\n        /// </summary>\r\n        /// <param name=\"array\">The one-dimensional <see cref=\"Array\"/> that is the destination of the elements copied from <see cref=\"ByteCircularBuffer\"/>. The <see cref=\"Array\"/> must have zero-based indexing.</param>\r\n        /// <param name=\"arrayIndex\">The zero-based index in <paramref name=\"array\"/> at which copying begins.</param>\r\n        public void CopyTo(byte[] array, int arrayIndex)\r\n        {\r\n            this.CopyTo(this.Head, array, arrayIndex, Math.Min(this.Size, array.Length - arrayIndex));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies a range of elements from the <see cref=\"ByteCircularBuffer\"/> to a compatible one-dimensional array, starting at the specified index of the target array.\r\n        /// </summary>\r\n        /// <param name=\"index\">The zero-based index in the source <see cref=\"ByteCircularBuffer\"/> at which copying begins.</param>\r\n        /// <param name=\"array\">The one-dimensional <see cref=\"Array\"/> that is the destination of the elements copied from <see cref=\"ByteCircularBuffer\"/>. The <see cref=\"Array\"/> must have zero-based indexing.</param>\r\n        /// <param name=\"arrayIndex\">The zero-based index in <paramref name=\"array\"/> at which copying begins.</param>\r\n        /// <param name=\"count\">The number of elements to copy.</param>\r\n        public virtual void CopyTo(int index, byte[] array, int arrayIndex, int count)\r\n        {\r\n            if (count > this.Size)\r\n            {\r\n                throw new ArgumentOutOfRangeException(nameof(count), count,\r\n                    \"The read count cannot be greater than the buffer size.\");\r\n            }\r\n\r\n            var startAnchor = index;\r\n            var dstIndex = arrayIndex;\r\n\r\n            while (count > 0)\r\n            {\r\n                int chunk = Math.Min(Capacity - startAnchor, count);\r\n                Buffer.BlockCopy(_buffer, startAnchor, array, dstIndex, chunk);\r\n                startAnchor = (startAnchor + chunk == Capacity) ? 0 : startAnchor + chunk;\r\n                dstIndex += chunk;\r\n                count -= chunk;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Removes and returns the specified number of objects from the beginning of the <see cref=\"ByteCircularBuffer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"count\">The number of elements to remove and return from the <see cref=\"ByteCircularBuffer\"/>.</param>\r\n        /// <returns>The objects that are removed from the beginning of the <see cref=\"ByteCircularBuffer\"/>.</returns>\r\n        public byte[] Get(int count)\r\n        {\r\n            if (count <= 0) throw new ArgumentOutOfRangeException(\"should greater than 0\");\r\n            var result = new byte[count];\r\n\r\n            this.Get(result);\r\n\r\n            return result;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies and removes the specified number elements from the <see cref=\"ByteCircularBuffer\"/> to a compatible one-dimensional array, starting at the beginning of the target array. \r\n        /// </summary>\r\n        /// <param name=\"array\">The one-dimensional <see cref=\"Array\"/> that is the destination of the elements copied from <see cref=\"ByteCircularBuffer\"/>. The <see cref=\"Array\"/> must have zero-based indexing.</param>\r\n        /// <returns>The actual number of elements copied into <paramref name=\"array\"/>.</returns>\r\n        public int Get(byte[] array)\r\n        {\r\n            if (array.Length <= 0) throw new ArgumentOutOfRangeException(\"should greater than 0\");\r\n            return this.Get(array, 0, array.Length);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies and removes the specified number elements from the <see cref=\"ByteCircularBuffer\"/> to a compatible one-dimensional array, starting at the specified index of the target array. \r\n        /// </summary>\r\n        /// <param name=\"array\">The one-dimensional <see cref=\"Array\"/> that is the destination of the elements copied from <see cref=\"ByteCircularBuffer\"/>. The <see cref=\"Array\"/> must have zero-based indexing.</param>\r\n        /// <param name=\"arrayIndex\">The zero-based index in <paramref name=\"array\"/> at which copying begins.</param>\r\n        /// <param name=\"count\">The number of elements to copy.</param>\r\n        /// <returns>The actual number of elements copied into <paramref name=\"array\"/>.</returns>\r\n        public virtual int Get(byte[] array, int arrayIndex, int count)\r\n        {\r\n            if (arrayIndex < 0)\r\n            {\r\n                throw new ArgumentOutOfRangeException(nameof(arrayIndex), \"Negative offset specified. Offsets must be positive.\");\r\n            }\r\n            if (count < 0)\r\n            {\r\n                throw new ArgumentOutOfRangeException(nameof(count), \"Negative count specified. Count must be positive.\");\r\n            }\r\n            if (count > this.Size)\r\n            {\r\n                throw new ArgumentException(\"Ringbuffer contents insufficient for take/read operation.\", nameof(count));\r\n            }\r\n            if (array.Length < arrayIndex + count)\r\n            {\r\n                throw new ArgumentException(\"Destination array too small for requested output.\");\r\n            }\r\n            var bytesCopied = 0;\r\n            var dstIndex = arrayIndex;\r\n            while (count > 0)\r\n            {\r\n                int chunk = Math.Min(Capacity - this.Head, count);\r\n                Buffer.BlockCopy(_buffer, this.Head, array, dstIndex, chunk);\r\n                this.Head = (this.Head + chunk == Capacity) ? 0 : this.Head + chunk;\r\n                this.Size -= chunk;\r\n                dstIndex += chunk;\r\n                bytesCopied += chunk;\r\n                count -= chunk;\r\n            }\r\n            return bytesCopied;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Removes and returns the object at the beginning of the <see cref=\"ByteCircularBuffer\"/>.\r\n        /// </summary>\r\n        /// <returns>The object that is removed from the beginning of the <see cref=\"ByteCircularBuffer\"/>.</returns>\r\n        /// <exception cref=\"System.InvalidOperationException\">Thrown if the buffer is empty.</exception>\r\n        /// <remarks>This method is similar to the <see cref=\"Peek()\"/> method, but <c>Peek</c> does not modify the <see cref=\"ByteCircularBuffer\"/>.</remarks>\r\n        public virtual byte Get()\r\n        {\r\n            if (this.IsEmpty)\r\n            {\r\n                throw new InvalidOperationException(\"The buffer is empty.\");\r\n            }\r\n\r\n            var item = _buffer[this.Head];\r\n            if (++this.Head == this.Capacity)\r\n            {\r\n                this.Head = 0;\r\n            }\r\n            this.Size--;\r\n\r\n            return item;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the object at the beginning of the <see cref=\"ByteCircularBuffer\"/> without removing it.\r\n        /// </summary>\r\n        /// <returns>The object at the beginning of the <see cref=\"ByteCircularBuffer\"/>.</returns>\r\n        /// <exception cref=\"System.InvalidOperationException\">Thrown if the buffer is empty.</exception>\r\n        public virtual byte Peek()\r\n        {\r\n            if (this.IsEmpty)\r\n            {\r\n                throw new InvalidOperationException(\"The buffer is empty.\");\r\n            }\r\n\r\n            var item = _buffer[this.Head];\r\n\r\n            return item;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the specified number of objects from the beginning of the <see cref=\"ByteCircularBuffer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"count\">The number of elements to return from the <see cref=\"ByteCircularBuffer\"/>.</param>\r\n        /// <returns>The objects that from the beginning of the <see cref=\"ByteCircularBuffer\"/>.</returns>\r\n        /// <exception cref=\"System.InvalidOperationException\">Thrown if the buffer is empty.</exception>\r\n        public virtual byte[] Peek(int count)\r\n        {\r\n            if (this.IsEmpty)\r\n            {\r\n                throw new InvalidOperationException(\"The buffer is empty.\");\r\n            }\r\n\r\n            var items = new byte[count];\r\n            this.CopyTo(items);\r\n\r\n            return items;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the object at the end of the <see cref=\"ByteCircularBuffer\"/> without removing it.\r\n        /// </summary>\r\n        /// <returns>The object at the end of the <see cref=\"ByteCircularBuffer\"/>.</returns>\r\n        /// <exception cref=\"System.InvalidOperationException\">Thrown if the buffer is empty.</exception>\r\n        public virtual byte PeekLast()\r\n        {\r\n            int bufferIndex;\r\n\r\n            if (this.IsEmpty)\r\n            {\r\n                throw new InvalidOperationException(\"The buffer is empty.\");\r\n            }\r\n\r\n            if (this.Tail == 0)\r\n            {\r\n                bufferIndex = this.Size - 1;\r\n            }\r\n            else\r\n            {\r\n                bufferIndex = this.Tail - 1;\r\n            }\r\n\r\n            var item = _buffer[bufferIndex];\r\n\r\n            return item;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies an entire compatible one-dimensional array to the <see cref=\"ByteCircularBuffer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"array\">The one-dimensional <see cref=\"Array\"/> that is the source of the elements copied to <see cref=\"ByteCircularBuffer\"/>. The <see cref=\"Array\"/> must have zero-based indexing.</param>\r\n        /// <exception cref=\"System.InvalidOperationException\">Thrown if buffer does not have sufficient capacity to put in new items.</exception>\r\n        /// <remarks>If <see cref=\"Size\"/> plus the size of <paramref name=\"array\"/> exceeds the capacity of the <see cref=\"ByteCircularBuffer\"/> and the <see cref=\"AllowOverwrite\"/> property is <c>true</c>, the oldest items in the <see cref=\"ByteCircularBuffer\"/> are overwritten with <paramref name=\"array\"/>.</remarks>\r\n        public int Put(byte[] array)\r\n        {\r\n            return this.Put(array, 0, array.Length);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies a range of elements from a compatible one-dimensional array to the <see cref=\"ByteCircularBuffer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"array\">The one-dimensional <see cref=\"Array\"/> that is the source of the elements copied to <see cref=\"ByteCircularBuffer\"/>. The <see cref=\"Array\"/> must have zero-based indexing.</param>\r\n        /// <param name=\"arrayIndex\">The zero-based index in <paramref name=\"array\"/> at which copying begins.</param>\r\n        /// <param name=\"count\">The number of elements to copy.</param>\r\n        /// <exception cref=\"System.InvalidOperationException\">Thrown if buffer does not have sufficient capacity to put in new items.</exception>\r\n        /// <remarks>If <see cref=\"Size\"/> plus <paramref name=\"count\"/> exceeds the capacity of the <see cref=\"ByteCircularBuffer\"/> and the <see cref=\"AllowOverwrite\"/> property is <c>true</c>, the oldest items in the <see cref=\"ByteCircularBuffer\"/> are overwritten with <paramref name=\"array\"/>.</remarks>\r\n        public virtual int Put(byte[] array, int arrayIndex, int count)\r\n        {\r\n            if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count), \"Count must be positive.\");\r\n            if (this.Size + count > this.Capacity)\r\n            {\r\n                throw new InvalidOperationException(\"The buffer does not have sufficient capacity to put new items.\");\r\n            }\r\n\r\n            if (array.Length < arrayIndex + count)\r\n            {\r\n                throw new ArgumentException(\"Source array too small for requested input.\");\r\n            }\r\n            var srcIndex = arrayIndex;\r\n            var bytesToProcess = count;\r\n            while (bytesToProcess > 0)\r\n            {\r\n                int chunk = Math.Min(Capacity - Tail, bytesToProcess);\r\n                Buffer.BlockCopy(array, srcIndex, _buffer, Tail, chunk);\r\n                Tail = (Tail + chunk == Capacity) ? 0 : Tail + chunk;\r\n                this.Size += chunk;\r\n                srcIndex += chunk;\r\n                bytesToProcess -= chunk;\r\n            }\r\n\r\n            return count;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a byte to the end of the <see cref=\"ByteCircularBuffer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"item\">The byte to add to the <see cref=\"ByteCircularBuffer\"/>. </param>\r\n        /// <exception cref=\"System.InvalidOperationException\">Thrown if buffer does not have sufficient capacity to put in new items.</exception>\r\n        public virtual void Put(byte item)\r\n        {\r\n            if (IsFull)\r\n            {\r\n                throw new InvalidOperationException(\"The buffer does not have sufficient capacity to put new items.\");\r\n            }\r\n\r\n            _buffer[this.Tail] = item;\r\n\r\n            this.Tail++;\r\n            if (this.Size == this.Capacity)\r\n            {\r\n                this.Head++;\r\n                if (this.Head >= this.Capacity)\r\n                {\r\n                    this.Head -= this.Capacity;\r\n                }\r\n            }\r\n\r\n            if (this.Tail == this.Capacity)\r\n            {\r\n                this.Tail = 0;\r\n            }\r\n\r\n            if (this.Size != this.Capacity)\r\n            {\r\n                this.Size++;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Increments the starting index of the data buffer in the <see cref=\"ByteCircularBuffer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"count\">The number of elements to increment the data buffer start index by.</param>\r\n        public void Skip(int count)\r\n        {\r\n            if (count < 0)\r\n            {\r\n                throw new ArgumentOutOfRangeException(nameof(count), \"Negative count specified. Count must be positive.\");\r\n            }\r\n            if (count > this.Size)\r\n            {\r\n                throw new ArgumentException(\"Ringbuffer contents insufficient for operation.\", nameof(count));\r\n            }\r\n\r\n            // Modular division gives new offset position\r\n            this.Head = (this.Head + count) % Capacity;\r\n            this.Size -= count;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies the <see cref=\"ByteCircularBuffer\"/> elements to a new array.\r\n        /// </summary>\r\n        /// <returns>A new array containing elements copied from the <see cref=\"ByteCircularBuffer\"/>.</returns>\r\n        /// <remarks>The <see cref=\"ByteCircularBuffer\"/> 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 <see cref=\"ByteCircularBuffer\"/> to its end.</remarks>\r\n        public byte[] ToArray()\r\n        {\r\n            var result = new byte[this.Size];\r\n\r\n            this.CopyTo(result);\r\n\r\n            return result;\r\n        }\r\n\r\n        #endregion\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/EncryptorBase.cs",
    "content": "﻿namespace Shadowsocks.Encryption\r\n{\r\n    public class EncryptorInfo\r\n    {\r\n        public int KeySize;\r\n        public int IvSize;\r\n        public int SaltSize;\r\n        public int TagSize;\r\n        public int NonceSize;\r\n        public int Type;\r\n        public string InnerLibName;\r\n\r\n        // For those who make use of internal crypto method name\r\n        // e.g. mbed TLS\r\n\r\n        #region Stream ciphers\r\n\r\n        public EncryptorInfo(string innerLibName, int keySize, int ivSize, int type)\r\n        {\r\n            this.KeySize = keySize;\r\n            this.IvSize = ivSize;\r\n            this.Type = type;\r\n            this.InnerLibName = innerLibName;\r\n        }\r\n\r\n        public EncryptorInfo(int keySize, int ivSize, int type)\r\n        {\r\n            this.KeySize = keySize;\r\n            this.IvSize = ivSize;\r\n            this.Type = type;\r\n            this.InnerLibName = string.Empty;\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region AEAD ciphers\r\n\r\n        public EncryptorInfo(string innerLibName, int keySize, int saltSize, int nonceSize, int tagSize, int type)\r\n        {\r\n            this.KeySize = keySize;\r\n            this.SaltSize = saltSize;\r\n            this.NonceSize = nonceSize;\r\n            this.TagSize = tagSize;\r\n            this.Type = type;\r\n            this.InnerLibName = innerLibName;\r\n        }\r\n\r\n        public EncryptorInfo(int keySize, int saltSize, int nonceSize, int tagSize, int type)\r\n        {\r\n            this.KeySize = keySize;\r\n            this.SaltSize = saltSize;\r\n            this.NonceSize = nonceSize;\r\n            this.TagSize = tagSize;\r\n            this.Type = type;\r\n            this.InnerLibName = string.Empty;\r\n        }\r\n\r\n        #endregion\r\n    }\r\n\r\n    public abstract class EncryptorBase\r\n        : IEncryptor\r\n    {\r\n        public const int MAX_INPUT_SIZE = 32768;\r\n\r\n        public const int MAX_DOMAIN_LEN = 255;\r\n        public const int ADDR_PORT_LEN = 2;\r\n        public const int ADDR_ATYP_LEN = 1;\r\n\r\n        public const int ATYP_IPv4 = 0x01;\r\n        public const int ATYP_DOMAIN = 0x03;\r\n        public const int ATYP_IPv6 = 0x04;\r\n\r\n        public const int MD5_LEN = 16;\r\n\r\n        protected EncryptorBase(string method, string password)\r\n        {\r\n            Method = method;\r\n            Password = password;\r\n        }\r\n\r\n        protected string Method;\r\n        protected string Password;\r\n\r\n        public abstract void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength);\r\n\r\n        public abstract void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength);\r\n\r\n        public abstract void EncryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength);\r\n\r\n        public abstract void DecryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength);\r\n\r\n        public abstract void Dispose();\r\n\r\n        public int AddrBufLength { get; set; } = - 1;\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/EncryptorFactory.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Text;\r\nusing Shadowsocks.Encryption.AEAD;\r\nusing Shadowsocks.Encryption.Stream;\r\n\r\nnamespace Shadowsocks.Encryption\r\n{\r\n    public static class EncryptorFactory\r\n    {\r\n        private static Dictionary<string, Type> _registeredEncryptors = new Dictionary<string, Type>();\r\n\r\n        private static readonly Type[] ConstructorTypes = {typeof(string), typeof(string)};\r\n\r\n        static EncryptorFactory()\r\n        {\r\n            var AEADMbedTLSEncryptorSupportedCiphers = AEADMbedTLSEncryptor.SupportedCiphers();\r\n            var AEADSodiumEncryptorSupportedCiphers = AEADSodiumEncryptor.SupportedCiphers();\r\n            var PlainEncryptorSupportedCiphers = PlainEncryptor.SupportedCiphers();\r\n\r\n            if (Sodium.AES256GCMAvailable)\r\n            {\r\n                // prefer to aes-256-gcm in libsodium\r\n                AEADMbedTLSEncryptorSupportedCiphers.Remove(\"aes-256-gcm\");\r\n            }\r\n            else\r\n            {\r\n                AEADSodiumEncryptorSupportedCiphers.Remove(\"aes-256-gcm\");\r\n            }\r\n\r\n            foreach (string method in AEADOpenSSLEncryptor.SupportedCiphers())\r\n            {\r\n                if (!_registeredEncryptors.ContainsKey(method))\r\n                    _registeredEncryptors.Add(method, typeof(AEADOpenSSLEncryptor));\r\n            }\r\n\r\n            foreach (string method in AEADSodiumEncryptorSupportedCiphers)\r\n            {\r\n                if (!_registeredEncryptors.ContainsKey(method))\r\n                    _registeredEncryptors.Add(method, typeof(AEADSodiumEncryptor));\r\n            }\r\n\r\n            foreach (string method in AEADMbedTLSEncryptorSupportedCiphers)\r\n            {\r\n                if (!_registeredEncryptors.ContainsKey(method))\r\n                    _registeredEncryptors.Add(method, typeof(AEADMbedTLSEncryptor));\r\n            }\r\n\r\n            foreach (string method in PlainEncryptorSupportedCiphers)\r\n            {\r\n                if (!_registeredEncryptors.ContainsKey(method))\r\n                    _registeredEncryptors.Add(method, typeof(PlainEncryptor));\r\n            }\r\n        }\r\n\r\n        public static IEncryptor GetEncryptor(string method, string password)\r\n        {\r\n            if (string.IsNullOrEmpty(method))\r\n            {\r\n                method = Model.Server.DefaultMethod;\r\n            }\r\n\r\n            method = method.ToLowerInvariant();\r\n            Type t = _registeredEncryptors[method];\r\n\r\n            ConstructorInfo c = t.GetConstructor(ConstructorTypes);\r\n            if (c == null) throw new System.Exception(\"Invalid ctor\");\r\n            IEncryptor result = (IEncryptor) c.Invoke(new object[] {method, password});\r\n            return result;\r\n        }\r\n\r\n        public static string DumpRegisteredEncryptor()\r\n        {\r\n            var sb = new StringBuilder();\r\n            sb.Append(Environment.NewLine);\r\n            sb.AppendLine(\"=========================\");\r\n            sb.AppendLine(\"Registered Encryptor Info\");\r\n            foreach (var encryptor in _registeredEncryptors)\r\n            {\r\n                sb.AppendLine(String.Format(\"{0}=>{1}\", encryptor.Key, encryptor.Value.Name));\r\n            }\r\n\r\n            sb.AppendLine(\"=========================\");\r\n            return sb.ToString();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Encryption/Exception/CryptoException.cs",
    "content": "﻿namespace Shadowsocks.Encryption.Exception\r\n{\r\n    public class CryptoErrorException : System.Exception\r\n    {\r\n        public CryptoErrorException()\r\n        {\r\n        }\r\n\r\n        public CryptoErrorException(string msg) : base(msg)\r\n        {\r\n        }\r\n\r\n        public CryptoErrorException(string message, System.Exception innerException) : base(message, innerException)\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/IEncryptor.cs",
    "content": "﻿using System;\r\n\r\nnamespace Shadowsocks.Encryption\r\n{\r\n    public interface IEncryptor : IDisposable\r\n    {\r\n        /* length == -1 means not used */\r\n        int AddrBufLength { set; get; }\r\n        void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength);\r\n        void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength);\r\n        void EncryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength);\r\n        void DecryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength);\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Encryption/MbedTLS.cs",
    "content": "﻿using System;\r\nusing System.IO;\r\nusing System.Runtime.InteropServices;\r\nusing NLog;\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Properties;\r\nusing Shadowsocks.Util;\r\n\r\nnamespace Shadowsocks.Encryption\r\n{\r\n    public static class MbedTLS\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private const string DLLNAME = \"libsscrypto.dll\";\r\n\r\n        public const int MBEDTLS_ENCRYPT = 1;\r\n        public const int MBEDTLS_DECRYPT = 0;\r\n\r\n        static MbedTLS()\r\n        {\r\n            string dllPath = Utils.GetTempPath(DLLNAME);\r\n            try\r\n            {\r\n                FileManager.UncompressFile(dllPath, Resources.libsscrypto_dll);\r\n            }\r\n            catch (IOException)\r\n            {\r\n            }\r\n            catch (System.Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n            LoadLibrary(dllPath);\r\n        }\r\n\r\n        public static byte[] MD5(byte[] input)\r\n        {\r\n            byte[] output = new byte[16];\r\n            if (md5_ret(input, (uint) input.Length, output) != 0)\r\n                throw new System.Exception(\"mbedtls: MD5 failure\");\r\n            return output;\r\n        }\r\n\r\n        [DllImport(\"Kernel32.dll\")]\r\n        private static extern IntPtr LoadLibrary(string path);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int md5_ret(byte[] input, uint ilen, byte[] output);\r\n\r\n        /// <summary>\r\n        /// Get cipher ctx size for unmanaged memory allocation\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int cipher_get_size_ex();\r\n\r\n        #region Cipher layer wrappers\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern IntPtr cipher_info_from_string(string cipher_name);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void cipher_init(IntPtr ctx);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int cipher_setup(IntPtr ctx, IntPtr cipher_info);\r\n\r\n        // XXX: Check operation before using it\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int cipher_setkey(IntPtr ctx, byte[] key, int key_bitlen, int operation);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int cipher_set_iv(IntPtr ctx, byte[] iv, int iv_len);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int cipher_reset(IntPtr ctx);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int cipher_update(IntPtr ctx, byte[] input, int ilen, byte[] output, ref int olen);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void cipher_free(IntPtr ctx);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int cipher_auth_encrypt(IntPtr ctx,\r\n            byte[] iv, uint iv_len,\r\n            IntPtr ad, uint ad_len,\r\n            byte[] input, uint ilen,\r\n            byte[] output, ref uint olen,\r\n            byte[] tag, uint tag_len);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int cipher_auth_decrypt(IntPtr ctx,\r\n            byte[] iv, uint iv_len,\r\n            IntPtr ad, uint ad_len,\r\n            byte[] input, uint ilen,\r\n            byte[] output, ref uint olen,\r\n            byte[] tag, uint tag_len);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int hkdf(byte[] salt,\r\n            int salt_len, byte[] ikm, int ikm_len,\r\n            byte[] info, int info_len, byte[] okm,\r\n            int okm_len);\r\n\r\n        #endregion\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/OpenSSL.cs",
    "content": "﻿using System;\r\nusing System.IO;\r\nusing System.Runtime.InteropServices;\r\nusing System.Security;\r\nusing System.Text;\r\nusing NLog;\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Encryption.Exception;\r\nusing Shadowsocks.Properties;\r\nusing Shadowsocks.Util;\r\n\r\nnamespace Shadowsocks.Encryption\r\n{\r\n    // XXX: only for OpenSSL 1.1.0 and higher\r\n    public static class OpenSSL\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private const string DLLNAME = \"libsscrypto.dll\";\r\n\r\n        public const int OPENSSL_ENCRYPT = 1;\r\n        public const int OPENSSL_DECRYPT = 0;\r\n\r\n        public const int EVP_CTRL_AEAD_SET_IVLEN = 0x9;\r\n        public const int EVP_CTRL_AEAD_GET_TAG = 0x10;\r\n        public const int EVP_CTRL_AEAD_SET_TAG = 0x11;\r\n\r\n        static OpenSSL()\r\n        {\r\n            string dllPath = Utils.GetTempPath(DLLNAME);\r\n            try\r\n            {\r\n                FileManager.UncompressFile(dllPath, Resources.libsscrypto_dll);\r\n            }\r\n            catch (IOException)\r\n            {\r\n            }\r\n            catch (System.Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n            LoadLibrary(dllPath);\r\n        }\r\n\r\n        public static IntPtr GetCipherInfo(string cipherName)\r\n        {\r\n            var name = Encoding.ASCII.GetBytes(cipherName);\r\n            Array.Resize(ref name, name.Length + 1);\r\n            return EVP_get_cipherbyname(name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Need init cipher context after EVP_CipherFinal_ex to reuse context\r\n        /// </summary>\r\n        /// <param name=\"ctx\"></param>\r\n        /// <param name=\"cipherType\"></param>\r\n        /// <param name=\"nonce\"></param>\r\n        public static void SetCtxNonce(IntPtr ctx, byte[] nonce, bool isEncrypt)\r\n        {\r\n            var ret = EVP_CipherInit_ex(ctx, IntPtr.Zero,\r\n                IntPtr.Zero, null,\r\n                nonce,\r\n                isEncrypt ? OPENSSL_ENCRYPT : OPENSSL_DECRYPT);\r\n            if (ret != 1) throw new System.Exception(\"openssl: fail to set AEAD nonce\");\r\n        }\r\n\r\n        public static void AEADGetTag(IntPtr ctx, byte[] tagbuf, int taglen)\r\n        {\r\n            IntPtr tagBufIntPtr = IntPtr.Zero;\r\n            try\r\n            {\r\n                tagBufIntPtr = Marshal.AllocHGlobal(taglen);\r\n                var ret = EVP_CIPHER_CTX_ctrl(ctx,\r\n                    EVP_CTRL_AEAD_GET_TAG, taglen, tagBufIntPtr);\r\n                if (ret != 1) throw new CryptoErrorException(\"openssl: fail to get AEAD tag\");\r\n                // take tag from unmanaged memory\r\n                Marshal.Copy(tagBufIntPtr, tagbuf, 0, taglen);\r\n            }\r\n            finally\r\n            {\r\n                if (tagBufIntPtr != IntPtr.Zero)\r\n                {\r\n                    Marshal.FreeHGlobal(tagBufIntPtr);\r\n                }\r\n            }\r\n        }\r\n\r\n        public static void AEADSetTag(IntPtr ctx, byte[] tagbuf, int taglen)\r\n        {\r\n            IntPtr tagBufIntPtr = IntPtr.Zero;\r\n            try\r\n            {\r\n                // allocate unmanaged memory for tag\r\n                tagBufIntPtr = Marshal.AllocHGlobal(taglen);\r\n\r\n                // copy tag to unmanaged memory\r\n                Marshal.Copy(tagbuf, 0, tagBufIntPtr, taglen);\r\n\r\n                var ret = EVP_CIPHER_CTX_ctrl(ctx,\r\n                    EVP_CTRL_AEAD_SET_TAG, taglen, tagBufIntPtr);\r\n\r\n                if (ret != 1) throw new CryptoErrorException(\"openssl: fail to set AEAD tag\");\r\n\r\n            }\r\n            finally\r\n            {\r\n                if (tagBufIntPtr != IntPtr.Zero)\r\n                {\r\n                    Marshal.FreeHGlobal(tagBufIntPtr);\r\n                }\r\n            }\r\n        }\r\n\r\n        [DllImport(\"Kernel32.dll\")]\r\n        private static extern IntPtr LoadLibrary(string path);\r\n\r\n        [SuppressUnmanagedCodeSecurity]\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern IntPtr EVP_CIPHER_CTX_new();\r\n\r\n        [SuppressUnmanagedCodeSecurity]\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void EVP_CIPHER_CTX_free(IntPtr ctx);\r\n\r\n        [SuppressUnmanagedCodeSecurity]\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int EVP_CIPHER_CTX_reset(IntPtr ctx);\r\n\r\n        [SuppressUnmanagedCodeSecurity]\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int EVP_CipherInit_ex(IntPtr ctx, IntPtr type,\r\n            IntPtr impl, byte[] key, byte[] iv, int enc);\r\n\r\n        [SuppressUnmanagedCodeSecurity]\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int EVP_CipherUpdate(IntPtr ctx, byte[] outb,\r\n            out int outl, byte[] inb, int inl);\r\n\r\n        [SuppressUnmanagedCodeSecurity]\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int EVP_CipherFinal_ex(IntPtr ctx, byte[] outm, ref int outl);\r\n\r\n        [SuppressUnmanagedCodeSecurity]\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int EVP_CIPHER_CTX_set_padding(IntPtr x, int padding);\r\n\r\n        [SuppressUnmanagedCodeSecurity]\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int EVP_CIPHER_CTX_set_key_length(IntPtr x, int keylen);\r\n\r\n        [SuppressUnmanagedCodeSecurity]\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int EVP_CIPHER_CTX_ctrl(IntPtr ctx, int type, int arg, IntPtr ptr);\r\n\r\n        /// <summary>\r\n        /// simulate NUL-terminated string\r\n        /// </summary>\r\n        /// <param name=\"name\"></param>\r\n        /// <returns></returns>\r\n        [SuppressUnmanagedCodeSecurity]\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern IntPtr EVP_get_cipherbyname(byte[] name);\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/RNG.cs",
    "content": "﻿using System;\r\nusing System.Security.Cryptography;\r\n\r\nnamespace Shadowsocks.Encryption\r\n{\r\n    public static class RNG\r\n    {\r\n        private static RNGCryptoServiceProvider _rng = null;\r\n\r\n        public static void Init()\r\n        {\r\n            _rng = _rng ?? new RNGCryptoServiceProvider();\r\n        }\r\n\r\n        public static void Close()\r\n        {\r\n            _rng?.Dispose();\r\n            _rng = null;\r\n        }\r\n\r\n        public static void Reload()\r\n        {\r\n            Close();\r\n            Init();\r\n        }\r\n\r\n        public static void GetBytes(byte[] buf)\r\n        {\r\n            GetBytes(buf, buf.Length);\r\n        }\r\n\r\n        public static void GetBytes(byte[] buf, int len)\r\n        {\r\n            if (_rng == null) Init();\r\n            try\r\n            {\r\n                _rng.GetBytes(buf, 0, len);\r\n            }\r\n            catch\r\n            {\r\n                // the backup way\r\n                byte[] tmp = new byte[len];\r\n                _rng.GetBytes(tmp);\r\n                Buffer.BlockCopy(tmp, 0, buf, 0, len);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/Sodium.cs",
    "content": "﻿using System;\r\nusing System.IO;\r\nusing System.Runtime.InteropServices;\r\nusing NLog;\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Properties;\r\nusing Shadowsocks.Util;\r\n\r\nnamespace Shadowsocks.Encryption\r\n{\r\n    public static class Sodium\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private const string DLLNAME = \"libsscrypto.dll\";\r\n\r\n        private static bool _initialized = false;\r\n        private static readonly object _initLock = new object();\r\n\r\n        public static bool AES256GCMAvailable { get; private set; } = false;\r\n\r\n        static Sodium()\r\n        {\r\n            string dllPath = Utils.GetTempPath(DLLNAME);\r\n            try\r\n            {\r\n                FileManager.UncompressFile(dllPath, Resources.libsscrypto_dll);\r\n            }\r\n            catch (IOException)\r\n            {\r\n            }\r\n            catch (System.Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n            LoadLibrary(dllPath);\r\n\r\n            lock (_initLock)\r\n            {\r\n                if (!_initialized)\r\n                {\r\n                    if (sodium_init() == -1)\r\n                    {\r\n                        throw new System.Exception(\"Failed to initialize sodium\");\r\n                    }\r\n                    else /* 1 means already initialized; 0 means success */\r\n                    {\r\n                        _initialized = true;\r\n                    }\r\n\r\n                    AES256GCMAvailable = crypto_aead_aes256gcm_is_available() == 1;\r\n                    logger.Debug($\"sodium: AES256GCMAvailable is {AES256GCMAvailable}\");\r\n                }\r\n            }\r\n        }\r\n\r\n        [DllImport(\"Kernel32.dll\")]\r\n        private static extern IntPtr LoadLibrary(string path);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern int sodium_init();\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern int crypto_aead_aes256gcm_is_available();\r\n\r\n        #region AEAD\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int sodium_increment(byte[] n, int nlen);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int crypto_aead_chacha20poly1305_ietf_encrypt(byte[] c, ref ulong clen_p, byte[] m,\r\n            ulong mlen, byte[] ad, ulong adlen, byte[] nsec, byte[] npub, byte[] k);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int crypto_aead_chacha20poly1305_ietf_decrypt(byte[] m, ref ulong mlen_p,\r\n            byte[] nsec, byte[] c, ulong clen, byte[] ad, ulong adlen, byte[] npub, byte[] k);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int crypto_aead_xchacha20poly1305_ietf_encrypt(byte[] c, ref ulong clen_p, byte[] m, ulong mlen,\r\n            byte[] ad, ulong adlen, byte[] nsec, byte[] npub, byte[] k);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int crypto_aead_xchacha20poly1305_ietf_decrypt(byte[] m, ref ulong mlen_p, byte[] nsec, byte[] c,\r\n            ulong clen, byte[] ad, ulong adlen, byte[] npub, byte[] k);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int crypto_aead_aes256gcm_encrypt(byte[] c, ref ulong clen_p, byte[] m, ulong mlen,\r\n            byte[] ad, ulong adlen, byte[] nsec, byte[] npub, byte[] k);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int crypto_aead_aes256gcm_decrypt(byte[] m, ref ulong mlen_p, byte[] nsec, byte[] c,\r\n            ulong clen, byte[] ad, ulong adlen, byte[] npub, byte[] k);\r\n\r\n        #endregion\r\n\r\n        #region Stream\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int crypto_stream_salsa20_xor_ic(byte[] c, byte[] m, ulong mlen, byte[] n, ulong ic,\r\n            byte[] k);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int crypto_stream_chacha20_xor_ic(byte[] c, byte[] m, ulong mlen, byte[] n, ulong ic,\r\n            byte[] k);\r\n\r\n        [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int crypto_stream_chacha20_ietf_xor_ic(byte[] c, byte[] m, ulong mlen, byte[] n, uint ic,\r\n            byte[] k);\r\n\r\n        #endregion\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Encryption/Stream/PlainEncryptor.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\n\nnamespace Shadowsocks.Encryption.Stream\n{\n    class PlainEncryptor\n        : EncryptorBase, IDisposable\n    {\n        const int CIPHER_NONE = 1;\n\n        private static Dictionary<string, EncryptorInfo> _ciphers = new Dictionary<string, EncryptorInfo> {\n            { \"plain\", new EncryptorInfo(\"PLAIN\", 0, 0, CIPHER_NONE) },\n            { \"none\", new EncryptorInfo(\"PLAIN\", 0, 0, CIPHER_NONE) }\n        };\n\n        public PlainEncryptor(string method, string password) : base(method, password)\n        {\n        }\n\n        public static List<string> SupportedCiphers()\n        {\n            return new List<string>(_ciphers.Keys);\n        }\n\n        protected Dictionary<string, EncryptorInfo> getCiphers()\n        {\n            return _ciphers;\n        }\n\n        #region TCP\n\n        public override void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength)\n        {\n            Buffer.BlockCopy(buf, 0, outbuf, 0, length);\n            outlength = length;\n        }\n\n        public override void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength)\n        {\n            Buffer.BlockCopy(buf, 0, outbuf, 0, length);\n            outlength = length;\n        }\n\n        #endregion\n\n        #region UDP\n\n        public override void EncryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)\n        {\n            Buffer.BlockCopy(buf, 0, outbuf, 0, length);\n            outlength = length;\n        }\n\n        public override void DecryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)\n        {\n            Buffer.BlockCopy(buf, 0, outbuf, 0, length);\n            outlength = length;\n        }\n\n        #endregion\n\n\n        #region IDisposable\n\n        private bool _disposed;\n\n        // instance based lock\n        private readonly object _lock = new object();\n\n        public override void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        ~PlainEncryptor()\n        {\n            Dispose(false);\n        }\n\n        protected virtual void Dispose(bool disposing)\n        {\n            lock (_lock)\n            {\n                if (_disposed) return;\n                _disposed = true;\n            }\n\n            if (disposing)\n            {\n                // free managed objects\n            }\n        }\n\n        #endregion\n\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/FodyWeavers.xml",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Weavers xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"FodyWeavers.xsd\">\r\n  <Caseless StringComparison=\"Ordinal\" />\r\n  <Costura />\r\n  <ReactiveUI />\r\n</Weavers>"
  },
  {
    "path": "shadowsocks-csharp/FodyWeavers.xsd",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\r\n  <!-- This file was generated by Fody. Manual changes to this file will be lost when your project is rebuilt. -->\r\n  <xs:element name=\"Weavers\">\r\n    <xs:complexType>\r\n      <xs:all>\r\n        <xs:element name=\"ReactiveUI\" minOccurs=\"0\" maxOccurs=\"1\" type=\"xs:anyType\" />\r\n        <xs:element name=\"Costura\" minOccurs=\"0\" maxOccurs=\"1\">\r\n          <xs:complexType>\r\n            <xs:all>\r\n              <xs:element minOccurs=\"0\" maxOccurs=\"1\" name=\"ExcludeAssemblies\" type=\"xs:string\">\r\n                <xs:annotation>\r\n                  <xs:documentation>A list of assembly names to exclude from the default action of \"embed all Copy Local references\", delimited with line breaks</xs:documentation>\r\n                </xs:annotation>\r\n              </xs:element>\r\n              <xs:element minOccurs=\"0\" maxOccurs=\"1\" name=\"IncludeAssemblies\" type=\"xs:string\">\r\n                <xs:annotation>\r\n                  <xs:documentation>A list of assembly names to include from the default action of \"embed all Copy Local references\", delimited with line breaks.</xs:documentation>\r\n                </xs:annotation>\r\n              </xs:element>\r\n              <xs:element minOccurs=\"0\" maxOccurs=\"1\" name=\"Unmanaged32Assemblies\" type=\"xs:string\">\r\n                <xs:annotation>\r\n                  <xs:documentation>A list of unmanaged 32 bit assembly names to include, delimited with line breaks.</xs:documentation>\r\n                </xs:annotation>\r\n              </xs:element>\r\n              <xs:element minOccurs=\"0\" maxOccurs=\"1\" name=\"Unmanaged64Assemblies\" type=\"xs:string\">\r\n                <xs:annotation>\r\n                  <xs:documentation>A list of unmanaged 64 bit assembly names to include, delimited with line breaks.</xs:documentation>\r\n                </xs:annotation>\r\n              </xs:element>\r\n              <xs:element minOccurs=\"0\" maxOccurs=\"1\" name=\"PreloadOrder\" type=\"xs:string\">\r\n                <xs:annotation>\r\n                  <xs:documentation>The order of preloaded assemblies, delimited with line breaks.</xs:documentation>\r\n                </xs:annotation>\r\n              </xs:element>\r\n            </xs:all>\r\n            <xs:attribute name=\"CreateTemporaryAssemblies\" type=\"xs:boolean\">\r\n              <xs:annotation>\r\n                <xs:documentation>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.</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n            <xs:attribute name=\"IncludeDebugSymbols\" type=\"xs:boolean\">\r\n              <xs:annotation>\r\n                <xs:documentation>Controls if .pdbs for reference assemblies are also embedded.</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n            <xs:attribute name=\"DisableCompression\" type=\"xs:boolean\">\r\n              <xs:annotation>\r\n                <xs:documentation>Embedded assemblies are compressed by default, and uncompressed when they are loaded. You can turn compression off with this option.</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n            <xs:attribute name=\"DisableCleanup\" type=\"xs:boolean\">\r\n              <xs:annotation>\r\n                <xs:documentation>As part of Costura, embedded assemblies are no longer included as part of the build. This cleanup can be turned off.</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n            <xs:attribute name=\"LoadAtModuleInit\" type=\"xs:boolean\">\r\n              <xs:annotation>\r\n                <xs:documentation>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.</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n            <xs:attribute name=\"IgnoreSatelliteAssemblies\" type=\"xs:boolean\">\r\n              <xs:annotation>\r\n                <xs:documentation>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.</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n            <xs:attribute name=\"ExcludeAssemblies\" type=\"xs:string\">\r\n              <xs:annotation>\r\n                <xs:documentation>A list of assembly names to exclude from the default action of \"embed all Copy Local references\", delimited with |</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n            <xs:attribute name=\"IncludeAssemblies\" type=\"xs:string\">\r\n              <xs:annotation>\r\n                <xs:documentation>A list of assembly names to include from the default action of \"embed all Copy Local references\", delimited with |.</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n            <xs:attribute name=\"Unmanaged32Assemblies\" type=\"xs:string\">\r\n              <xs:annotation>\r\n                <xs:documentation>A list of unmanaged 32 bit assembly names to include, delimited with |.</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n            <xs:attribute name=\"Unmanaged64Assemblies\" type=\"xs:string\">\r\n              <xs:annotation>\r\n                <xs:documentation>A list of unmanaged 64 bit assembly names to include, delimited with |.</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n            <xs:attribute name=\"PreloadOrder\" type=\"xs:string\">\r\n              <xs:annotation>\r\n                <xs:documentation>The order of preloaded assemblies, delimited with |.</xs:documentation>\r\n              </xs:annotation>\r\n            </xs:attribute>\r\n          </xs:complexType>\r\n        </xs:element>\r\n        <xs:element name=\"Caseless\" minOccurs=\"0\" maxOccurs=\"1\" type=\"xs:anyType\" />\r\n      </xs:all>\r\n      <xs:attribute name=\"VerifyAssembly\" type=\"xs:boolean\">\r\n        <xs:annotation>\r\n          <xs:documentation>'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.</xs:documentation>\r\n        </xs:annotation>\r\n      </xs:attribute>\r\n      <xs:attribute name=\"VerifyIgnoreCodes\" type=\"xs:string\">\r\n        <xs:annotation>\r\n          <xs:documentation>A comma-separated list of error codes that can be safely ignored in assembly verification.</xs:documentation>\r\n        </xs:annotation>\r\n      </xs:attribute>\r\n      <xs:attribute name=\"GenerateXsd\" type=\"xs:boolean\">\r\n        <xs:annotation>\r\n          <xs:documentation>'false' to turn off automatic generation of the XML Schema file.</xs:documentation>\r\n        </xs:annotation>\r\n      </xs:attribute>\r\n    </xs:complexType>\r\n  </xs:element>\r\n</xs:schema>"
  },
  {
    "path": "shadowsocks-csharp/Localization/LocalizationProvider.cs",
    "content": "﻿using System.Reflection;\nusing WPFLocalizeExtension.Extensions;\n\nnamespace Shadowsocks.Localization\n{\n    public static class LocalizationProvider\n    {\n        public static T GetLocalizedValue<T>(string key)\n        {\n            return LocExtension.GetLocalizedValue<T>(Assembly.GetCallingAssembly().GetName().Name + \":Strings:\" + key);\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Localization/Strings.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.42000\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace Shadowsocks.Localization {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"16.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class Strings {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal Strings() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Shadowsocks.Localization.Strings\", typeof(Strings).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to _Add.\n        /// </summary>\n        internal static string addButton_Content {\n            get {\n                return ResourceManager.GetString(\"addButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Address.\n        /// </summary>\n        internal static string Address {\n            get {\n                return ResourceManager.GetString(\"Address\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Allow clients from LAN.\n        /// </summary>\n        internal static string AllowClientsFromLAN {\n            get {\n                return ResourceManager.GetString(\"AllowClientsFromLAN\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to _Cancel.\n        /// </summary>\n        internal static string cancelButton_Content {\n            get {\n                return ResourceManager.GetString(\"cancelButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to _Copy.\n        /// </summary>\n        internal static string Copy {\n            get {\n                return ResourceManager.GetString(\"Copy\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to _Copy link.\n        /// </summary>\n        internal static string copyLinkButton_Content {\n            get {\n                return ResourceManager.GetString(\"copyLinkButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Credentials (optional).\n        /// </summary>\n        internal static string CredentialsOptional {\n            get {\n                return ResourceManager.GetString(\"CredentialsOptional\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Details.\n        /// </summary>\n        internal static string Details {\n            get {\n                return ResourceManager.GetString(\"Details\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Forward Proxy.\n        /// </summary>\n        internal static string ForwardProxy {\n            get {\n                return ResourceManager.GetString(\"ForwardProxy\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Hotkeys.\n        /// </summary>\n        internal static string Hotkeys {\n            get {\n                return ResourceManager.GetString(\"Hotkeys\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to HTTP.\n        /// </summary>\n        internal static string HTTP {\n            get {\n                return ResourceManager.GetString(\"HTTP\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No proxy.\n        /// </summary>\n        internal static string NoProxy {\n            get {\n                return ResourceManager.GetString(\"NoProxy\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to _Not now.\n        /// </summary>\n        internal static string notNowButton_Content {\n            get {\n                return ResourceManager.GetString(\"notNowButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to _OK.\n        /// </summary>\n        internal static string okButton_Content {\n            get {\n                return ResourceManager.GetString(\"okButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Online Configuration Delivery.\n        /// </summary>\n        internal static string OnlineConfigDelivery {\n            get {\n                return ResourceManager.GetString(\"OnlineConfigDelivery\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Open logs window.\n        /// </summary>\n        internal static string OpenLogsWindow {\n            get {\n                return ResourceManager.GetString(\"OpenLogsWindow\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Password.\n        /// </summary>\n        internal static string Password {\n            get {\n                return ResourceManager.GetString(\"Password\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Port.\n        /// </summary>\n        internal static string Port {\n            get {\n                return ResourceManager.GetString(\"Port\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to _Register all.\n        /// </summary>\n        internal static string registerAllButton_Content {\n            get {\n                return ResourceManager.GetString(\"registerAllButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Register hotkeys at startup.\n        /// </summary>\n        internal static string RegisterHotkeysAtStartup {\n            get {\n                return ResourceManager.GetString(\"RegisterHotkeysAtStartup\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Remove.\n        /// </summary>\n        internal static string removeButton_Content {\n            get {\n                return ResourceManager.GetString(\"removeButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to _Save.\n        /// </summary>\n        internal static string saveButton_Content {\n            get {\n                return ResourceManager.GetString(\"saveButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Server Sharing.\n        /// </summary>\n        internal static string ServerSharing {\n            get {\n                return ResourceManager.GetString(\"ServerSharing\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The following sources failed to update:\\n\\n.\n        /// </summary>\n        internal static string sip008UpdateAllFailure {\n            get {\n                return ResourceManager.GetString(\"sip008UpdateAllFailure\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Successfully updated all sources!.\n        /// </summary>\n        internal static string sip008UpdateAllSuccess {\n            get {\n                return ResourceManager.GetString(\"sip008UpdateAllSuccess\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Update failed. See the logs for more information..\n        /// </summary>\n        internal static string sip008UpdateFailure {\n            get {\n                return ResourceManager.GetString(\"sip008UpdateFailure\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Successfully updated the selected source!.\n        /// </summary>\n        internal static string sip008UpdateSuccess {\n            get {\n                return ResourceManager.GetString(\"sip008UpdateSuccess\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to _Skip version.\n        /// </summary>\n        internal static string skipVersionButton_Content {\n            get {\n                return ResourceManager.GetString(\"skipVersionButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to SOCKS5.\n        /// </summary>\n        internal static string SOCKS5 {\n            get {\n                return ResourceManager.GetString(\"SOCKS5\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Switch to next server.\n        /// </summary>\n        internal static string SwitchToNextServer {\n            get {\n                return ResourceManager.GetString(\"SwitchToNextServer\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Switch to previous server.\n        /// </summary>\n        internal static string SwitchToPreviousServer {\n            get {\n                return ResourceManager.GetString(\"SwitchToPreviousServer\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Timeout (sec).\n        /// </summary>\n        internal static string Timeout {\n            get {\n                return ResourceManager.GetString(\"Timeout\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Toggle proxy mode.\n        /// </summary>\n        internal static string ToggleProxyMode {\n            get {\n                return ResourceManager.GetString(\"ToggleProxyMode\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Toggle system proxy.\n        /// </summary>\n        internal static string ToggleSystemProxy {\n            get {\n                return ResourceManager.GetString(\"ToggleSystemProxy\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Type.\n        /// </summary>\n        internal static string Type {\n            get {\n                return ResourceManager.GetString(\"Type\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Update all.\n        /// </summary>\n        internal static string updateAllButton_Content {\n            get {\n                return ResourceManager.GetString(\"updateAllButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to _Update.\n        /// </summary>\n        internal static string updateButton_Content {\n            get {\n                return ResourceManager.GetString(\"updateButton_Content\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Please read the release notes carefully. Then decide whether to update..\n        /// </summary>\n        internal static string updatePromptBody {\n            get {\n                return ResourceManager.GetString(\"updatePromptBody\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An update is available..\n        /// </summary>\n        internal static string updatePromptTitle {\n            get {\n                return ResourceManager.GetString(\"updatePromptTitle\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Username.\n        /// </summary>\n        internal static string Username {\n            get {\n                return ResourceManager.GetString(\"Username\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to VersionUpdate.\n        /// </summary>\n        internal static string VersionUpdate {\n            get {\n                return ResourceManager.GetString(\"VersionUpdate\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Localization/Strings.fr.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Password\" xml:space=\"preserve\">\n    <value>Mot de passe</value>\n  </data>\n  <data name=\"Port\" xml:space=\"preserve\">\n    <value>Port</value>\n  </data>\n  <data name=\"Type\" xml:space=\"preserve\">\n    <value>Type</value>\n  </data>\n  <data name=\"Address\" xml:space=\"preserve\">\n    <value>adresse</value>\n  </data>\n  <data name=\"Timeout\" xml:space=\"preserve\">\n    <value>Délai d'attente (sec)</value>\n  </data>\n  <data name=\"cancelButton_Content\" xml:space=\"preserve\">\n    <value>Annuler</value>\n  </data>\n  <data name=\"okButton_Content\" xml:space=\"preserve\">\n    <value>OK</value>\n  </data>\n  <data name=\"ToggleSystemProxy\" xml:space=\"preserve\">\n    <value>Changer l'état de proxy système</value>\n  </data>\n  <data name=\"ToggleProxyMode\" xml:space=\"preserve\">\n    <value>Changer le mode de proxy système</value>\n  </data>\n  <data name=\"AllowClientsFromLAN\" xml:space=\"preserve\">\n    <value>Autoriser les clients du LAN</value>\n  </data>\n  <data name=\"OpenLogsWindow\" xml:space=\"preserve\">\n    <value>Afficher les journaux</value>\n  </data>\n  <data name=\"SwitchToPreviousServer\" xml:space=\"preserve\">\n    <value>Passer au serveur précédent</value>\n  </data>\n  <data name=\"SwitchToNextServer\" xml:space=\"preserve\">\n    <value>Passer au serveur suivant</value>\n  </data>\n  <data name=\"RegisterHotkeysAtStartup\" xml:space=\"preserve\">\n    <value>Enregistrer tout</value>\n  </data>\n  <data name=\"registerAllButton_Content\" xml:space=\"preserve\">\n    <value>Enregistrer tout au démarrage</value>\n  </data>\n  <data name=\"addButton_Content\" xml:space=\"preserve\">\n    <value>Ajouter</value>\n  </data>\n  <data name=\"skipVersionButton_Content\" xml:space=\"preserve\">\n    <value>sauter la version</value>\n  </data>\n  <data name=\"copyLinkButton_Content\" xml:space=\"preserve\">\n    <value>Copier le lien</value>\n  </data>\n  <data name=\"removeButton_Content\" xml:space=\"preserve\">\n    <value>retirer</value>\n  </data>\n  <data name=\"updateButton_Content\" xml:space=\"preserve\">\n    <value>mise à jour</value>\n  </data>\n  <data name=\"Copy\" xml:space=\"preserve\">\n    <value>copie</value>\n  </data>\n</root>"
  },
  {
    "path": "shadowsocks-csharp/Localization/Strings.ja.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Password\" xml:space=\"preserve\">\n    <value>パスワード</value>\n  </data>\n  <data name=\"Type\" xml:space=\"preserve\">\n    <value>タイプ</value>\n  </data>\n  <data name=\"Address\" xml:space=\"preserve\">\n    <value>アドレス</value>\n  </data>\n  <data name=\"Port\" xml:space=\"preserve\">\n    <value>ポート</value>\n  </data>\n  <data name=\"Timeout\" xml:space=\"preserve\">\n    <value>タイムアウト (秒)</value>\n  </data>\n  <data name=\"cancelButton_Content\" xml:space=\"preserve\">\n    <value>キャンセル</value>\n  </data>\n  <data name=\"okButton_Content\" xml:space=\"preserve\">\n    <value>OK</value>\n  </data>\n  <data name=\"ToggleSystemProxy\" xml:space=\"preserve\">\n    <value>システム プロキシの状態を切り替える</value>\n  </data>\n  <data name=\"ToggleProxyMode\" xml:space=\"preserve\">\n    <value>プロキシモードを切り替える</value>\n  </data>\n  <data name=\"AllowClientsFromLAN\" xml:space=\"preserve\">\n    <value>LAN からのアクセスの許可を切り替える</value>\n  </data>\n  <data name=\"OpenLogsWindow\" xml:space=\"preserve\">\n    <value>ログの表示</value>\n  </data>\n  <data name=\"SwitchToPreviousServer\" xml:space=\"preserve\">\n    <value>前のサーバーに切り替える</value>\n  </data>\n  <data name=\"SwitchToNextServer\" xml:space=\"preserve\">\n    <value>次のサーバーに切り替える</value>\n  </data>\n  <data name=\"RegisterHotkeysAtStartup\" xml:space=\"preserve\">\n    <value>全部登録する</value>\n  </data>\n  <data name=\"registerAllButton_Content\" xml:space=\"preserve\">\n    <value>起動時にホットキーを登録する</value>\n  </data>\n  <data name=\"addButton_Content\" xml:space=\"preserve\">\n    <value>新規</value>\n  </data>\n  <data name=\"skipVersionButton_Content\" xml:space=\"preserve\">\n    <value>バージョンをスキップ</value>\n  </data>\n  <data name=\"copyLinkButton_Content\" xml:space=\"preserve\">\n    <value>リンクをコピーする</value>\n  </data>\n  <data name=\"updateButton_Content\" xml:space=\"preserve\">\n    <value>更新</value>\n  </data>\n  <data name=\"Copy\" xml:space=\"preserve\">\n    <value>コピー</value>\n  </data>\n</root>"
  },
  {
    "path": "shadowsocks-csharp/Localization/Strings.ko.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Password\" xml:space=\"preserve\">\n    <value>비밀번호</value>\n  </data>\n  <data name=\"Type\" xml:space=\"preserve\">\n    <value>유형</value>\n  </data>\n  <data name=\"Address\" xml:space=\"preserve\">\n    <value>주소</value>\n  </data>\n  <data name=\"Port\" xml:space=\"preserve\">\n    <value>포트</value>\n  </data>\n  <data name=\"Timeout\" xml:space=\"preserve\">\n    <value>시간 초과 (초)</value>\n  </data>\n  <data name=\"cancelButton_Content\" xml:space=\"preserve\">\n    <value>취소</value>\n  </data>\n  <data name=\"okButton_Content\" xml:space=\"preserve\">\n    <value>확인</value>\n  </data>\n  <data name=\"ToggleSystemProxy\" xml:space=\"preserve\">\n    <value>시스템 프록시 전환</value>\n  </data>\n  <data name=\"ToggleProxyMode\" xml:space=\"preserve\">\n    <value>시스템 프록시 모드 전환</value>\n  </data>\n  <data name=\"AllowClientsFromLAN\" xml:space=\"preserve\">\n    <value>LAN으로부터 클라이언트 허용</value>\n  </data>\n  <data name=\"OpenLogsWindow\" xml:space=\"preserve\">\n    <value>로그 보기…</value>\n  </data>\n  <data name=\"SwitchToPreviousServer\" xml:space=\"preserve\">\n    <value>이전 서버로 전환</value>\n  </data>\n  <data name=\"SwitchToNextServer\" xml:space=\"preserve\">\n    <value>다음 서버로 전환</value>\n  </data>\n  <data name=\"RegisterHotkeysAtStartup\" xml:space=\"preserve\">\n    <value>모두 등록</value>\n  </data>\n  <data name=\"registerAllButton_Content\" xml:space=\"preserve\">\n    <value>시스템 시작 시 단축키 등록</value>\n  </data>\n  <data name=\"addButton_Content\" xml:space=\"preserve\">\n    <value>추가</value>\n  </data>\n  <data name=\"skipVersionButton_Content\" xml:space=\"preserve\">\n    <value>버전 건너 뛰기</value>\n  </data>\n  <data name=\"copyLinkButton_Content\" xml:space=\"preserve\">\n    <value>링크 복사</value>\n  </data>\n  <data name=\"updateButton_Content\" xml:space=\"preserve\">\n    <value>새롭게 함</value>\n  </data>\n  <data name=\"Copy\" xml:space=\"preserve\">\n    <value>부</value>\n  </data>\n</root>"
  },
  {
    "path": "shadowsocks-csharp/Localization/Strings.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Type\" xml:space=\"preserve\">\n    <value>Type</value>\n  </data>\n  <data name=\"NoProxy\" xml:space=\"preserve\">\n    <value>No proxy</value>\n  </data>\n  <data name=\"SOCKS5\" xml:space=\"preserve\">\n    <value>SOCKS5</value>\n  </data>\n  <data name=\"HTTP\" xml:space=\"preserve\">\n    <value>HTTP</value>\n  </data>\n  <data name=\"Details\" xml:space=\"preserve\">\n    <value>Details</value>\n  </data>\n  <data name=\"Address\" xml:space=\"preserve\">\n    <value>Address</value>\n  </data>\n  <data name=\"Port\" xml:space=\"preserve\">\n    <value>Port</value>\n  </data>\n  <data name=\"Timeout\" xml:space=\"preserve\">\n    <value>Timeout (sec)</value>\n  </data>\n  <data name=\"CredentialsOptional\" xml:space=\"preserve\">\n    <value>Credentials (optional)</value>\n  </data>\n  <data name=\"Username\" xml:space=\"preserve\">\n    <value>Username</value>\n  </data>\n  <data name=\"Password\" xml:space=\"preserve\">\n    <value>Password</value>\n  </data>\n  <data name=\"saveButton_Content\" xml:space=\"preserve\">\n    <value>_Save</value>\n  </data>\n  <data name=\"cancelButton_Content\" xml:space=\"preserve\">\n    <value>_Cancel</value>\n  </data>\n  <data name=\"okButton_Content\" xml:space=\"preserve\">\n    <value>_OK</value>\n  </data>\n  <data name=\"ToggleSystemProxy\" xml:space=\"preserve\">\n    <value>Toggle system proxy</value>\n  </data>\n  <data name=\"ToggleProxyMode\" xml:space=\"preserve\">\n    <value>Toggle proxy mode</value>\n  </data>\n  <data name=\"AllowClientsFromLAN\" xml:space=\"preserve\">\n    <value>Allow clients from LAN</value>\n  </data>\n  <data name=\"OpenLogsWindow\" xml:space=\"preserve\">\n    <value>Open logs window</value>\n  </data>\n  <data name=\"SwitchToPreviousServer\" xml:space=\"preserve\">\n    <value>Switch to previous server</value>\n  </data>\n  <data name=\"SwitchToNextServer\" xml:space=\"preserve\">\n    <value>Switch to next server</value>\n  </data>\n  <data name=\"RegisterHotkeysAtStartup\" xml:space=\"preserve\">\n    <value>Register hotkeys at startup</value>\n  </data>\n  <data name=\"registerAllButton_Content\" xml:space=\"preserve\">\n    <value>_Register all</value>\n  </data>\n  <data name=\"updateButton_Content\" xml:space=\"preserve\">\n    <value>_Update</value>\n  </data>\n  <data name=\"updateAllButton_Content\" xml:space=\"preserve\">\n    <value>Update all</value>\n  </data>\n  <data name=\"copyLinkButton_Content\" xml:space=\"preserve\">\n    <value>_Copy link</value>\n  </data>\n  <data name=\"removeButton_Content\" xml:space=\"preserve\">\n    <value>Remove</value>\n  </data>\n  <data name=\"addButton_Content\" xml:space=\"preserve\">\n    <value>_Add</value>\n  </data>\n  <data name=\"updatePromptTitle\" xml:space=\"preserve\">\n    <value>An update is available.</value>\n  </data>\n  <data name=\"updatePromptBody\" xml:space=\"preserve\">\n    <value>Please read the release notes carefully. Then decide whether to update.</value>\n  </data>\n  <data name=\"skipVersionButton_Content\" xml:space=\"preserve\">\n    <value>_Skip version</value>\n  </data>\n  <data name=\"notNowButton_Content\" xml:space=\"preserve\">\n    <value>_Not now</value>\n  </data>\n  <data name=\"Copy\" xml:space=\"preserve\">\n    <value>_Copy</value>\n  </data>\n  <data name=\"ForwardProxy\" xml:space=\"preserve\">\n    <value>Forward Proxy</value>\n  </data>\n  <data name=\"ServerSharing\" xml:space=\"preserve\">\n    <value>Server Sharing</value>\n  </data>\n  <data name=\"Hotkeys\" xml:space=\"preserve\">\n    <value>Hotkeys</value>\n  </data>\n  <data name=\"OnlineConfigDelivery\" xml:space=\"preserve\">\n    <value>Online Configuration Delivery</value>\n  </data>\n  <data name=\"VersionUpdate\" xml:space=\"preserve\">\n    <value>VersionUpdate</value>\n  </data>\n  <data name=\"sip008UpdateSuccess\" xml:space=\"preserve\">\n    <value>Successfully updated the selected source!</value>\n  </data>\n  <data name=\"sip008UpdateFailure\" xml:space=\"preserve\">\n    <value>Update failed. See the logs for more information.</value>\n  </data>\n  <data name=\"sip008UpdateAllSuccess\" xml:space=\"preserve\">\n    <value>Successfully updated all sources!</value>\n  </data>\n  <data name=\"sip008UpdateAllFailure\" xml:space=\"preserve\">\n    <value>The following sources failed to update:\\n\\n</value>\n  </data>\n</root>"
  },
  {
    "path": "shadowsocks-csharp/Localization/Strings.ru.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Password\" xml:space=\"preserve\">\n    <value>Пароль</value>\n  </data>\n  <data name=\"Type\" xml:space=\"preserve\">\n    <value>тип</value>\n  </data>\n  <data name=\"Address\" xml:space=\"preserve\">\n    <value>адрес</value>\n  </data>\n  <data name=\"Port\" xml:space=\"preserve\">\n    <value>порт</value>\n  </data>\n  <data name=\"Timeout\" xml:space=\"preserve\">\n    <value>Таймаут (сек)</value>\n  </data>\n  <data name=\"cancelButton_Content\" xml:space=\"preserve\">\n    <value>Отмена</value>\n  </data>\n  <data name=\"okButton_Content\" xml:space=\"preserve\">\n    <value>ОК</value>\n  </data>\n  <data name=\"ToggleSystemProxy\" xml:space=\"preserve\">\n    <value>ВКЛ/ВЫКЛ системный прокси-сервер</value>\n  </data>\n  <data name=\"ToggleProxyMode\" xml:space=\"preserve\">\n    <value>Переключение режима прокси-сервера</value>\n  </data>\n  <data name=\"AllowClientsFromLAN\" xml:space=\"preserve\">\n    <value>Общий доступ к подключению</value>\n  </data>\n  <data name=\"OpenLogsWindow\" xml:space=\"preserve\">\n    <value>Просмотр журналов</value>\n  </data>\n  <data name=\"SwitchToPreviousServer\" xml:space=\"preserve\">\n    <value>Переключить на пред. сервер</value>\n  </data>\n  <data name=\"SwitchToNextServer\" xml:space=\"preserve\">\n    <value>Переключить на след. сервер</value>\n  </data>\n  <data name=\"RegisterHotkeysAtStartup\" xml:space=\"preserve\">\n    <value>Применить все</value>\n  </data>\n  <data name=\"registerAllButton_Content\" xml:space=\"preserve\">\n    <value>Применять при запуске программы</value>\n  </data>\n  <data name=\"addButton_Content\" xml:space=\"preserve\">\n    <value>Добавить</value>\n  </data>\n  <data name=\"skipVersionButton_Content\" xml:space=\"preserve\">\n    <value>пропустить версию</value>\n  </data>\n  <data name=\"copyLinkButton_Content\" xml:space=\"preserve\">\n    <value>копировать ссылку</value>\n  </data>\n  <data name=\"removeButton_Content\" xml:space=\"preserve\">\n    <value>Удалить</value>\n  </data>\n  <data name=\"updateButton_Content\" xml:space=\"preserve\">\n    <value>Обновить</value>\n  </data>\n  <data name=\"Copy\" xml:space=\"preserve\">\n    <value>копировать</value>\n  </data>\n</root>"
  },
  {
    "path": "shadowsocks-csharp/Localization/Strings.zh-Hans.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"NoProxy\" xml:space=\"preserve\">\n    <value>不使用代理</value>\n  </data>\n  <data name=\"Type\" xml:space=\"preserve\">\n    <value>类型</value>\n  </data>\n  <data name=\"CredentialsOptional\" xml:space=\"preserve\">\n    <value>认证 (可选)</value>\n  </data>\n  <data name=\"Details\" xml:space=\"preserve\">\n    <value>详细设置</value>\n  </data>\n  <data name=\"Address\" xml:space=\"preserve\">\n    <value>地址</value>\n  </data>\n  <data name=\"saveButton_Content\" xml:space=\"preserve\">\n    <value>保存</value>\n  </data>\n  <data name=\"cancelButton_Content\" xml:space=\"preserve\">\n    <value>取消</value>\n  </data>\n  <data name=\"Username\" xml:space=\"preserve\">\n    <value>用户名</value>\n  </data>\n  <data name=\"Password\" xml:space=\"preserve\">\n    <value>密码</value>\n  </data>\n  <data name=\"Port\" xml:space=\"preserve\">\n    <value>端口</value>\n  </data>\n  <data name=\"Timeout\" xml:space=\"preserve\">\n    <value>超时 (秒)</value>\n  </data>\n  <data name=\"okButton_Content\" xml:space=\"preserve\">\n    <value>确定</value>\n  </data>\n  <data name=\"registerAllButton_Content\" xml:space=\"preserve\">\n    <value>全部注册</value>\n  </data>\n  <data name=\"ToggleSystemProxy\" xml:space=\"preserve\">\n    <value>切换系统代理</value>\n  </data>\n  <data name=\"ToggleProxyMode\" xml:space=\"preserve\">\n    <value>切换代理模式</value>\n  </data>\n  <data name=\"AllowClientsFromLAN\" xml:space=\"preserve\">\n    <value>允许内网客户端连接</value>\n  </data>\n  <data name=\"OpenLogsWindow\" xml:space=\"preserve\">\n    <value>打开日志窗口</value>\n  </data>\n  <data name=\"SwitchToPreviousServer\" xml:space=\"preserve\">\n    <value>切换到上一个服务器</value>\n  </data>\n  <data name=\"SwitchToNextServer\" xml:space=\"preserve\">\n    <value>切换到下一个服务器</value>\n  </data>\n  <data name=\"RegisterHotkeysAtStartup\" xml:space=\"preserve\">\n    <value>启动时注册快捷键</value>\n  </data>\n  <data name=\"updateButton_Content\" xml:space=\"preserve\">\n    <value>更新</value>\n  </data>\n  <data name=\"updateAllButton_Content\" xml:space=\"preserve\">\n    <value>全部更新</value>\n  </data>\n  <data name=\"copyLinkButton_Content\" xml:space=\"preserve\">\n    <value>复制链接</value>\n  </data>\n  <data name=\"removeButton_Content\" xml:space=\"preserve\">\n    <value>移除</value>\n  </data>\n  <data name=\"addButton_Content\" xml:space=\"preserve\">\n    <value>添加</value>\n  </data>\n  <data name=\"skipVersionButton_Content\" xml:space=\"preserve\">\n    <value>跳过版本</value>\n  </data>\n  <data name=\"notNowButton_Content\" xml:space=\"preserve\">\n    <value>暂不更新</value>\n  </data>\n  <data name=\"updatePromptTitle\" xml:space=\"preserve\">\n    <value>发现可用更新</value>\n  </data>\n  <data name=\"updatePromptBody\" xml:space=\"preserve\">\n    <value>请仔细阅读发布信息，然后决定是否更新。</value>\n  </data>\n  <data name=\"Copy\" xml:space=\"preserve\">\n    <value>复制</value>\n  </data>\n  <data name=\"ForwardProxy\" xml:space=\"preserve\">\n    <value>前置代理</value>\n  </data>\n  <data name=\"OnlineConfigDelivery\" xml:space=\"preserve\">\n    <value>在线配置下发</value>\n  </data>\n  <data name=\"Hotkeys\" xml:space=\"preserve\">\n    <value>热键</value>\n  </data>\n  <data name=\"ServerSharing\" xml:space=\"preserve\">\n    <value>服务器分享</value>\n  </data>\n  <data name=\"VersionUpdate\" xml:space=\"preserve\">\n    <value>版本更新</value>\n  </data>\n  <data name=\"sip008UpdateSuccess\" xml:space=\"preserve\">\n    <value>成功更新选定来源！</value>\n  </data>\n  <data name=\"sip008UpdateFailure\" xml:space=\"preserve\">\n    <value>更新失败，请查看日志获取更多信息。</value>\n  </data>\n  <data name=\"sip008UpdateAllSuccess\" xml:space=\"preserve\">\n    <value>成功更新所有来源！</value>\n  </data>\n  <data name=\"sip008UpdateAllFailure\" xml:space=\"preserve\">\n    <value>下列来源更新失败:\\n\\n</value>\n  </data>\n</root>"
  },
  {
    "path": "shadowsocks-csharp/Localization/Strings.zh-Hant.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Password\" xml:space=\"preserve\">\n    <value>密碼</value>\n  </data>\n  <data name=\"Port\" xml:space=\"preserve\">\n    <value>Port</value>\n  </data>\n  <data name=\"Type\" xml:space=\"preserve\">\n    <value>類型</value>\n  </data>\n  <data name=\"Address\" xml:space=\"preserve\">\n    <value>位址</value>\n  </data>\n  <data name=\"Timeout\" xml:space=\"preserve\">\n    <value>逾時 (秒)</value>\n  </data>\n  <data name=\"cancelButton_Content\" xml:space=\"preserve\">\n    <value>取消</value>\n  </data>\n  <data name=\"okButton_Content\" xml:space=\"preserve\">\n    <value>確定</value>\n  </data>\n  <data name=\"ToggleSystemProxy\" xml:space=\"preserve\">\n    <value>切換系統 Proxy 狀態</value>\n  </data>\n  <data name=\"ToggleProxyMode\" xml:space=\"preserve\">\n    <value>切換系統 Proxy 模式</value>\n  </data>\n  <data name=\"AllowClientsFromLAN\" xml:space=\"preserve\">\n    <value>切換區域網路共用</value>\n  </data>\n  <data name=\"OpenLogsWindow\" xml:space=\"preserve\">\n    <value>顯示記錄檔</value>\n  </data>\n  <data name=\"SwitchToPreviousServer\" xml:space=\"preserve\">\n    <value>切換上一個伺服器</value>\n  </data>\n  <data name=\"SwitchToNextServer\" xml:space=\"preserve\">\n    <value>切換下一個伺服器</value>\n  </data>\n  <data name=\"RegisterHotkeysAtStartup\" xml:space=\"preserve\">\n    <value>註冊所有快速鍵</value>\n  </data>\n  <data name=\"registerAllButton_Content\" xml:space=\"preserve\">\n    <value>啟動時註冊快速鍵</value>\n  </data>\n  <data name=\"updateButton_Content\" xml:space=\"preserve\">\n    <value>更新</value>\n  </data>\n  <data name=\"updateAllButton_Content\" xml:space=\"preserve\">\n    <value>全部更新</value>\n  </data>\n  <data name=\"addButton_Content\" xml:space=\"preserve\">\n    <value>新增</value>\n  </data>\n  <data name=\"skipVersionButton_Content\" xml:space=\"preserve\">\n    <value>跳過版本</value>\n  </data>\n  <data name=\"notNowButton_Content\" xml:space=\"preserve\">\n    <value>暫不更新</value>\n  </data>\n  <data name=\"updatePromptTitle\" xml:space=\"preserve\">\n    <value>發現可用更新</value>\n  </data>\n  <data name=\"copyLinkButton_Content\" xml:space=\"preserve\">\n    <value>複製鏈接</value>\n  </data>\n  <data name=\"Copy\" xml:space=\"preserve\">\n    <value>複製</value>\n  </data>\n</root>"
  },
  {
    "path": "shadowsocks-csharp/Model/Configuration.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Net;\r\nusing System.Windows;\r\nusing Newtonsoft.Json;\r\nusing NLog;\r\nusing Shadowsocks.Controller;\r\n\r\nnamespace Shadowsocks.Model\r\n{\r\n    [Serializable]\r\n    public class Configuration\r\n    {\r\n        [JsonIgnore]\r\n        private static readonly Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        public string version;\r\n\r\n        public List<Server> configs;\r\n\r\n        public List<string> onlineConfigSource;\r\n\r\n        // when strategy is set, index is ignored\r\n        public string strategy;\r\n        public int index;\r\n        public bool global;\r\n        public bool enabled;\r\n        public bool shareOverLan;\r\n        public bool firstRun;\r\n        public int localPort;\r\n        public bool portableMode;\r\n        public bool showPluginOutput;\r\n        public string pacUrl;\r\n\r\n        public bool useOnlinePac;\r\n        public bool secureLocalPac; // enable secret for PAC server\r\n        public bool regeneratePacOnUpdate; // regenerate pac.txt on version update\r\n        public bool autoCheckUpdate;\r\n        public bool checkPreRelease;\r\n        public string skippedUpdateVersion; // skip the update with this version number\r\n        public bool isVerboseLogging;\r\n\r\n        // hidden options\r\n        public bool isIPv6Enabled; // for experimental ipv6 support\r\n        public bool generateLegacyUrl; // for pre-sip002 url compatibility\r\n        public string geositeUrl; // for custom geosite source (and rule group)\r\n        public string geositeSha256sumUrl; // optional custom sha256sum url, leave empty to disable checksum verification for your custom geosite source\r\n        public List<string> geositeDirectGroups;  // groups of domains that we connect without the proxy\r\n        public List<string> geositeProxiedGroups; // groups of domains that we connect via the proxy\r\n        public bool geositePreferDirect; // a.k.a blacklist mode\r\n        public string userAgent;\r\n\r\n        //public NLogConfig.LogLevel logLevel;\r\n        public LogViewerConfig logViewer;\r\n        public ForwardProxyConfig proxy;\r\n        public HotkeyConfig hotkey;\r\n\r\n        [JsonIgnore]\r\n        public bool firstRunOnNewVersion;\r\n\r\n        public Configuration()\r\n        {\r\n            version = UpdateChecker.Version;\r\n            strategy = \"\";\r\n            index = 0;\r\n            global = false;\r\n            enabled = false;\r\n            shareOverLan = false;\r\n            firstRun = true;\r\n            localPort = 1080;\r\n            portableMode = true;\r\n            showPluginOutput = false;\r\n            pacUrl = \"\";\r\n            useOnlinePac = false;\r\n            secureLocalPac = true;\r\n            regeneratePacOnUpdate = true;\r\n            autoCheckUpdate = false;\r\n            checkPreRelease = false;\r\n            skippedUpdateVersion = \"\";\r\n            isVerboseLogging = false;\r\n\r\n            // hidden options\r\n            isIPv6Enabled = false;\r\n            generateLegacyUrl = false;\r\n            geositeUrl = \"\";\r\n            geositeSha256sumUrl = \"\";\r\n            geositeDirectGroups = new List<string>()\r\n            {\r\n                \"private\",\r\n                \"cn\",\r\n                \"geolocation-!cn@cn\",\r\n            };\r\n            geositeProxiedGroups = new List<string>()\r\n            {\r\n                \"geolocation-!cn\",\r\n            };\r\n            geositePreferDirect = false;\r\n            userAgent = \"ShadowsocksWindows/$version\";\r\n\r\n            logViewer = new LogViewerConfig();\r\n            proxy = new ForwardProxyConfig();\r\n            hotkey = new HotkeyConfig();\r\n\r\n            firstRunOnNewVersion = false;\r\n\r\n            configs = new List<Server>();\r\n            onlineConfigSource = new List<string>();\r\n        }\r\n\r\n        [JsonIgnore]\r\n        public string userAgentString; // $version substituted with numeral version in it\r\n\r\n        [JsonIgnore]\r\n        NLogConfig nLogConfig;\r\n\r\n        private static readonly string CONFIG_FILE = \"gui-config.json\";\r\n#if DEBUG\r\n        private static readonly NLogConfig.LogLevel verboseLogLevel = NLogConfig.LogLevel.Trace;\r\n#else\r\n        private static readonly NLogConfig.LogLevel verboseLogLevel =  NLogConfig.LogLevel.Debug;\r\n#endif\r\n\r\n        [JsonIgnore]\r\n        public string LocalHost => isIPv6Enabled ? \"[::1]\" : \"127.0.0.1\";\r\n\r\n        public Server GetCurrentServer()\r\n        {\r\n            if (index >= 0 && index < configs.Count)\r\n                return configs[index];\r\n            else\r\n                return GetDefaultServer();\r\n        }\r\n\r\n        public WebProxy WebProxy => enabled\r\n            ? new WebProxy(\r\n                    isIPv6Enabled\r\n                    ? $\"[{IPAddress.IPv6Loopback}]\"\r\n                    : IPAddress.Loopback.ToString(),\r\n                    localPort)\r\n            : null;\r\n\r\n        /// <summary>\r\n        /// Used by multiple forms to validate a server.\r\n        /// Communication is done by throwing exceptions.\r\n        /// </summary>\r\n        /// <param name=\"server\"></param>\r\n        public static void CheckServer(Server server)\r\n        {\r\n            CheckServer(server.server);\r\n            CheckPort(server.server_port);\r\n            CheckPassword(server.password);\r\n            CheckTimeout(server.timeout, Server.MaxServerTimeoutSec);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Loads the configuration from file.\r\n        /// </summary>\r\n        /// <returns>An Configuration object.</returns>\r\n        public static Configuration Load()\r\n        {\r\n            Configuration config;\r\n            if (File.Exists(CONFIG_FILE))\r\n            {\r\n                try\r\n                {\r\n                    string configContent = File.ReadAllText(CONFIG_FILE);\r\n                    config = JsonConvert.DeserializeObject<Configuration>(configContent, new JsonSerializerSettings()\r\n                    {\r\n                        ObjectCreationHandling = ObjectCreationHandling.Replace\r\n                    });\r\n                    return config;\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    if (!(e is FileNotFoundException))\r\n                        logger.LogUsefulException(e);\r\n                }\r\n            }\r\n            config = new Configuration();\r\n            return config;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Process the loaded configurations and set up things.\r\n        /// </summary>\r\n        /// <param name=\"config\">A reference of Configuration object.</param>\r\n        public static void Process(ref Configuration config)\r\n        {\r\n            // Verify if the configured geosite groups exist.\r\n            // Reset to default if ANY one of the configured group doesn't exist.\r\n            if (!ValidateGeositeGroupList(config.geositeDirectGroups))\r\n                ResetGeositeDirectGroup(ref config.geositeDirectGroups);\r\n            if (!ValidateGeositeGroupList(config.geositeProxiedGroups))\r\n                ResetGeositeProxiedGroup(ref config.geositeProxiedGroups);\r\n\r\n            // Mark the first run of a new version.\r\n            var appVersion = new Version(UpdateChecker.Version);\r\n            var configVersion = new Version(config.version);\r\n            if (appVersion.CompareTo(configVersion) > 0)\r\n            {\r\n                config.firstRunOnNewVersion = true;\r\n            }\r\n            // Add an empty server configuration\r\n            if (config.configs.Count == 0)\r\n                config.configs.Add(GetDefaultServer());\r\n            // Selected server\r\n            if (config.index == -1 && string.IsNullOrEmpty(config.strategy))\r\n                config.index = 0;\r\n            if (config.index >= config.configs.Count)\r\n                config.index = config.configs.Count - 1;\r\n            // Check OS IPv6 support\r\n            if (!System.Net.Sockets.Socket.OSSupportsIPv6)\r\n                config.isIPv6Enabled = false;\r\n            config.proxy.CheckConfig();\r\n            // Replace $version with the version number.\r\n            config.userAgentString = config.userAgent.Replace(\"$version\", config.version);\r\n\r\n            // NLog log level\r\n            try\r\n            {\r\n                config.nLogConfig = NLogConfig.LoadXML();\r\n                switch (config.nLogConfig.GetLogLevel())\r\n                {\r\n                    case NLogConfig.LogLevel.Fatal:\r\n                    case NLogConfig.LogLevel.Error:\r\n                    case NLogConfig.LogLevel.Warn:\r\n                    case NLogConfig.LogLevel.Info:\r\n                        config.isVerboseLogging = false;\r\n                        break;\r\n                    case NLogConfig.LogLevel.Debug:\r\n                    case NLogConfig.LogLevel.Trace:\r\n                        config.isVerboseLogging = true;\r\n                        break;\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                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}\");\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Saves the Configuration object to file.\r\n        /// </summary>\r\n        /// <param name=\"config\">A Configuration object.</param>\r\n        public static void Save(Configuration config)\r\n        {\r\n            config.configs = SortByOnlineConfig(config.configs);\r\n\r\n            FileStream configFileStream = null;\r\n            StreamWriter configStreamWriter = null;\r\n            try\r\n            {\r\n                configFileStream = File.Open(CONFIG_FILE, FileMode.Create);\r\n                configStreamWriter = new StreamWriter(configFileStream);\r\n                var jsonString = JsonConvert.SerializeObject(config, Formatting.Indented);\r\n                configStreamWriter.Write(jsonString);\r\n                configStreamWriter.Flush();\r\n                // NLog\r\n                config.nLogConfig.SetLogLevel(config.isVerboseLogging ? verboseLogLevel : NLogConfig.LogLevel.Info);\r\n                NLogConfig.SaveXML(config.nLogConfig);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n            finally\r\n            {\r\n                if (configStreamWriter != null)\r\n                    configStreamWriter.Dispose();\r\n                if (configFileStream != null)\r\n                    configFileStream.Dispose();\r\n            }\r\n        }\r\n\r\n        public static List<Server> SortByOnlineConfig(IEnumerable<Server> servers)\r\n        {\r\n            var groups = servers.GroupBy(s => s.group);\r\n            List<Server> ret = new List<Server>();\r\n            ret.AddRange(groups.Where(g => string.IsNullOrEmpty(g.Key)).SelectMany(g => g));\r\n            ret.AddRange(groups.Where(g => !string.IsNullOrEmpty(g.Key)).SelectMany(g => g));\r\n            return ret;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Validates if the groups in the list are all valid.\r\n        /// </summary>\r\n        /// <param name=\"groups\">The list of groups to validate.</param>\r\n        /// <returns>\r\n        /// True if all groups are valid.\r\n        /// False if any one of them is invalid.\r\n        /// </returns>\r\n        public static bool ValidateGeositeGroupList(List<string> groups)\r\n        {\r\n            foreach (var geositeGroup in groups)\r\n                if (!GeositeUpdater.CheckGeositeGroup(geositeGroup)) // found invalid group\r\n                {\r\n#if DEBUG\r\n                    logger.Debug($\"Available groups:\");\r\n                    foreach (var group in GeositeUpdater.Geosites.Keys)\r\n                        logger.Debug($\"{group}\");\r\n#endif\r\n                    logger.Warn($\"The Geosite group {geositeGroup} doesn't exist. Resetting to default groups.\");\r\n                    return false;\r\n                }\r\n            return true;\r\n        }\r\n\r\n        public static void ResetGeositeDirectGroup(ref List<string> geositeDirectGroups)\r\n        {\r\n            geositeDirectGroups.Clear();\r\n            geositeDirectGroups.Add(\"private\");\r\n            geositeDirectGroups.Add(\"cn\");\r\n            geositeDirectGroups.Add(\"geolocation-!cn@cn\");\r\n        }\r\n\r\n        public static void ResetGeositeProxiedGroup(ref List<string> geositeProxiedGroups)\r\n        {\r\n            geositeProxiedGroups.Clear();\r\n            geositeProxiedGroups.Add(\"geolocation-!cn\");\r\n        }\r\n\r\n        public static void ResetUserAgent(Configuration config)\r\n        {\r\n            config.userAgent = \"ShadowsocksWindows/$version\";\r\n            config.userAgentString = config.userAgent.Replace(\"$version\", config.version);\r\n        }\r\n\r\n        public static Server AddDefaultServerOrServer(Configuration config, Server server = null, int? index = null)\r\n        {\r\n            if (config?.configs != null)\r\n            {\r\n                server = (server ?? GetDefaultServer());\r\n\r\n                config.configs.Insert(index.GetValueOrDefault(config.configs.Count), server);\r\n\r\n                //if (index.HasValue)\r\n                //    config.configs.Insert(index.Value, server);\r\n                //else\r\n                //    config.configs.Add(server);\r\n            }\r\n            return server;\r\n        }\r\n\r\n        public static Server GetDefaultServer()\r\n        {\r\n            return new Server();\r\n        }\r\n\r\n        public static void CheckPort(int port)\r\n        {\r\n            if (port <= 0 || port > 65535)\r\n                throw new ArgumentException(I18N.GetString(\"Port out of range\"));\r\n        }\r\n\r\n        public static void CheckLocalPort(int port)\r\n        {\r\n            CheckPort(port);\r\n            if (port == 8123)\r\n                throw new ArgumentException(I18N.GetString(\"Port can't be 8123\"));\r\n        }\r\n\r\n        private static void CheckPassword(string password)\r\n        {\r\n            if (string.IsNullOrEmpty(password))\r\n                throw new ArgumentException(I18N.GetString(\"Password can not be blank\"));\r\n        }\r\n\r\n        public static void CheckServer(string server)\r\n        {\r\n            if (string.IsNullOrEmpty(server))\r\n                throw new ArgumentException(I18N.GetString(\"Server IP can not be blank\"));\r\n        }\r\n\r\n        public static void CheckTimeout(int timeout, int maxTimeout)\r\n        {\r\n            if (timeout <= 0 || timeout > maxTimeout)\r\n                throw new ArgumentException(\r\n                    I18N.GetString(\"Timeout is invalid, it should not exceed {0}\", maxTimeout));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Model/ForwardProxyConfig.cs",
    "content": "﻿using System;\n\nnamespace Shadowsocks.Model\n{\n    [Serializable]\n    public class ForwardProxyConfig\n    {\n        public const int PROXY_SOCKS5 = 0;\n        public const int PROXY_HTTP = 1;\n\n        public const int MaxProxyTimeoutSec = 10;\n        private const int DefaultProxyTimeoutSec = 3;\n\n        public bool useProxy;\n        public int proxyType;\n        public string proxyServer;\n        public int proxyPort;\n        public int proxyTimeout;\n        public bool useAuth;\n        public string authUser;\n        public string authPwd;\n\n        public ForwardProxyConfig()\n        {\n            useProxy = false;\n            proxyType = PROXY_SOCKS5;\n            proxyServer = \"\";\n            proxyPort = 0;\n            proxyTimeout = DefaultProxyTimeoutSec;\n            useAuth = false;\n            authUser = \"\";\n            authPwd = \"\";\n        }\n\n        public void CheckConfig()\n        {\n            if (proxyType < PROXY_SOCKS5 || proxyType > PROXY_HTTP)\n            {\n                proxyType = PROXY_SOCKS5;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Model/Geosite/Geosite.cs",
    "content": "// <auto-generated>\n//     Generated by the protocol buffer compiler.  DO NOT EDIT!\n//     source: geosite.proto\n// </auto-generated>\n#pragma warning disable 1591, 0612, 3021\n#region Designer generated code\n\nusing pb = global::Google.Protobuf;\nusing pbc = global::Google.Protobuf.Collections;\nusing pbr = global::Google.Protobuf.Reflection;\nusing scg = global::System.Collections.Generic;\n/// <summary>Holder for reflection information generated from geosite.proto</summary>\npublic static partial class GeositeReflection {\n\n  #region Descriptor\n  /// <summary>File descriptor for geosite.proto</summary>\n  public static pbr::FileDescriptor Descriptor {\n    get { return descriptor; }\n  }\n  private static pbr::FileDescriptor descriptor;\n\n  static GeositeReflection() {\n    byte[] descriptorData = global::System.Convert.FromBase64String(\n        string.Concat(\n          \"Cg1nZW9zaXRlLnByb3RvIvMBCgxEb21haW5PYmplY3QSIAoEdHlwZRgBIAEo\",\n          \"DjISLkRvbWFpbk9iamVjdC5UeXBlEg0KBXZhbHVlGAIgASgJEioKCWF0dHJp\",\n          \"YnV0ZRgDIAMoCzIXLkRvbWFpbk9iamVjdC5BdHRyaWJ1dGUaUgoJQXR0cmli\",\n          \"dXRlEgsKA2tleRgBIAEoCRIUCgpib29sX3ZhbHVlGAIgASgISAASEwoJaW50\",\n          \"X3ZhbHVlGAMgASgDSABCDQoLdHlwZWRfdmFsdWUiMgoEVHlwZRIJCgVQbGFp\",\n          \"bhAAEgkKBVJlZ2V4EAESCgoGRG9tYWluEAISCAoERnVsbBADIj0KB0dlb3Np\",\n          \"dGUSEgoKZ3JvdXBfbmFtZRgBIAEoCRIeCgdkb21haW5zGAIgAygLMg0uRG9t\",\n          \"YWluT2JqZWN0IigKC0dlb3NpdGVMaXN0EhkKB2VudHJpZXMYASADKAsyCC5H\",\n          \"ZW9zaXRlYgZwcm90bzM=\"));\n    descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,\n        new pbr::FileDescriptor[] { },\n        new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {\n          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)}),\n          new pbr::GeneratedClrTypeInfo(typeof(global::Geosite), global::Geosite.Parser, new[]{ \"GroupName\", \"Domains\" }, null, null, null, null),\n          new pbr::GeneratedClrTypeInfo(typeof(global::GeositeList), global::GeositeList.Parser, new[]{ \"Entries\" }, null, null, null, null)\n        }));\n  }\n  #endregion\n\n}\n#region Messages\n/// <summary>\n/// DomainObject for routing decision.\n/// </summary>\npublic sealed partial class DomainObject : pb::IMessage<DomainObject> {\n  private static readonly pb::MessageParser<DomainObject> _parser = new pb::MessageParser<DomainObject>(() => new DomainObject());\n  private pb::UnknownFieldSet _unknownFields;\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public static pb::MessageParser<DomainObject> Parser { get { return _parser; } }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public static pbr::MessageDescriptor Descriptor {\n    get { return global::GeositeReflection.Descriptor.MessageTypes[0]; }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  pbr::MessageDescriptor pb::IMessage.Descriptor {\n    get { return Descriptor; }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public DomainObject() {\n    OnConstruction();\n  }\n\n  partial void OnConstruction();\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public DomainObject(DomainObject other) : this() {\n    type_ = other.type_;\n    value_ = other.value_;\n    attribute_ = other.attribute_.Clone();\n    _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public DomainObject Clone() {\n    return new DomainObject(this);\n  }\n\n  /// <summary>Field number for the \"type\" field.</summary>\n  public const int TypeFieldNumber = 1;\n  private global::DomainObject.Types.Type type_ = global::DomainObject.Types.Type.Plain;\n  /// <summary>\n  /// DomainObject matching type.\n  /// </summary>\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public global::DomainObject.Types.Type Type {\n    get { return type_; }\n    set {\n      type_ = value;\n    }\n  }\n\n  /// <summary>Field number for the \"value\" field.</summary>\n  public const int ValueFieldNumber = 2;\n  private string value_ = \"\";\n  /// <summary>\n  /// DomainObject value.\n  /// </summary>\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public string Value {\n    get { return value_; }\n    set {\n      value_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n    }\n  }\n\n  /// <summary>Field number for the \"attribute\" field.</summary>\n  public const int AttributeFieldNumber = 3;\n  private static readonly pb::FieldCodec<global::DomainObject.Types.Attribute> _repeated_attribute_codec\n      = pb::FieldCodec.ForMessage(26, global::DomainObject.Types.Attribute.Parser);\n  private readonly pbc::RepeatedField<global::DomainObject.Types.Attribute> attribute_ = new pbc::RepeatedField<global::DomainObject.Types.Attribute>();\n  /// <summary>\n  /// Attributes of this domain. May be used for filtering.\n  /// </summary>\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public pbc::RepeatedField<global::DomainObject.Types.Attribute> Attribute {\n    get { return attribute_; }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public override bool Equals(object other) {\n    return Equals(other as DomainObject);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public bool Equals(DomainObject other) {\n    if (ReferenceEquals(other, null)) {\n      return false;\n    }\n    if (ReferenceEquals(other, this)) {\n      return true;\n    }\n    if (Type != other.Type) return false;\n    if (Value != other.Value) return false;\n    if(!attribute_.Equals(other.attribute_)) return false;\n    return Equals(_unknownFields, other._unknownFields);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public override int GetHashCode() {\n    int hash = 1;\n    if (Type != global::DomainObject.Types.Type.Plain) hash ^= Type.GetHashCode();\n    if (Value.Length != 0) hash ^= Value.GetHashCode();\n    hash ^= attribute_.GetHashCode();\n    if (_unknownFields != null) {\n      hash ^= _unknownFields.GetHashCode();\n    }\n    return hash;\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public override string ToString() {\n    return pb::JsonFormatter.ToDiagnosticString(this);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public void WriteTo(pb::CodedOutputStream output) {\n    if (Type != global::DomainObject.Types.Type.Plain) {\n      output.WriteRawTag(8);\n      output.WriteEnum((int) Type);\n    }\n    if (Value.Length != 0) {\n      output.WriteRawTag(18);\n      output.WriteString(Value);\n    }\n    attribute_.WriteTo(output, _repeated_attribute_codec);\n    if (_unknownFields != null) {\n      _unknownFields.WriteTo(output);\n    }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public int CalculateSize() {\n    int size = 0;\n    if (Type != global::DomainObject.Types.Type.Plain) {\n      size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);\n    }\n    if (Value.Length != 0) {\n      size += 1 + pb::CodedOutputStream.ComputeStringSize(Value);\n    }\n    size += attribute_.CalculateSize(_repeated_attribute_codec);\n    if (_unknownFields != null) {\n      size += _unknownFields.CalculateSize();\n    }\n    return size;\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public void MergeFrom(DomainObject other) {\n    if (other == null) {\n      return;\n    }\n    if (other.Type != global::DomainObject.Types.Type.Plain) {\n      Type = other.Type;\n    }\n    if (other.Value.Length != 0) {\n      Value = other.Value;\n    }\n    attribute_.Add(other.attribute_);\n    _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public void MergeFrom(pb::CodedInputStream input) {\n    uint tag;\n    while ((tag = input.ReadTag()) != 0) {\n      switch(tag) {\n        default:\n          _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);\n          break;\n        case 8: {\n          Type = (global::DomainObject.Types.Type) input.ReadEnum();\n          break;\n        }\n        case 18: {\n          Value = input.ReadString();\n          break;\n        }\n        case 26: {\n          attribute_.AddEntriesFrom(input, _repeated_attribute_codec);\n          break;\n        }\n      }\n    }\n  }\n\n  #region Nested types\n  /// <summary>Container for nested types declared in the DomainObject message type.</summary>\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public static partial class Types {\n    /// <summary>\n    /// Type of domain value.\n    /// </summary>\n    public enum Type {\n      /// <summary>\n      /// The value is used as is.\n      /// </summary>\n      [pbr::OriginalName(\"Plain\")] Plain = 0,\n      /// <summary>\n      /// The value is used as a regular expression.\n      /// </summary>\n      [pbr::OriginalName(\"Regex\")] Regex = 1,\n      /// <summary>\n      /// The value is a root domain.\n      /// </summary>\n      [pbr::OriginalName(\"Domain\")] Domain = 2,\n      /// <summary>\n      /// The value is a domain.\n      /// </summary>\n      [pbr::OriginalName(\"Full\")] Full = 3,\n    }\n\n    public sealed partial class Attribute : pb::IMessage<Attribute> {\n      private static readonly pb::MessageParser<Attribute> _parser = new pb::MessageParser<Attribute>(() => new Attribute());\n      private pb::UnknownFieldSet _unknownFields;\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public static pb::MessageParser<Attribute> Parser { get { return _parser; } }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public static pbr::MessageDescriptor Descriptor {\n        get { return global::DomainObject.Descriptor.NestedTypes[0]; }\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      pbr::MessageDescriptor pb::IMessage.Descriptor {\n        get { return Descriptor; }\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public Attribute() {\n        OnConstruction();\n      }\n\n      partial void OnConstruction();\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public Attribute(Attribute other) : this() {\n        key_ = other.key_;\n        switch (other.TypedValueCase) {\n          case TypedValueOneofCase.BoolValue:\n            BoolValue = other.BoolValue;\n            break;\n          case TypedValueOneofCase.IntValue:\n            IntValue = other.IntValue;\n            break;\n        }\n\n        _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public Attribute Clone() {\n        return new Attribute(this);\n      }\n\n      /// <summary>Field number for the \"key\" field.</summary>\n      public const int KeyFieldNumber = 1;\n      private string key_ = \"\";\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public string Key {\n        get { return key_; }\n        set {\n          key_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n        }\n      }\n\n      /// <summary>Field number for the \"bool_value\" field.</summary>\n      public const int BoolValueFieldNumber = 2;\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public bool BoolValue {\n        get { return typedValueCase_ == TypedValueOneofCase.BoolValue ? (bool) typedValue_ : false; }\n        set {\n          typedValue_ = value;\n          typedValueCase_ = TypedValueOneofCase.BoolValue;\n        }\n      }\n\n      /// <summary>Field number for the \"int_value\" field.</summary>\n      public const int IntValueFieldNumber = 3;\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public long IntValue {\n        get { return typedValueCase_ == TypedValueOneofCase.IntValue ? (long) typedValue_ : 0L; }\n        set {\n          typedValue_ = value;\n          typedValueCase_ = TypedValueOneofCase.IntValue;\n        }\n      }\n\n      private object typedValue_;\n      /// <summary>Enum of possible cases for the \"typed_value\" oneof.</summary>\n      public enum TypedValueOneofCase {\n        None = 0,\n        BoolValue = 2,\n        IntValue = 3,\n      }\n      private TypedValueOneofCase typedValueCase_ = TypedValueOneofCase.None;\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public TypedValueOneofCase TypedValueCase {\n        get { return typedValueCase_; }\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public void ClearTypedValue() {\n        typedValueCase_ = TypedValueOneofCase.None;\n        typedValue_ = null;\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public override bool Equals(object other) {\n        return Equals(other as Attribute);\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public bool Equals(Attribute other) {\n        if (ReferenceEquals(other, null)) {\n          return false;\n        }\n        if (ReferenceEquals(other, this)) {\n          return true;\n        }\n        if (Key != other.Key) return false;\n        if (BoolValue != other.BoolValue) return false;\n        if (IntValue != other.IntValue) return false;\n        if (TypedValueCase != other.TypedValueCase) return false;\n        return Equals(_unknownFields, other._unknownFields);\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public override int GetHashCode() {\n        int hash = 1;\n        if (Key.Length != 0) hash ^= Key.GetHashCode();\n        if (typedValueCase_ == TypedValueOneofCase.BoolValue) hash ^= BoolValue.GetHashCode();\n        if (typedValueCase_ == TypedValueOneofCase.IntValue) hash ^= IntValue.GetHashCode();\n        hash ^= (int) typedValueCase_;\n        if (_unknownFields != null) {\n          hash ^= _unknownFields.GetHashCode();\n        }\n        return hash;\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public override string ToString() {\n        return pb::JsonFormatter.ToDiagnosticString(this);\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public void WriteTo(pb::CodedOutputStream output) {\n        if (Key.Length != 0) {\n          output.WriteRawTag(10);\n          output.WriteString(Key);\n        }\n        if (typedValueCase_ == TypedValueOneofCase.BoolValue) {\n          output.WriteRawTag(16);\n          output.WriteBool(BoolValue);\n        }\n        if (typedValueCase_ == TypedValueOneofCase.IntValue) {\n          output.WriteRawTag(24);\n          output.WriteInt64(IntValue);\n        }\n        if (_unknownFields != null) {\n          _unknownFields.WriteTo(output);\n        }\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public int CalculateSize() {\n        int size = 0;\n        if (Key.Length != 0) {\n          size += 1 + pb::CodedOutputStream.ComputeStringSize(Key);\n        }\n        if (typedValueCase_ == TypedValueOneofCase.BoolValue) {\n          size += 1 + 1;\n        }\n        if (typedValueCase_ == TypedValueOneofCase.IntValue) {\n          size += 1 + pb::CodedOutputStream.ComputeInt64Size(IntValue);\n        }\n        if (_unknownFields != null) {\n          size += _unknownFields.CalculateSize();\n        }\n        return size;\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public void MergeFrom(Attribute other) {\n        if (other == null) {\n          return;\n        }\n        if (other.Key.Length != 0) {\n          Key = other.Key;\n        }\n        switch (other.TypedValueCase) {\n          case TypedValueOneofCase.BoolValue:\n            BoolValue = other.BoolValue;\n            break;\n          case TypedValueOneofCase.IntValue:\n            IntValue = other.IntValue;\n            break;\n        }\n\n        _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);\n      }\n\n      [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n      public void MergeFrom(pb::CodedInputStream input) {\n        uint tag;\n        while ((tag = input.ReadTag()) != 0) {\n          switch(tag) {\n            default:\n              _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);\n              break;\n            case 10: {\n              Key = input.ReadString();\n              break;\n            }\n            case 16: {\n              BoolValue = input.ReadBool();\n              break;\n            }\n            case 24: {\n              IntValue = input.ReadInt64();\n              break;\n            }\n          }\n        }\n      }\n\n    }\n\n  }\n  #endregion\n\n}\n\npublic sealed partial class Geosite : pb::IMessage<Geosite> {\n  private static readonly pb::MessageParser<Geosite> _parser = new pb::MessageParser<Geosite>(() => new Geosite());\n  private pb::UnknownFieldSet _unknownFields;\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public static pb::MessageParser<Geosite> Parser { get { return _parser; } }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public static pbr::MessageDescriptor Descriptor {\n    get { return global::GeositeReflection.Descriptor.MessageTypes[1]; }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  pbr::MessageDescriptor pb::IMessage.Descriptor {\n    get { return Descriptor; }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public Geosite() {\n    OnConstruction();\n  }\n\n  partial void OnConstruction();\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public Geosite(Geosite other) : this() {\n    groupName_ = other.groupName_;\n    domains_ = other.domains_.Clone();\n    _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public Geosite Clone() {\n    return new Geosite(this);\n  }\n\n  /// <summary>Field number for the \"group_name\" field.</summary>\n  public const int GroupNameFieldNumber = 1;\n  private string groupName_ = \"\";\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public string GroupName {\n    get { return groupName_; }\n    set {\n      groupName_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n    }\n  }\n\n  /// <summary>Field number for the \"domains\" field.</summary>\n  public const int DomainsFieldNumber = 2;\n  private static readonly pb::FieldCodec<global::DomainObject> _repeated_domains_codec\n      = pb::FieldCodec.ForMessage(18, global::DomainObject.Parser);\n  private readonly pbc::RepeatedField<global::DomainObject> domains_ = new pbc::RepeatedField<global::DomainObject>();\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public pbc::RepeatedField<global::DomainObject> Domains {\n    get { return domains_; }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public override bool Equals(object other) {\n    return Equals(other as Geosite);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public bool Equals(Geosite other) {\n    if (ReferenceEquals(other, null)) {\n      return false;\n    }\n    if (ReferenceEquals(other, this)) {\n      return true;\n    }\n    if (GroupName != other.GroupName) return false;\n    if(!domains_.Equals(other.domains_)) return false;\n    return Equals(_unknownFields, other._unknownFields);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public override int GetHashCode() {\n    int hash = 1;\n    if (GroupName.Length != 0) hash ^= GroupName.GetHashCode();\n    hash ^= domains_.GetHashCode();\n    if (_unknownFields != null) {\n      hash ^= _unknownFields.GetHashCode();\n    }\n    return hash;\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public override string ToString() {\n    return pb::JsonFormatter.ToDiagnosticString(this);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public void WriteTo(pb::CodedOutputStream output) {\n    if (GroupName.Length != 0) {\n      output.WriteRawTag(10);\n      output.WriteString(GroupName);\n    }\n    domains_.WriteTo(output, _repeated_domains_codec);\n    if (_unknownFields != null) {\n      _unknownFields.WriteTo(output);\n    }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public int CalculateSize() {\n    int size = 0;\n    if (GroupName.Length != 0) {\n      size += 1 + pb::CodedOutputStream.ComputeStringSize(GroupName);\n    }\n    size += domains_.CalculateSize(_repeated_domains_codec);\n    if (_unknownFields != null) {\n      size += _unknownFields.CalculateSize();\n    }\n    return size;\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public void MergeFrom(Geosite other) {\n    if (other == null) {\n      return;\n    }\n    if (other.GroupName.Length != 0) {\n      GroupName = other.GroupName;\n    }\n    domains_.Add(other.domains_);\n    _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public void MergeFrom(pb::CodedInputStream input) {\n    uint tag;\n    while ((tag = input.ReadTag()) != 0) {\n      switch(tag) {\n        default:\n          _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);\n          break;\n        case 10: {\n          GroupName = input.ReadString();\n          break;\n        }\n        case 18: {\n          domains_.AddEntriesFrom(input, _repeated_domains_codec);\n          break;\n        }\n      }\n    }\n  }\n\n}\n\npublic sealed partial class GeositeList : pb::IMessage<GeositeList> {\n  private static readonly pb::MessageParser<GeositeList> _parser = new pb::MessageParser<GeositeList>(() => new GeositeList());\n  private pb::UnknownFieldSet _unknownFields;\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public static pb::MessageParser<GeositeList> Parser { get { return _parser; } }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public static pbr::MessageDescriptor Descriptor {\n    get { return global::GeositeReflection.Descriptor.MessageTypes[2]; }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  pbr::MessageDescriptor pb::IMessage.Descriptor {\n    get { return Descriptor; }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public GeositeList() {\n    OnConstruction();\n  }\n\n  partial void OnConstruction();\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public GeositeList(GeositeList other) : this() {\n    entries_ = other.entries_.Clone();\n    _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public GeositeList Clone() {\n    return new GeositeList(this);\n  }\n\n  /// <summary>Field number for the \"entries\" field.</summary>\n  public const int EntriesFieldNumber = 1;\n  private static readonly pb::FieldCodec<global::Geosite> _repeated_entries_codec\n      = pb::FieldCodec.ForMessage(10, global::Geosite.Parser);\n  private readonly pbc::RepeatedField<global::Geosite> entries_ = new pbc::RepeatedField<global::Geosite>();\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public pbc::RepeatedField<global::Geosite> Entries {\n    get { return entries_; }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public override bool Equals(object other) {\n    return Equals(other as GeositeList);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public bool Equals(GeositeList other) {\n    if (ReferenceEquals(other, null)) {\n      return false;\n    }\n    if (ReferenceEquals(other, this)) {\n      return true;\n    }\n    if(!entries_.Equals(other.entries_)) return false;\n    return Equals(_unknownFields, other._unknownFields);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public override int GetHashCode() {\n    int hash = 1;\n    hash ^= entries_.GetHashCode();\n    if (_unknownFields != null) {\n      hash ^= _unknownFields.GetHashCode();\n    }\n    return hash;\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public override string ToString() {\n    return pb::JsonFormatter.ToDiagnosticString(this);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public void WriteTo(pb::CodedOutputStream output) {\n    entries_.WriteTo(output, _repeated_entries_codec);\n    if (_unknownFields != null) {\n      _unknownFields.WriteTo(output);\n    }\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public int CalculateSize() {\n    int size = 0;\n    size += entries_.CalculateSize(_repeated_entries_codec);\n    if (_unknownFields != null) {\n      size += _unknownFields.CalculateSize();\n    }\n    return size;\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public void MergeFrom(GeositeList other) {\n    if (other == null) {\n      return;\n    }\n    entries_.Add(other.entries_);\n    _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);\n  }\n\n  [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n  public void MergeFrom(pb::CodedInputStream input) {\n    uint tag;\n    while ((tag = input.ReadTag()) != 0) {\n      switch(tag) {\n        default:\n          _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);\n          break;\n        case 10: {\n          entries_.AddEntriesFrom(input, _repeated_entries_codec);\n          break;\n        }\n      }\n    }\n  }\n\n}\n\n#endregion\n\n\n#endregion Designer generated code\n"
  },
  {
    "path": "shadowsocks-csharp/Model/Geosite/geosite.proto",
    "content": "﻿syntax = \"proto3\";\n\n// DomainObject for routing decision.\nmessage DomainObject {\n  // Type of domain value.\n  enum Type {\n    // The value is used as is.\n    Plain = 0;\n    // The value is used as a regular expression.\n    Regex = 1;\n    // The value is a root domain.\n    Domain = 2;\n    // The value is a domain.\n    Full = 3;\n  }\n\n  // DomainObject matching type.\n  Type type = 1;\n\n  // DomainObject value.\n  string value = 2;\n\n  message Attribute {\n    string key = 1;\n\n    oneof typed_value {\n      bool bool_value = 2;\n      int64 int_value = 3;\n    }\n  }\n\n  // Attributes of this domain. May be used for filtering.\n  repeated Attribute attribute = 3;\n}\n\nmessage Geosite {\n  string group_name = 1;\n  repeated DomainObject domains = 2;\n}\n\nmessage GeositeList{\n  repeated Geosite entries = 1;\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Model/HotKeyConfig.cs",
    "content": "﻿using System;\r\n\r\nnamespace Shadowsocks.Model\r\n{\r\n    /*\r\n     * Format:\r\n     *  <modifiers-combination>+<key>\r\n     *\r\n     */\r\n\r\n    [Serializable]\r\n    public class HotkeyConfig\r\n    {\r\n        public string SwitchSystemProxy;\r\n        public string SwitchSystemProxyMode;\r\n        public string SwitchAllowLan;\r\n        public string ShowLogs;\r\n        public string ServerMoveUp;\r\n        public string ServerMoveDown;\r\n        public bool RegHotkeysAtStartup;\r\n\r\n        public HotkeyConfig()\r\n        {\r\n            SwitchSystemProxy = \"\";\r\n            SwitchSystemProxyMode = \"\";\r\n            SwitchAllowLan = \"\";\r\n            ShowLogs = \"\";\r\n            ServerMoveUp = \"\";\r\n            ServerMoveDown = \"\";\r\n            RegHotkeysAtStartup = false;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Model/LogViewerConfig.cs",
    "content": "﻿using System;\r\nusing System.Drawing;\r\nusing System.Windows.Forms;\r\nusing Newtonsoft.Json;\r\n\r\nnamespace Shadowsocks.Model\r\n{\r\n    [Serializable]\r\n    public class LogViewerConfig\r\n    {\r\n        public bool topMost;\r\n        public bool wrapText;\r\n        public bool toolbarShown;\r\n\r\n        public Font Font { get; set; } = new Font(\"Consolas\", 8F);\r\n\r\n        public Color BackgroundColor { get; set; } = Color.Black;\r\n\r\n        public Color TextColor { get; set; } = Color.White;\r\n\r\n        public LogViewerConfig()\r\n        {\r\n            topMost = false;\r\n            wrapText = false;\r\n            toolbarShown = false;\r\n        }\r\n\r\n\r\n        #region Size\r\n\r\n        public void SaveSize()\r\n        {\r\n            Properties.Settings.Default.Save();\r\n        }\r\n\r\n        [JsonIgnore]\r\n        public int Width\r\n        {\r\n            get { return Properties.Settings.Default.LogViewerWidth; }\r\n            set { Properties.Settings.Default.LogViewerWidth = value; }\r\n        }\r\n\r\n        [JsonIgnore]\r\n        public int Height\r\n        {\r\n            get { return Properties.Settings.Default.LogViewerHeight; }\r\n            set { Properties.Settings.Default.LogViewerHeight = value; }\r\n        }\r\n        [JsonIgnore]\r\n        public int Top\r\n        {\r\n            get { return Properties.Settings.Default.LogViewerTop; }\r\n            set { Properties.Settings.Default.LogViewerTop = value; }\r\n        }\r\n        [JsonIgnore]\r\n        public int Left\r\n        {\r\n            get { return Properties.Settings.Default.LogViewerLeft; }\r\n            set { Properties.Settings.Default.LogViewerLeft = value; }\r\n        }\r\n        [JsonIgnore]\r\n        public bool Maximized\r\n        {\r\n            get { return Properties.Settings.Default.LogViewerMaximized; }\r\n            set { Properties.Settings.Default.LogViewerMaximized = value; }\r\n        }\r\n\r\n        [JsonIgnore]\r\n        // Use GetBestTop() and GetBestLeft() to ensure the log viwer form can be always display IN screen. \r\n        public int BestLeft\r\n        {\r\n            get\r\n            {\r\n                int width = Width;\r\n                width = (width >= 400) ? width : 400; // set up the minimum size\r\n                return Screen.PrimaryScreen.WorkingArea.Width - width;\r\n            }\r\n        }\r\n\r\n        [JsonIgnore]\r\n        public int BestTop\r\n        {\r\n            get\r\n            {\r\n                int height = Height;\r\n                height = (height >= 200) ? height : 200; // set up the minimum size\r\n                return Screen.PrimaryScreen.WorkingArea.Height - height;\r\n            }\r\n        }\r\n\r\n        #endregion\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Model/NlogConfig.cs",
    "content": "﻿using NLog;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Xml;\r\n\r\nnamespace Shadowsocks.Model\r\n{\r\n    public class NLogConfig\r\n    {\r\n        public enum LogLevel\r\n        {\r\n            Fatal,\r\n            Error,\r\n            Warn,\r\n            Info,\r\n            Debug,\r\n            Trace,\r\n        }\r\n\r\n        const string NLOG_CONFIG_FILE_NAME = \"NLog.config\";\r\n        const string TARGET_MIN_LEVEL_ATTRIBUTE = \"minlevel\";\r\n        const string LOGGER_FILE_NAME_ATTRIBUTE = \"fileName\";\r\n\r\n        XmlDocument doc = new XmlDocument();\r\n        XmlElement logFileNameElement;\r\n        XmlElement logLevelElement;\r\n\r\n        /// <summary>\r\n        /// Load the NLog config xml file content\r\n        /// </summary>\r\n        public static NLogConfig LoadXML()\r\n        {\r\n            NLogConfig config = new NLogConfig();\r\n            config.doc.Load(NLOG_CONFIG_FILE_NAME);\r\n            config.logLevelElement = (XmlElement)SelectSingleNode(config.doc, \"//nlog:logger[@name='*']\");\r\n            config.logFileNameElement = (XmlElement)SelectSingleNode(config.doc, \"//nlog:target[@name='file']\");\r\n            return config;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Save the content to NLog config xml file\r\n        /// </summary>\r\n        public static void SaveXML(NLogConfig nLogConfig)\r\n        {\r\n            nLogConfig.doc.Save(NLOG_CONFIG_FILE_NAME);\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Get the current minLogLevel from xml file\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        public LogLevel GetLogLevel()\r\n        {\r\n            LogLevel level = LogLevel.Warn;\r\n            string levelStr = logLevelElement.GetAttribute(TARGET_MIN_LEVEL_ATTRIBUTE);\r\n            Enum.TryParse(levelStr, out level);\r\n            return level;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the target fileName from xml file\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        public string GetLogFileName()\r\n        {\r\n            return logFileNameElement.GetAttribute(LOGGER_FILE_NAME_ATTRIBUTE);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Set the minLogLevel to xml file\r\n        /// </summary>\r\n        /// <param name=\"logLevel\"></param>\r\n        public void SetLogLevel(LogLevel logLevel)\r\n        {\r\n            logLevelElement.SetAttribute(TARGET_MIN_LEVEL_ATTRIBUTE, logLevel.ToString(\"G\"));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Set the target fileName to xml file\r\n        /// </summary>\r\n        /// <param name=\"fileName\"></param>\r\n        public void SetLogFileName(string fileName)\r\n        {\r\n            logFileNameElement.SetAttribute(LOGGER_FILE_NAME_ATTRIBUTE, fileName);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Select a single XML node/elemant\r\n        /// </summary>\r\n        /// <param name=\"doc\"></param>\r\n        /// <param name=\"xpath\"></param>\r\n        /// <returns></returns>\r\n        private static XmlNode SelectSingleNode(XmlDocument doc, string xpath)\r\n        {\r\n            XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);\r\n            manager.AddNamespace(\"nlog\", \"http://www.nlog-project.org/schemas/NLog.xsd\");\r\n            //return doc.SelectSingleNode(\"//nlog:logger[(@shadowsocks='managed') and (@name='*')]\", manager);\r\n            return doc.SelectSingleNode(xpath, manager);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Extract the pre-defined NLog configuration file is does not exist. Then reload the Nlog configuration.\r\n        /// </summary>\r\n        public static void TouchAndApplyNLogConfig()\r\n        {\r\n            try\r\n            {\r\n                if (File.Exists(NLOG_CONFIG_FILE_NAME))\r\n                    return; // NLog.config exists, and has already been loaded\r\n\r\n                File.WriteAllText(NLOG_CONFIG_FILE_NAME, Properties.Resources.NLog_config);\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                NLog.Common.InternalLogger.Error(ex, \"[shadowsocks] Failed to setup default NLog.config: {0}\", NLOG_CONFIG_FILE_NAME);\r\n                return;\r\n            }\r\n\r\n            LoadConfiguration();    // Load the new config-file\r\n        }\r\n\r\n        /// <summary>\r\n        /// NLog reload the config file and apply to current LogManager\r\n        /// </summary>\r\n        public static void LoadConfiguration()\r\n        {\r\n            LogManager.LoadConfiguration(NLOG_CONFIG_FILE_NAME);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Model/Server.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Collections.Specialized;\r\nusing System.Text;\r\nusing System.Web;\r\nusing Shadowsocks.Controller;\r\nusing System.Text.RegularExpressions;\r\nusing System.Linq;\r\nusing Newtonsoft.Json;\r\nusing System.ComponentModel;\r\n\r\nnamespace Shadowsocks.Model\r\n{\r\n    [Serializable]\r\n    public class Server\r\n    {\r\n        public const string DefaultMethod = \"chacha20-ietf-poly1305\";\r\n        public const int DefaultPort = 8388;\r\n\r\n        #region ParseLegacyURL\r\n        private static readonly Regex UrlFinder = new Regex(@\"ss://(?<base64>[A-Za-z0-9+-/=_]+)(?:#(?<tag>\\S+))?\", RegexOptions.IgnoreCase);\r\n        private static readonly Regex DetailsParser = new Regex(@\"^((?<method>.+?):(?<password>.*)@(?<hostname>.+?):(?<port>\\d+?))$\", RegexOptions.IgnoreCase);\r\n        #endregion ParseLegacyURL\r\n\r\n        private const int DefaultServerTimeoutSec = 5;\r\n        public const int MaxServerTimeoutSec = 20;\r\n\r\n        public string server;\r\n        public int server_port;\r\n        public string password;\r\n        public string method;\r\n        // optional fields\r\n        [DefaultValue(\"\")]\r\n        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]\r\n        public string plugin;\r\n        [DefaultValue(\"\")]\r\n        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]\r\n        public string plugin_opts;\r\n        [DefaultValue(\"\")]\r\n        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]\r\n        public string plugin_args;\r\n        [DefaultValue(\"\")]\r\n        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]\r\n        public string remarks;\r\n\r\n        [DefaultValue(\"\")]\r\n        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]\r\n        public string group;\r\n\r\n        public int timeout;\r\n\r\n        // Set to true when imported from a legacy ss:// URL.\r\n        public bool warnLegacyUrl;\r\n\r\n        public override int GetHashCode()\r\n        {\r\n            return server.GetHashCode() ^ server_port;\r\n        }\r\n\r\n        public override bool Equals(object obj) => obj is Server o2 && server == o2.server && server_port == o2.server_port;\r\n\r\n        public override string ToString()\r\n        {\r\n            if (string.IsNullOrEmpty(server))\r\n            {\r\n                return I18N.GetString(\"New server\");\r\n            }\r\n\r\n            string serverStr = $\"{FormalHostName}:{server_port}\";\r\n            return string.IsNullOrEmpty(remarks)\r\n                ? serverStr\r\n                : $\"{remarks} ({serverStr})\";\r\n        }\r\n\r\n        public string GetURL(bool legacyUrl = false)\r\n        {\r\n            string tag = string.Empty;\r\n            string url = string.Empty;\r\n\r\n            if (legacyUrl && string.IsNullOrWhiteSpace(plugin))\r\n            {\r\n                // For backwards compatiblity, if no plugin, use old url format\r\n                string parts = $\"{method}:{password}@{server}:{server_port}\";\r\n                string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));\r\n                url = base64;\r\n            }\r\n            else\r\n            {\r\n                // SIP002\r\n                string parts = $\"{method}:{password}\";\r\n                string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));\r\n                string websafeBase64 = base64.Replace('+', '-').Replace('/', '_').TrimEnd('=');\r\n\r\n                url = string.Format(\r\n                    \"{0}@{1}:{2}/\",\r\n                    websafeBase64,\r\n                    FormalHostName,\r\n                    server_port\r\n                    );\r\n\r\n                if (!string.IsNullOrWhiteSpace(plugin))\r\n                {\r\n\r\n                    string pluginPart = plugin;\r\n                    if (!string.IsNullOrWhiteSpace(plugin_opts))\r\n                    {\r\n                        pluginPart += \";\" + plugin_opts;\r\n                    }\r\n                    string pluginQuery = \"?plugin=\" + HttpUtility.UrlEncode(pluginPart, Encoding.UTF8);\r\n                    url += pluginQuery;\r\n                }\r\n            }\r\n\r\n            if (!string.IsNullOrEmpty(remarks))\r\n            {\r\n                tag = $\"#{HttpUtility.UrlEncode(remarks, Encoding.UTF8)}\";\r\n            }\r\n            return $\"ss://{url}{tag}\";\r\n        }\r\n\r\n        [JsonIgnore]\r\n        public string FormalHostName\r\n        {\r\n            get\r\n            {\r\n                // CheckHostName() won't do a real DNS lookup\r\n                switch (Uri.CheckHostName(server))\r\n                {\r\n                    case UriHostNameType.IPv6:  // Add square bracket when IPv6 (RFC3986)\r\n                        return $\"[{server}]\";\r\n                    default:    // IPv4 or domain name\r\n                        return server;\r\n                }\r\n            }\r\n        }\r\n\r\n        public Server()\r\n        {\r\n            server = \"\";\r\n            server_port = DefaultPort;\r\n            method = DefaultMethod;\r\n            plugin = \"\";\r\n            plugin_opts = \"\";\r\n            plugin_args = \"\";\r\n            password = \"\";\r\n            remarks = \"\";\r\n            timeout = DefaultServerTimeoutSec;\r\n        }\r\n\r\n        private static Server ParseLegacyURL(string ssURL)\r\n        {\r\n            var match = UrlFinder.Match(ssURL);\r\n            if (!match.Success)\r\n                return null;\r\n\r\n            Server server = new Server();\r\n            var base64 = match.Groups[\"base64\"].Value.TrimEnd('/');\r\n            var tag = match.Groups[\"tag\"].Value;\r\n            if (!string.IsNullOrEmpty(tag))\r\n            {\r\n                server.remarks = HttpUtility.UrlDecode(tag, Encoding.UTF8);\r\n            }\r\n            Match details = null;\r\n            try\r\n            {\r\n                details = DetailsParser.Match(Encoding.UTF8.GetString(Convert.FromBase64String(\r\n                base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '='))));\r\n            }\r\n            catch (FormatException)\r\n            {\r\n                return null;\r\n            }\r\n            if (!details.Success)\r\n                return null;\r\n            server.method = details.Groups[\"method\"].Value;\r\n            server.password = details.Groups[\"password\"].Value;\r\n            server.server = details.Groups[\"hostname\"].Value;\r\n            server.server_port = int.Parse(details.Groups[\"port\"].Value);\r\n            server.warnLegacyUrl = true;\r\n            return server;\r\n        }\r\n\r\n        public static Server ParseURL(string serverUrl)\r\n        {\r\n            string _serverUrl = serverUrl.Trim();\r\n            if (!_serverUrl.StartsWith(\"ss://\", StringComparison.InvariantCultureIgnoreCase))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            Server legacyServer = ParseLegacyURL(serverUrl);\r\n            if (legacyServer != null)   //legacy\r\n            {\r\n                return legacyServer;\r\n            }\r\n            else   //SIP002\r\n            {\r\n                Uri parsedUrl;\r\n                try\r\n                {\r\n                    parsedUrl = new Uri(serverUrl);\r\n                }\r\n                catch (UriFormatException)\r\n                {\r\n                    return null;\r\n                }\r\n                Server server = new Server\r\n                {\r\n                    remarks = HttpUtility.UrlDecode(parsedUrl.GetComponents(\r\n                        UriComponents.Fragment, UriFormat.Unescaped), Encoding.UTF8),\r\n                    server = parsedUrl.IdnHost,\r\n                    server_port = parsedUrl.Port,\r\n                };\r\n\r\n                // parse base64 UserInfo\r\n                string rawUserInfo = parsedUrl.GetComponents(UriComponents.UserInfo, UriFormat.Unescaped);\r\n                string base64 = rawUserInfo.Replace('-', '+').Replace('_', '/');    // Web-safe base64 to normal base64\r\n                string userInfo = \"\";\r\n                try\r\n                {\r\n                    userInfo = Encoding.UTF8.GetString(Convert.FromBase64String(\r\n                    base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=')));\r\n                }\r\n                catch (FormatException)\r\n                {\r\n                    return null;\r\n                }\r\n                string[] userInfoParts = userInfo.Split(new char[] { ':' }, 2);\r\n                if (userInfoParts.Length != 2)\r\n                {\r\n                    return null;\r\n                }\r\n                server.method = userInfoParts[0];\r\n                server.password = userInfoParts[1];\r\n\r\n                NameValueCollection queryParameters = HttpUtility.ParseQueryString(parsedUrl.Query);\r\n                string[] pluginParts = (queryParameters[\"plugin\"] ?? \"\").Split(new[] { ';' }, 2);\r\n                if (pluginParts.Length > 0)\r\n                {\r\n                    server.plugin = pluginParts[0] ?? \"\";\r\n                }\r\n\r\n                if (pluginParts.Length > 1)\r\n                {\r\n                    server.plugin_opts = pluginParts[1] ?? \"\";\r\n                }\r\n\r\n                return server;\r\n            }\r\n        }\r\n\r\n        public static List<Server> GetServers(string ssURL)\r\n        {\r\n            return ssURL\r\n                .Split('\\r', '\\n', ' ')\r\n                .Select(u => ParseURL(u))\r\n                .Where(s => s != null)\r\n                .ToList();\r\n        }\r\n\r\n        public string Identifier()\r\n        {\r\n            return server + ':' + server_port;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Model/SysproxyConfig.cs",
    "content": "﻿using System;\r\n\r\nnamespace Shadowsocks.Model\r\n{\r\n    /*\r\n     * Data come from WinINET\r\n     */\r\n\r\n    [Serializable]\r\n    public class SysproxyConfig\r\n    {\r\n        public bool UserSettingsRecorded;\r\n        public string Flags;\r\n        public string ProxyServer;\r\n        public string BypassList;\r\n        public string PacUrl;\r\n\r\n        public SysproxyConfig()\r\n        {\r\n            UserSettingsRecorded = false;\r\n            Flags = \"1\";\r\n            // Watchout, Nullable! See #2100\r\n            ProxyServer = \"\";\r\n            BypassList = \"\";\r\n            PacUrl = \"\";\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/Program.cs",
    "content": "using System;\r\nusing System.Diagnostics;\r\nusing System.IO;\r\nusing System.IO.Pipes;\r\nusing System.Net;\r\nusing System.Reflection;\r\nusing System.Text;\r\nusing System.Threading;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing CommandLine;\r\nusing Microsoft.Win32;\r\nusing NLog;\r\nusing ReactiveUI;\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Controller.Hotkeys;\r\nusing Shadowsocks.Util;\r\nusing Shadowsocks.View;\r\nusing Splat;\r\nusing WPFLocalizeExtension.Engine;\r\n\r\nnamespace Shadowsocks\r\n{\r\n    internal static class Program\r\n    {\r\n        private static readonly Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        public static ShadowsocksController MainController { get; private set; }\r\n        public static MenuViewController MenuController { get; private set; }\r\n        public static CommandLineOption Options { get; private set; }\r\n        public static string[] Args { get; private set; }\r\n\r\n        // https://github.com/dotnet/runtime/issues/13051#issuecomment-510267727\r\n        public static readonly string ExecutablePath = Process.GetCurrentProcess().MainModule?.FileName;\r\n        public static readonly string WorkingDirectory = Path.GetDirectoryName(ExecutablePath);\r\n\r\n        private static readonly Mutex mutex = new Mutex(true, $\"Shadowsocks_{ExecutablePath.GetHashCode()}\");\r\n\r\n        /// <summary>\r\n        /// 应用程序的主入口点。\r\n        /// </summary>\r\n        /// </summary>\r\n        [STAThread]\r\n        private static void Main(string[] args)\r\n        {\r\n            #region Single Instance and IPC\r\n            bool hasAnotherInstance = !mutex.WaitOne(TimeSpan.Zero, true);\r\n\r\n            // store args for further use\r\n            Args = args;\r\n            Parser.Default.ParseArguments<CommandLineOption>(args)\r\n                .WithParsed(opt => Options = opt)\r\n                .WithNotParsed(e => e.Output());\r\n\r\n            if (hasAnotherInstance)\r\n            {\r\n                if (!string.IsNullOrWhiteSpace(Options.OpenUrl))\r\n                {\r\n                    IPCService.RequestOpenUrl(Options.OpenUrl);\r\n                }\r\n                else\r\n                {\r\n                    MessageBox.Show(I18N.GetString(\"Find Shadowsocks icon in your notify tray.\")\r\n                                    + Environment.NewLine\r\n                                    + I18N.GetString(\"If you want to start multiple Shadowsocks, make a copy in another directory.\"),\r\n                        I18N.GetString(\"Shadowsocks is already running.\"));\r\n                }\r\n                return;\r\n            }\r\n            #endregion\r\n\r\n            #region Enviroment Setup\r\n            Directory.SetCurrentDirectory(WorkingDirectory);\r\n            // todo: initialize the NLog configuartion\r\n            Model.NLogConfig.TouchAndApplyNLogConfig();\r\n\r\n            // .NET Framework 4.7.2 on Win7 compatibility\r\n            ServicePointManager.SecurityProtocol |=\r\n                SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;\r\n            #endregion\r\n\r\n            #region Compactibility Check\r\n            // Check OS since we are using dual-mode socket\r\n            if (!Utils.IsWinVistaOrHigher())\r\n            {\r\n                MessageBox.Show(I18N.GetString(\"Unsupported operating system, use Windows Vista at least.\"),\r\n                \"Shadowsocks Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\r\n                return;\r\n            }\r\n\r\n            // Check .NET Framework version\r\n            if (!Utils.IsSupportedRuntimeVersion())\r\n            {\r\n                if (DialogResult.OK == MessageBox.Show(I18N.GetString(\"Unsupported .NET Framework, please update to {0} or later.\", \"4.8\"),\r\n                \"Shadowsocks Error\", MessageBoxButtons.OKCancel, MessageBoxIcon.Error))\r\n                {\r\n                    Process.Start(\"https://dotnet.microsoft.com/download/dotnet-framework/net48\");\r\n                }\r\n                return;\r\n            }\r\n            #endregion\r\n\r\n            #region Event Handlers Setup\r\n            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);\r\n            // handle UI exceptions\r\n            Application.ThreadException += Application_ThreadException;\r\n            // handle non-UI exceptions\r\n            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;\r\n            Application.ApplicationExit += Application_ApplicationExit;\r\n            SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;\r\n            Application.EnableVisualStyles();\r\n            Application.SetCompatibleTextRenderingDefault(false);\r\n            AutoStartup.RegisterForRestart(true);\r\n            #endregion\r\n\r\n            // We would use this in v5.\r\n            // Parameters would have to be dropped from views' constructors (VersionUpdatePromptView)\r\n            //Locator.CurrentMutable.RegisterViewsForViewModels(Assembly.GetCallingAssembly());\r\n\r\n            // Workaround for hosting WPF controls in a WinForms app.\r\n            // We have to manually set the culture for the LocalizeDictionary instance.\r\n            // https://stackoverflow.com/questions/374518/localizing-a-winforms-application-with-embedded-wpf-user-controls\r\n            // https://stackoverflow.com/questions/14668640/wpf-localize-extension-translate-window-at-run-time\r\n            LocalizeDictionary.Instance.Culture = Thread.CurrentThread.CurrentCulture;\r\n\r\n#if DEBUG\r\n            // truncate privoxy log file while debugging\r\n            string privoxyLogFilename = Utils.GetTempPath(\"privoxy.log\");\r\n            if (File.Exists(privoxyLogFilename))\r\n                using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }\r\n#endif\r\n            MainController = new ShadowsocksController();\r\n            MenuController = new MenuViewController(MainController);\r\n\r\n            HotKeys.Init(MainController);\r\n            MainController.Start();\r\n\r\n            // Update online config \r\n            Task.Run(async () =>\r\n            {\r\n                await Task.Delay(10 * 1000);\r\n                await MainController.UpdateAllOnlineConfig();\r\n            });\r\n\r\n#region IPC Handler and Arguement Process\r\n            IPCService ipcService = new IPCService();\r\n            Task.Run(() => ipcService.RunServer());\r\n            ipcService.OpenUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url);\r\n\r\n            if (!string.IsNullOrWhiteSpace(Options.OpenUrl))\r\n            {\r\n                MainController.AskAddServerBySSURL(Options.OpenUrl);\r\n            }\r\n#endregion\r\n            \r\n            Application.Run();\r\n\r\n        }\r\n\r\n        private static int exited = 0;\r\n        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\r\n        {\r\n            if (Interlocked.Increment(ref exited) == 1)\r\n            {\r\n                string errMsg = e.ExceptionObject.ToString();\r\n                logger.Error(errMsg);\r\n                MessageBox.Show(\r\n                    $\"{I18N.GetString(\"Unexpected error, shadowsocks will exit. Please report to\")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errMsg}\",\r\n                    \"Shadowsocks non-UI Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\r\n                Application.Exit();\r\n            }\r\n        }\r\n\r\n        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)\r\n        {\r\n            if (Interlocked.Increment(ref exited) == 1)\r\n            {\r\n                string errorMsg = $\"Exception Detail: {Environment.NewLine}{e.Exception}\";\r\n                logger.Error(errorMsg);\r\n                MessageBox.Show(\r\n                    $\"{I18N.GetString(\"Unexpected error, shadowsocks will exit. Please report to\")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errorMsg}\",\r\n                    \"Shadowsocks UI Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\r\n                Application.Exit();\r\n            }\r\n        }\r\n\r\n        private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)\r\n        {\r\n            switch (e.Mode)\r\n            {\r\n                case PowerModes.Resume:\r\n                    logger.Info(\"os wake up\");\r\n                    if (MainController != null)\r\n                    {\r\n                        Task.Factory.StartNew(() =>\r\n                        {\r\n                            Thread.Sleep(10 * 1000);\r\n                            try\r\n                            {\r\n                                MainController.Start(true);\r\n                                logger.Info(\"controller started\");\r\n                            }\r\n                            catch (Exception ex)\r\n                            {\r\n                                logger.LogUsefulException(ex);\r\n                            }\r\n                        });\r\n                    }\r\n                    break;\r\n                case PowerModes.Suspend:\r\n                    if (MainController != null)\r\n                    {\r\n                        MainController.Stop();\r\n                        logger.Info(\"controller stopped\");\r\n                    }\r\n                    logger.Info(\"os suspend\");\r\n                    break;\r\n            }\r\n        }\r\n\r\n        private static void Application_ApplicationExit(object sender, EventArgs e)\r\n        {\r\n            // detach static event handlers\r\n            Application.ApplicationExit -= Application_ApplicationExit;\r\n            SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;\r\n            Application.ThreadException -= Application_ThreadException;\r\n            HotKeys.Destroy();\r\n            if (MainController != null)\r\n            {\r\n                MainController.Stop();\r\n                MainController = null;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Properties/AssemblyInfo.cs",
    "content": "﻿using Shadowsocks.Controller;\r\nusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\n// 有关程序集的常规信息通过下列属性集\r\n// 控制。更改这些属性值可修改\r\n// 与程序集关联的信息。\r\n[assembly: AssemblyTitle(\"Shadowsocks\")]\r\n[assembly: AssemblyDescription(\"\")]\r\n[assembly: AssemblyConfiguration(\"\")]\r\n[assembly: AssemblyCompany(\"\")]\r\n[assembly: AssemblyProduct(\"Shadowsocks\")]\r\n[assembly: AssemblyCopyright(\"clowwindy & community 2020\")]\r\n[assembly: AssemblyTrademark(\"\")]\r\n[assembly: AssemblyCulture(\"\")]\r\n\r\n// 将 ComVisible 设置为 false 使此程序集中的类型\r\n// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型，\r\n// 则将该类型上的 ComVisible 属性设置为 true。\r\n[assembly: ComVisible(false)]\r\n\r\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\r\n[assembly: Guid(\"f8334709-4309-436a-8bbd-6165dcf4a660\")]\r\n\r\n// 程序集的版本信息由下面四个值组成:\r\n//\r\n//      主版本\r\n//      次版本 \r\n//      内部版本号\r\n//      修订号\r\n//\r\n// 可以指定所有这些值，也可以使用“内部版本号”和“修订号”的默认值，\r\n// 方法是按如下所示使用“*”:\r\n// [assembly: AssemblyVersion(\"1.0.*\")]\r\n[assembly: AssemblyVersion(UpdateChecker.Version)]\r\n// [assembly: AssemblyFileVersion(\"2.0.0\")]\r\n"
  },
  {
    "path": "shadowsocks-csharp/Properties/Resources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\r\n// <auto-generated>\r\n//     This code was generated by a tool.\r\n//     Runtime Version:4.0.30319.42000\r\n//\r\n//     Changes to this file may cause incorrect behavior and will be lost if\r\n//     the code is regenerated.\r\n// </auto-generated>\r\n//------------------------------------------------------------------------------\r\n\r\nnamespace Shadowsocks.Properties {\r\n    using System;\r\n    \r\n    \r\n    /// <summary>\r\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\r\n    /// </summary>\r\n    // This class was auto-generated by the StronglyTypedResourceBuilder\r\n    // class via a tool like ResGen or Visual Studio.\r\n    // To add or remove a member, edit your .ResX file then rerun ResGen\r\n    // with the /str option, or rebuild your VS project.\r\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"16.0.0.0\")]\r\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\r\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\r\n    public class Resources {\r\n        \r\n        private static global::System.Resources.ResourceManager resourceMan;\r\n        \r\n        private static global::System.Globalization.CultureInfo resourceCulture;\r\n        \r\n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\r\n        internal Resources() {\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Returns the cached ResourceManager instance used by this class.\r\n        /// </summary>\r\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\r\n        public static global::System.Resources.ResourceManager ResourceManager {\r\n            get {\r\n                if (object.ReferenceEquals(resourceMan, null)) {\r\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Shadowsocks.Properties.Resources\", typeof(Resources).Assembly);\r\n                    resourceMan = temp;\r\n                }\r\n                return resourceMan;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Overrides the current thread's CurrentUICulture property for all\r\n        ///   resource lookups using this strongly typed resource class.\r\n        /// </summary>\r\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\r\n        public static global::System.Globalization.CultureInfo Culture {\r\n            get {\r\n                return resourceCulture;\r\n            }\r\n            set {\r\n                resourceCulture = value;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized string similar to /* eslint-disable */\r\n        ///// Was generated by gfwlist2pac in precise mode\r\n        ///// https://github.com/clowwindy/gfwlist2pac\r\n        ///\r\n        ///// 2019-10-06: More &apos;javascript&apos; way to interaction with main program\r\n        ///// 2019-02-08: Updated to support shadowsocks-windows user rules.\r\n        ///\r\n        ///var proxy = __PROXY__;\r\n        ///var userrules = [];\r\n        ///var rules = [];\r\n        ///\r\n        ///// convert to abp grammar\r\n        ///var re = /^(@@)?\\|\\|.*?[^\\^]$/;\r\n        ///for (var i = 0; i &lt; __RULES__.length; i++) {\r\n        ///    var s = __RULES__[i];\r\n        ///    if (s.match(re)) s += &quot;^&quot;;\r\n        ///    rules.push(s);\r\n        ///}\r\n        ///\r\n        /// [rest of string was truncated]&quot;;.\r\n        /// </summary>\r\n        public static string abp_js {\r\n            get {\r\n                return ResourceManager.GetString(\"abp_js\", resourceCulture);\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized resource of type System.Byte[].\r\n        /// </summary>\r\n        public static byte[] dlc_dat {\r\n            get {\r\n                object obj = ResourceManager.GetObject(\"dlc_dat\", resourceCulture);\r\n                return ((byte[])(obj));\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized string similar to en,ru-RU,zh-CN,zh-TW,ja,ko,fr\r\n        ///#Restart program to apply translation,,,,,,\r\n        ///#This is comment line,,,,,,\r\n        ///#Always keep language name at head of file,,,,,,\r\n        ///#Language name is output in log,,,,,,\r\n        ///&quot;#You can find it by search &quot;&quot;Current language is:&quot;&quot;&quot;,,,,,,\r\n        ///#Please use UTF-8 with BOM encoding so we can edit it in Excel,,,,,,\r\n        ///,,,,,,\r\n        ///Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks\r\n        ///,,,,,,\r\n        ///#Menu,,,,,,\r\n        ///,,,,,,\r\n        ///System Proxy,Системный прокси-сервер,系统代理,系統代理,システムプロキシ,시스템 프록시,P [rest of string was truncated]&quot;;.\r\n        /// </summary>\r\n        public static string i18n_csv {\r\n            get {\r\n                return ResourceManager.GetString(\"i18n_csv\", resourceCulture);\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized resource of type System.Byte[].\r\n        /// </summary>\r\n        public static byte[] libsscrypto_dll {\r\n            get {\r\n                object obj = ResourceManager.GetObject(\"libsscrypto_dll\", resourceCulture);\r\n                return ((byte[])(obj));\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized string similar to &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;\r\n        ///&lt;!-- Warning: Configuration may reset after shadowsocks upgrade. --&gt;\r\n        ///&lt;!-- If you messed it up, delete this file and Shadowsocks will create a new one. --&gt;\r\n        ///&lt;nlog xmlns=&quot;http://www.nlog-project.org/schemas/NLog.xsd&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;\r\n        ///  &lt;targets&gt;\r\n        ///    &lt;!-- This line is managed by Shadowsocks. Do not modify it unless you know what you are doing.--&gt;\r\n        ///    &lt;target name=&quot;file&quot; xsi:type=&quot;File&quot; fileName=&quot;ss_win_temp\\shadowsocks.log&quot; writ [rest of string was truncated]&quot;;.\r\n        /// </summary>\r\n        public static string NLog_config {\r\n            get {\r\n                return ResourceManager.GetString(\"NLog_config\", resourceCulture);\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized string similar to listen-address __PRIVOXY_BIND_IP__:__PRIVOXY_BIND_PORT__\r\n        ///toggle 0\r\n        ///logfile ss_privoxy.log\r\n        ///show-on-task-bar 0\r\n        ///activity-animation 0\r\n        ///forward-socks5 / __SOCKS_HOST__:__SOCKS_PORT__ .\r\n        ///max-client-connections 2048\r\n        ///hide-console\r\n        ///.\r\n        /// </summary>\r\n        public static string privoxy_conf {\r\n            get {\r\n                return ResourceManager.GetString(\"privoxy_conf\", resourceCulture);\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized resource of type System.Byte[].\r\n        /// </summary>\r\n        public static byte[] privoxy_exe {\r\n            get {\r\n                object obj = ResourceManager.GetObject(\"privoxy_exe\", resourceCulture);\r\n                return ((byte[])(obj));\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized resource of type System.Drawing.Bitmap.\r\n        /// </summary>\r\n        public static System.Drawing.Bitmap ss32Fill {\r\n            get {\r\n                object obj = ResourceManager.GetObject(\"ss32Fill\", resourceCulture);\r\n                return ((System.Drawing.Bitmap)(obj));\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized resource of type System.Drawing.Bitmap.\r\n        /// </summary>\r\n        public static System.Drawing.Bitmap ss32In {\r\n            get {\r\n                object obj = ResourceManager.GetObject(\"ss32In\", resourceCulture);\r\n                return ((System.Drawing.Bitmap)(obj));\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized resource of type System.Drawing.Bitmap.\r\n        /// </summary>\r\n        public static System.Drawing.Bitmap ss32Out {\r\n            get {\r\n                object obj = ResourceManager.GetObject(\"ss32Out\", resourceCulture);\r\n                return ((System.Drawing.Bitmap)(obj));\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized resource of type System.Drawing.Bitmap.\r\n        /// </summary>\r\n        public static System.Drawing.Bitmap ss32Outline {\r\n            get {\r\n                object obj = ResourceManager.GetObject(\"ss32Outline\", resourceCulture);\r\n                return ((System.Drawing.Bitmap)(obj));\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized resource of type System.Drawing.Bitmap.\r\n        /// </summary>\r\n        public static System.Drawing.Bitmap ssw128 {\r\n            get {\r\n                object obj = ResourceManager.GetObject(\"ssw128\", resourceCulture);\r\n                return ((System.Drawing.Bitmap)(obj));\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized resource of type System.Byte[].\r\n        /// </summary>\r\n        public static byte[] sysproxy_exe {\r\n            get {\r\n                object obj = ResourceManager.GetObject(\"sysproxy_exe\", resourceCulture);\r\n                return ((byte[])(obj));\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized resource of type System.Byte[].\r\n        /// </summary>\r\n        public static byte[] sysproxy64_exe {\r\n            get {\r\n                object obj = ResourceManager.GetObject(\"sysproxy64_exe\", resourceCulture);\r\n                return ((byte[])(obj));\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized string similar to ! Put user rules line by line in this file.\r\n        ///! See https://adblockplus.org/en/filter-cheatsheet\r\n        ///.\r\n        /// </summary>\r\n        public static string user_rule {\r\n            get {\r\n                return ResourceManager.GetString(\"user_rule\", resourceCulture);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Properties/Resources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<root>\r\n  <!-- \r\n    Microsoft ResX Schema \r\n    \r\n    Version 2.0\r\n    \r\n    The primary goals of this format is to allow a simple XML format \r\n    that is mostly human readable. The generation and parsing of the \r\n    various data types are done through the TypeConverter classes \r\n    associated with the data types.\r\n    \r\n    Example:\r\n    \r\n    ... ado.net/XML headers & schema ...\r\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\r\n    <resheader name=\"version\">2.0</resheader>\r\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\r\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\r\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\r\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\r\n    </data>\r\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\r\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r\n        <comment>This is a comment</comment>\r\n    </data>\r\n                \r\n    There are any number of \"resheader\" rows that contain simple \r\n    name/value pairs.\r\n    \r\n    Each data row contains a name, and value. The row also contains a \r\n    type or mimetype. Type corresponds to a .NET class that support \r\n    text/value conversion through the TypeConverter architecture. \r\n    Classes that don't support this are serialized and stored with the \r\n    mimetype set.\r\n    \r\n    The mimetype is used for serialized objects, and tells the \r\n    ResXResourceReader how to depersist the object. This is currently not \r\n    extensible. For a given mimetype the value must be set accordingly:\r\n    \r\n    Note - application/x-microsoft.net.object.binary.base64 is the format \r\n    that the ResXResourceWriter will generate, however the reader can \r\n    read any of the formats listed below.\r\n    \r\n    mimetype: application/x-microsoft.net.object.binary.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r\n            : and then encoded with base64 encoding.\r\n    \r\n    mimetype: application/x-microsoft.net.object.soap.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r\n            : and then encoded with base64 encoding.\r\n\r\n    mimetype: application/x-microsoft.net.object.bytearray.base64\r\n    value   : The object must be serialized into a byte array \r\n            : using a System.ComponentModel.TypeConverter\r\n            : and then encoded with base64 encoding.\r\n    -->\r\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\r\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\r\n      <xsd:complexType>\r\n        <xsd:choice maxOccurs=\"unbounded\">\r\n          <xsd:element name=\"metadata\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"assembly\">\r\n            <xsd:complexType>\r\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"data\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"resheader\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n        </xsd:choice>\r\n      </xsd:complexType>\r\n    </xsd:element>\r\n  </xsd:schema>\r\n  <resheader name=\"resmimetype\">\r\n    <value>text/microsoft-resx</value>\r\n  </resheader>\r\n  <resheader name=\"version\">\r\n    <value>2.0</value>\r\n  </resheader>\r\n  <resheader name=\"reader\">\r\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <resheader name=\"writer\">\r\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <assembly alias=\"System.Windows.Forms\" name=\"System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" />\r\n  <data name=\"abp_js\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\Data\\abp.js;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;gb2312</value>\r\n  </data>\r\n  <data name=\"dlc_dat\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\data\\dlc.dat;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </data>\r\n  <data name=\"i18n_csv\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\Data\\i18n.csv;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>\r\n  </data>\r\n  <data name=\"libsscrypto_dll\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\Data\\libsscrypto.dll.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </data>\r\n  <data name=\"NLog_config\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\data\\nlog.config;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>\r\n  </data>\r\n  <data name=\"privoxy_conf\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\data\\privoxy_conf.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>\r\n  </data>\r\n  <data name=\"privoxy_exe\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\data\\privoxy.exe.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </data>\r\n  <data name=\"ss32Fill\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\Resources\\ss32Fill.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>\r\n  </data>\r\n  <data name=\"ss32In\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\Resources\\ss32In.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>\r\n  </data>\r\n  <data name=\"ss32Out\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\Resources\\ss32Out.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>\r\n  </data>\r\n  <data name=\"ss32Outline\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\Resources\\ss32Outline.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>\r\n  </data>\r\n  <data name=\"ssw128\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\Resources\\ssw128.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>\r\n  </data>\r\n  <data name=\"sysproxy64_exe\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\Data\\sysproxy64.exe.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </data>\r\n  <data name=\"sysproxy_exe\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\Data\\sysproxy.exe.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </data>\r\n  <data name=\"user_rule\" type=\"System.Resources.ResXFileRef, System.Windows.Forms\">\r\n    <value>..\\data\\user-rule.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>\r\n  </data>\r\n</root>"
  },
  {
    "path": "shadowsocks-csharp/Properties/Settings.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\r\n// <auto-generated>\r\n//     This code was generated by a tool.\r\n//     Runtime Version:4.0.30319.42000\r\n//\r\n//     Changes to this file may cause incorrect behavior and will be lost if\r\n//     the code is regenerated.\r\n// </auto-generated>\r\n//------------------------------------------------------------------------------\r\n\r\nnamespace Shadowsocks.Properties {\r\n    \r\n    \r\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\r\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator\", \"16.8.1.0\")]\r\n    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {\r\n        \r\n        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));\r\n        \r\n        public static Settings Default {\r\n            get {\r\n                return defaultInstance;\r\n            }\r\n        }\r\n        \r\n        [global::System.Configuration.UserScopedSettingAttribute()]\r\n        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\r\n        [global::System.Configuration.DefaultSettingValueAttribute(\"600\")]\r\n        public int LogViewerWidth {\r\n            get {\r\n                return ((int)(this[\"LogViewerWidth\"]));\r\n            }\r\n            set {\r\n                this[\"LogViewerWidth\"] = value;\r\n            }\r\n        }\r\n        \r\n        [global::System.Configuration.UserScopedSettingAttribute()]\r\n        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\r\n        [global::System.Configuration.DefaultSettingValueAttribute(\"400\")]\r\n        public int LogViewerHeight {\r\n            get {\r\n                return ((int)(this[\"LogViewerHeight\"]));\r\n            }\r\n            set {\r\n                this[\"LogViewerHeight\"] = value;\r\n            }\r\n        }\r\n        \r\n        [global::System.Configuration.UserScopedSettingAttribute()]\r\n        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\r\n        [global::System.Configuration.DefaultSettingValueAttribute(\"True\")]\r\n        public bool LogViewerMaximized {\r\n            get {\r\n                return ((bool)(this[\"LogViewerMaximized\"]));\r\n            }\r\n            set {\r\n                this[\"LogViewerMaximized\"] = value;\r\n            }\r\n        }\r\n        \r\n        [global::System.Configuration.UserScopedSettingAttribute()]\r\n        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\r\n        [global::System.Configuration.DefaultSettingValueAttribute(\"0\")]\r\n        public int LogViewerTop {\r\n            get {\r\n                return ((int)(this[\"LogViewerTop\"]));\r\n            }\r\n            set {\r\n                this[\"LogViewerTop\"] = value;\r\n            }\r\n        }\r\n        \r\n        [global::System.Configuration.UserScopedSettingAttribute()]\r\n        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\r\n        [global::System.Configuration.DefaultSettingValueAttribute(\"0\")]\r\n        public int LogViewerLeft {\r\n            get {\r\n                return ((int)(this[\"LogViewerLeft\"]));\r\n            }\r\n            set {\r\n                this[\"LogViewerLeft\"] = value;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Properties/Settings.settings",
    "content": "﻿<?xml version='1.0' encoding='utf-8'?>\n<SettingsFile xmlns=\"http://schemas.microsoft.com/VisualStudio/2004/01/settings\" CurrentProfile=\"(Default)\" GeneratedClassNamespace=\"Shadowsocks.Properties\" GeneratedClassName=\"Settings\">\n  <Profiles />\n  <Settings>\n    <Setting Name=\"LogViewerWidth\" Type=\"System.Int32\" Scope=\"User\">\n      <Value Profile=\"(Default)\">600</Value>\n    </Setting>\n    <Setting Name=\"LogViewerHeight\" Type=\"System.Int32\" Scope=\"User\">\n      <Value Profile=\"(Default)\">400</Value>\n    </Setting>\n    <Setting Name=\"LogViewerMaximized\" Type=\"System.Boolean\" Scope=\"User\">\n      <Value Profile=\"(Default)\">True</Value>\n    </Setting>\n    <Setting Name=\"LogViewerTop\" Type=\"System.Int32\" Scope=\"User\">\n      <Value Profile=\"(Default)\">0</Value>\n    </Setting>\n    <Setting Name=\"LogViewerLeft\" Type=\"System.Int32\" Scope=\"User\">\n      <Value Profile=\"(Default)\">0</Value>\n    </Setting>\n  </Settings>\n</SettingsFile>"
  },
  {
    "path": "shadowsocks-csharp/Proxy/DirectConnect.cs",
    "content": "﻿using System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading;\nusing Shadowsocks.Util.Sockets;\n\nnamespace Shadowsocks.Proxy\n{\n    public class DirectConnect : IProxy\n    {\n        private class FakeAsyncResult : IAsyncResult\n        {\n            public FakeAsyncResult(object state)\n            {\n                AsyncState = state;\n            }\n\n            public bool IsCompleted { get; } = true;\n            public WaitHandle AsyncWaitHandle { get; } = null;\n            public object AsyncState { get; }\n            public bool CompletedSynchronously { get; } = true;\n        }\n\n        private class FakeEndPoint : EndPoint\n        {\n            public override AddressFamily AddressFamily { get; } = AddressFamily.Unspecified;\n\n            public override string ToString()\n            {\n                return \"null proxy\";\n            }\n        }\n\n        private WrappedSocket _remote = new WrappedSocket();\n\n        public EndPoint LocalEndPoint => _remote.LocalEndPoint;\n\n        public EndPoint ProxyEndPoint { get; } = new FakeEndPoint();\n        public EndPoint DestEndPoint { get; private set; }\n\n        public void BeginConnectProxy(EndPoint remoteEP, AsyncCallback callback, object state)\n        {\n            // do nothing\n\n            var r = new FakeAsyncResult(state);\n            callback?.Invoke(r);\n        }\n\n        public void EndConnectProxy(IAsyncResult asyncResult)\n        {\n            // do nothing\n        }\n\n        public void BeginConnectDest(EndPoint destEndPoint, AsyncCallback callback, object state, NetworkCredential auth = null)\n        {\n            DestEndPoint = destEndPoint;\n\n            _remote.BeginConnect(destEndPoint, callback, state);\n        }\n\n        public void EndConnectDest(IAsyncResult asyncResult)\n        {\n            _remote.EndConnect(asyncResult);\n            _remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);\n        }\n\n        public void BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,\n            object state)\n        {\n            _remote.BeginSend(buffer, offset, size, socketFlags, callback, state);\n        }\n\n        public int EndSend(IAsyncResult asyncResult)\n        {\n            return _remote.EndSend(asyncResult);\n        }\n\n        public void BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,\n            object state)\n        {\n            _remote.BeginReceive(buffer, offset, size, socketFlags, callback, state);\n        }\n\n        public int EndReceive(IAsyncResult asyncResult)\n        {\n            return _remote.EndReceive(asyncResult);\n        }\n\n        public void Shutdown(SocketShutdown how)\n        {\n            _remote.Shutdown(how);\n        }\n\n        public void Close()\n        {\n            _remote.Dispose();\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Proxy/HttpProxy.cs",
    "content": "﻿using System;\r\nusing System.Net;\r\nusing System.Net.Sockets;\r\nusing System.Text;\r\nusing System.Text.RegularExpressions;\r\nusing System.Threading;\r\nusing NLog;\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Util.Sockets;\r\n\r\nnamespace Shadowsocks.Proxy\r\n{\r\n    public class HttpProxy : IProxy\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private class FakeAsyncResult : IAsyncResult\r\n        {\r\n            public readonly HttpState innerState;\r\n\r\n            private readonly IAsyncResult r;\r\n\r\n            public FakeAsyncResult(IAsyncResult orig, HttpState state)\r\n            {\r\n                r = orig;\r\n                innerState = state;\r\n            }\r\n\r\n            public bool IsCompleted => r.IsCompleted;\r\n            public WaitHandle AsyncWaitHandle => r.AsyncWaitHandle;\r\n            public object AsyncState => innerState.AsyncState;\r\n            public bool CompletedSynchronously => r.CompletedSynchronously;\r\n        }\r\n\r\n        private class HttpState\r\n        {\r\n\r\n            public AsyncCallback Callback { get; set; }\r\n\r\n            public object AsyncState { get; set; }\r\n\r\n            public Exception ex { get; set; }\r\n        }\r\n\r\n        public EndPoint LocalEndPoint => _remote.LocalEndPoint;\r\n        public EndPoint ProxyEndPoint { get; private set; }\r\n        public EndPoint DestEndPoint { get; private set; }\r\n\r\n\r\n        private readonly WrappedSocket _remote = new WrappedSocket();\r\n\r\n\r\n        public void BeginConnectProxy(EndPoint remoteEP, AsyncCallback callback, object state)\r\n        {\r\n            ProxyEndPoint = remoteEP;\r\n\r\n            _remote.BeginConnect(remoteEP, callback, state);\r\n        }\r\n\r\n        public void EndConnectProxy(IAsyncResult asyncResult)\r\n        {\r\n            _remote.EndConnect(asyncResult);\r\n            _remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);\r\n        }\r\n\r\n        private const string HTTP_CRLF = \"\\r\\n\";\r\n        private const string HTTP_CONNECT_TEMPLATE = \r\n            \"CONNECT {0} HTTP/1.1\" + HTTP_CRLF + \r\n            \"Host: {0}\" + HTTP_CRLF +\r\n            \"Proxy-Connection: keep-alive\" + HTTP_CRLF +\r\n            \"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 +\r\n            \"{1}\" +         // Proxy-Authorization if any\r\n            \"\" + HTTP_CRLF; // End with an empty line\r\n        private const string PROXY_AUTH_TEMPLATE = \"Proxy-Authorization: Basic {0}\" + HTTP_CRLF;\r\n\r\n        public void BeginConnectDest(EndPoint destEndPoint, AsyncCallback callback, object state, NetworkCredential auth = null)\r\n        {\r\n            DestEndPoint = destEndPoint;\r\n            String authInfo = \"\";\r\n            if (auth != null)\r\n            {\r\n                string authKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(auth.UserName + \":\" + auth.Password));\r\n                authInfo = string.Format(PROXY_AUTH_TEMPLATE, authKey);\r\n            }\r\n            string request = string.Format(HTTP_CONNECT_TEMPLATE, destEndPoint, authInfo);\r\n\r\n            var b = Encoding.UTF8.GetBytes(request);\r\n\r\n            var st = new HttpState();\r\n            st.Callback = callback;\r\n            st.AsyncState = state;\r\n\r\n            _remote.BeginSend(b, 0, b.Length, 0, HttpRequestSendCallback, st);\r\n        }\r\n\r\n        public void EndConnectDest(IAsyncResult asyncResult)\r\n        {\r\n            var state = ((FakeAsyncResult)asyncResult).innerState;\r\n\r\n            if (state.ex != null)\r\n            {\r\n                throw state.ex;\r\n            }\r\n        }\r\n\r\n        public void BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,\r\n            object state)\r\n        {\r\n            _remote.BeginSend(buffer, offset, size, socketFlags, callback, state);\r\n        }\r\n\r\n        public int EndSend(IAsyncResult asyncResult)\r\n        {\r\n            return _remote.EndSend(asyncResult);\r\n        }\r\n\r\n        public void BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,\r\n            object state)\r\n        {\r\n            _remote.BeginReceive(buffer, offset, size, socketFlags, callback, state);\r\n        }\r\n\r\n        public int EndReceive(IAsyncResult asyncResult)\r\n        {\r\n            return _remote.EndReceive(asyncResult);\r\n        }\r\n\r\n        public void Shutdown(SocketShutdown how)\r\n        {\r\n            _remote.Shutdown(how);\r\n        }\r\n\r\n        public void Close()\r\n        {\r\n            _remote.Dispose();\r\n        }\r\n\r\n        private void HttpRequestSendCallback(IAsyncResult ar)\r\n        {\r\n            var state = (HttpState) ar.AsyncState;\r\n            try\r\n            {\r\n                _remote.EndSend(ar);\r\n\r\n                // start line read\r\n                new LineReader(_remote, OnLineRead, OnException, OnFinish, Encoding.UTF8, HTTP_CRLF, 1024, new FakeAsyncResult(ar, state));\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                state.ex = ex;\r\n                state.Callback?.Invoke(new FakeAsyncResult(ar, state));\r\n            }\r\n        }\r\n\r\n        private void OnFinish(byte[] lastBytes, int index, int length, object state)\r\n        {\r\n            var st = (FakeAsyncResult)state;\r\n\r\n            if (st.innerState.ex == null)\r\n            {\r\n                if (!_established)\r\n                {\r\n                    st.innerState.ex = new Exception(I18N.GetString(\"Proxy request failed\"));\r\n                }\r\n                // TODO: save last bytes\r\n            }\r\n            st.innerState.Callback?.Invoke(st);\r\n        }\r\n\r\n        private void OnException(Exception ex, object state)\r\n        {\r\n            var st = (FakeAsyncResult) state;\r\n\r\n            st.innerState.ex = ex;\r\n        }\r\n\r\n        private static readonly Regex HttpRespondHeaderRegex = new Regex(@\"^(HTTP/1\\.\\d) (\\d{3}) (.+)$\", RegexOptions.Compiled);\r\n        private int _respondLineCount = 0;\r\n        private bool _established = false;\r\n\r\n        private bool OnLineRead(string line, object state)\r\n        {\r\n            logger.Trace(line);\r\n\r\n            if (_respondLineCount == 0)\r\n            {\r\n                var m = HttpRespondHeaderRegex.Match(line);\r\n                if (m.Success)\r\n                {\r\n                    var resultCode = m.Groups[2].Value;\r\n                    if (\"200\" != resultCode)\r\n                    {\r\n                        return true;\r\n                    }\r\n                    _established = true;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                if (string.IsNullOrEmpty(line))\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n            _respondLineCount++;\r\n\r\n            return false;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Proxy/IProxy.cs",
    "content": "﻿using System;\nusing System.Net;\nusing System.Net.Sockets;\n\nnamespace Shadowsocks.Proxy\n{\n\n    public interface IProxy\n    {\n        EndPoint LocalEndPoint { get; }\n\n        EndPoint ProxyEndPoint { get; }\n\n        EndPoint DestEndPoint { get; }\n\n        void BeginConnectProxy(EndPoint remoteEP, AsyncCallback callback, object state);\n\n        void EndConnectProxy(IAsyncResult asyncResult);\n\n        void BeginConnectDest(EndPoint destEndPoint, AsyncCallback callback, object state, NetworkCredential auth = null);\n\n        void EndConnectDest(IAsyncResult asyncResult);\n\n        void BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,\n            object state);\n\n        int EndSend(IAsyncResult asyncResult);\n\n        void BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,\n            object state);\n\n        int EndReceive(IAsyncResult asyncResult);\n\n        void Shutdown(SocketShutdown how);\n\n        void Close();\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Proxy/Socks5Proxy.cs",
    "content": "﻿using System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\nusing Shadowsocks.Controller;\nusing Shadowsocks.Util.Sockets;\n\nnamespace Shadowsocks.Proxy\n{\n    public class Socks5Proxy : IProxy\n    {\n        private class FakeAsyncResult : IAsyncResult\n        {\n            public readonly Socks5State innerState;\n\n            private readonly IAsyncResult r;\n\n            public FakeAsyncResult(IAsyncResult orig, Socks5State state)\n            {\n                r = orig;\n                innerState = state;\n            }\n\n            public bool IsCompleted => r.IsCompleted;\n            public WaitHandle AsyncWaitHandle => r.AsyncWaitHandle;\n            public object AsyncState => innerState.AsyncState;\n            public bool CompletedSynchronously => r.CompletedSynchronously;\n        }\n\n        private class Socks5State\n        {\n            public AsyncCallback Callback { get; set; }\n\n            public object AsyncState { get; set; }\n\n            public int BytesToRead;\n\n            public Exception ex { get; set; }\n        }\n\n        private readonly WrappedSocket _remote = new WrappedSocket();\n\n        private const int Socks5PktMaxSize = 4 + 16 + 2;\n        private readonly byte[] _receiveBuffer = new byte[Socks5PktMaxSize];\n\n        public EndPoint LocalEndPoint => _remote.LocalEndPoint;\n        public EndPoint ProxyEndPoint { get; private set; }\n        public EndPoint DestEndPoint { get; private set; }\n\n        public void BeginConnectProxy(EndPoint remoteEP, AsyncCallback callback, object state)\n        {\n            var st = new Socks5State();\n            st.Callback = callback;\n            st.AsyncState = state;\n\n            ProxyEndPoint = remoteEP;\n\n            _remote.BeginConnect(remoteEP, ConnectCallback, st);\n        }\n\n        public void EndConnectProxy(IAsyncResult asyncResult)\n        {\n            var state = ((FakeAsyncResult)asyncResult).innerState;\n\n            if (state.ex != null)\n            {\n                throw state.ex;\n            }\n        }\n\n        public void BeginConnectDest(EndPoint destEndPoint, AsyncCallback callback, object state, NetworkCredential auth = null)\n        {\n            // TODO: support SOCKS5 auth\n            DestEndPoint = destEndPoint;\n\n            byte[] request = null;\n            byte atyp = 0;\n            int port;\n\n            var dep = destEndPoint as DnsEndPoint;\n            if (dep != null)\n            {\n                // is a domain name, we will leave it to server\n\n                atyp = 3; // DOMAINNAME\n                var enc = Encoding.UTF8;\n                var hostByteCount = enc.GetByteCount(dep.Host);\n\n                request = new byte[4 + 1/*length byte*/ + hostByteCount + 2];\n                request[4] = (byte)hostByteCount;\n                enc.GetBytes(dep.Host, 0, dep.Host.Length, request, 5);\n\n                port = dep.Port;\n            }\n            else\n            {\n                switch (DestEndPoint.AddressFamily)\n                {\n                    case AddressFamily.InterNetwork:\n                        request = new byte[4 + 4 + 2];\n                        atyp = 1; // IP V4 address\n                        break;\n                    case AddressFamily.InterNetworkV6:\n                        request = new byte[4 + 16 + 2];\n                        atyp = 4; // IP V6 address\n                        break;\n                    default:\n                        throw new Exception(I18N.GetString(\"Proxy request failed\"));\n                }\n                port = ((IPEndPoint) DestEndPoint).Port;\n                var addr = ((IPEndPoint)DestEndPoint).Address.GetAddressBytes();\n                Array.Copy(addr, 0, request, 4, request.Length - 4 - 2);\n            }\n\n            // 构造request包剩余部分\n            request[0] = 5;\n            request[1] = 1;\n            request[2] = 0;\n            request[3] = atyp;\n            request[request.Length - 2] = (byte) ((port >> 8) & 0xff);\n            request[request.Length - 1] = (byte) (port & 0xff);\n\n            var st = new Socks5State();\n            st.Callback = callback;\n            st.AsyncState = state;\n\n            _remote.BeginSend(request, 0, request.Length, 0, Socks5RequestSendCallback, st);\n        }\n\n        public void EndConnectDest(IAsyncResult asyncResult)\n        {\n            var state = ((FakeAsyncResult)asyncResult).innerState;\n\n            if (state.ex != null)\n            {\n                throw state.ex;\n            }\n        }\n\n        public void BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,\n            object state)\n        {\n            _remote.BeginSend(buffer, offset, size, socketFlags, callback, state);\n        }\n\n        public int EndSend(IAsyncResult asyncResult)\n        {\n            return _remote.EndSend(asyncResult);\n        }\n\n        public void BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,\n            object state)\n        {\n            _remote.BeginReceive(buffer, offset, size, socketFlags, callback, state);\n        }\n\n        public int EndReceive(IAsyncResult asyncResult)\n        {\n            return _remote.EndReceive(asyncResult);\n        }\n\n        public void Shutdown(SocketShutdown how)\n        {\n            _remote.Shutdown(how);\n        }\n\n        public void Close()\n        {\n            _remote.Dispose();\n        }\n        \n\n        private void ConnectCallback(IAsyncResult ar)\n        {\n            var state = (Socks5State) ar.AsyncState;\n            try\n            {\n                _remote.EndConnect(ar);\n\n                _remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);\n\n                byte[] handshake = {5, 1, 0};\n                _remote.BeginSend(handshake, 0, handshake.Length, 0, Socks5HandshakeSendCallback, state);\n            }\n            catch (Exception ex)\n            {\n                state.ex = ex;\n                state.Callback?.Invoke(new FakeAsyncResult(ar, state));\n            }\n        }\n\n        private void Socks5HandshakeSendCallback(IAsyncResult ar)\n        {\n            var state = (Socks5State)ar.AsyncState;\n            try\n            {\n                _remote.EndSend(ar);\n\n                _remote.BeginReceive(_receiveBuffer, 0, 2, 0, Socks5HandshakeReceiveCallback, state);\n            }\n            catch (Exception ex)\n            {\n                state.ex = ex;\n                state.Callback?.Invoke(new FakeAsyncResult(ar, state));\n            }\n        }\n\n        private void Socks5HandshakeReceiveCallback(IAsyncResult ar)\n        {\n            Exception ex = null;\n            var state = (Socks5State)ar.AsyncState;\n            try\n            {\n                var bytesRead = _remote.EndReceive(ar);\n                if (bytesRead >= 2)\n                {\n                    if (_receiveBuffer[0] != 5 || _receiveBuffer[1] != 0)\n                    {\n                        ex = new Exception(I18N.GetString(\"Proxy handshake failed\"));\n                    }\n                }\n                else\n                {\n                    ex = new Exception(I18N.GetString(\"Proxy handshake failed\"));\n                }\n            }\n            catch (Exception ex2)\n            {\n                ex = ex2;\n            }\n            state.ex = ex;\n            state.Callback?.Invoke(new FakeAsyncResult(ar, state));\n        }\n\n\n        private void Socks5RequestSendCallback(IAsyncResult ar)\n        {\n            var state = (Socks5State)ar.AsyncState;\n            try\n            {\n                _remote.EndSend(ar);\n\n                _remote.BeginReceive(_receiveBuffer, 0, 4, 0, Socks5ReplyReceiveCallback, state);\n            }\n            catch (Exception ex)\n            {\n                state.ex = ex;\n                state.Callback?.Invoke(new FakeAsyncResult(ar, state));\n            }\n        }\n\n        private void Socks5ReplyReceiveCallback(IAsyncResult ar)\n        {\n            var state = (Socks5State)ar.AsyncState;\n            try\n            {\n                var bytesRead = _remote.EndReceive(ar);\n                if (bytesRead >= 4)\n                {\n                    if (_receiveBuffer[0] == 5 && _receiveBuffer[1] == 0)\n                    {\n                        // 跳过剩下的reply\n                        switch (_receiveBuffer[3]) // atyp\n                        {\n                            case 1:\n                                state.BytesToRead = 4 + 2;\n                                _remote.BeginReceive(_receiveBuffer, 0, 4 + 2, 0, Socks5ReplyReceiveCallback2, state);\n                                break;\n                            case 4:\n                                state.BytesToRead = 16 + 2;\n                                _remote.BeginReceive(_receiveBuffer, 0, 16 + 2, 0, Socks5ReplyReceiveCallback2, state);\n                                break;\n                            default:\n                                state.ex = new Exception(I18N.GetString(\"Proxy request failed\"));\n                                state.Callback?.Invoke(new FakeAsyncResult(ar, state));\n                                break;\n                        }\n                    }\n                    else\n                    {\n                        state.ex = new Exception(I18N.GetString(\"Proxy request failed\"));\n                        state.Callback?.Invoke(new FakeAsyncResult(ar, state));\n                    }\n                }\n                else\n                {\n                    state.ex = new Exception(I18N.GetString(\"Proxy request failed\"));\n                    state.Callback?.Invoke(new FakeAsyncResult(ar, state));\n                }\n            }\n            catch (Exception ex)\n            {\n                state.ex = ex;\n                state.Callback?.Invoke(new FakeAsyncResult(ar, state));\n            }\n        }\n\n\n        private void Socks5ReplyReceiveCallback2(IAsyncResult ar)\n        {\n            Exception ex = null;\n            var state = (Socks5State)ar.AsyncState;\n            try\n            {\n                var bytesRead = _remote.EndReceive(ar);\n                var bytesNeedSkip = state.BytesToRead;\n\n                if (bytesRead < bytesNeedSkip)\n                {\n                    ex = new Exception(I18N.GetString(\"Proxy request failed\"));\n                }\n            }\n            catch (Exception ex2)\n            {\n                ex = ex2;\n            }\n\n            state.ex = ex;\n            state.Callback?.Invoke(new FakeAsyncResult(ar, state));\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Settings.cs",
    "content": "﻿namespace Shadowsocks.Properties {\n    \n    \n    // 通过此类可以处理设置类的特定事件: \n    //  在更改某个设置的值之前将引发 SettingChanging 事件。\n    //  在更改某个设置的值之后将引发 PropertyChanged 事件。\n    //  在加载设置值之后将引发 SettingsLoaded 事件。\n    //  在保存设置值之前将引发 SettingsSaving 事件。\n    internal sealed partial class Settings {\n        \n        public Settings() {\n            // // 若要为保存和更改设置添加事件处理程序，请取消注释下列行: \n            //\n            // this.SettingChanging += this.SettingChangingEventHandler;\n            //\n            // this.SettingsSaving += this.SettingsSavingEventHandler;\n            //\n        }\n        \n        private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {\n            // 在此处添加用于处理 SettingChangingEvent 事件的代码。\n        }\n        \n        private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {\n            // 在此处添加用于处理 SettingsSaving 事件的代码。\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Util/ProcessManagement/Job.cs",
    "content": "﻿using System;\r\nusing System.Diagnostics;\r\nusing System.Runtime.InteropServices;\r\nusing NLog;\r\nusing Shadowsocks.Controller;\r\n\r\nnamespace Shadowsocks.Util.ProcessManagement\r\n{\r\n    /*\r\n     * See:\r\n     * http://stackoverflow.com/questions/6266820/working-example-of-createjobobject-setinformationjobobject-pinvoke-in-net\r\n     */\r\n    public class Job : IDisposable\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private IntPtr handle = IntPtr.Zero;\r\n\r\n        public Job()\r\n        {\r\n            handle = CreateJobObject(IntPtr.Zero, null);\r\n            var extendedInfoPtr = IntPtr.Zero;\r\n            var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION\r\n            {\r\n                LimitFlags = 0x2000\r\n            };\r\n\r\n            var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION\r\n            {\r\n                BasicLimitInformation = info\r\n            };\r\n\r\n            try\r\n            {\r\n                int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));\r\n                extendedInfoPtr = Marshal.AllocHGlobal(length);\r\n                Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);\r\n\r\n                if (!SetInformationJobObject(handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr,\r\n                        (uint) length))\r\n                    throw new Exception(string.Format(\"Unable to set information.  Error: {0}\",\r\n                        Marshal.GetLastWin32Error()));\r\n            }\r\n            finally\r\n            {\r\n                if (extendedInfoPtr != IntPtr.Zero)\r\n                {\r\n                    Marshal.FreeHGlobal(extendedInfoPtr);\r\n                    extendedInfoPtr = IntPtr.Zero;\r\n                }\r\n            }\r\n        }\r\n\r\n        public bool AddProcess(IntPtr processHandle)\r\n        {\r\n            var succ = AssignProcessToJobObject(handle, processHandle);\r\n\r\n            if (!succ)\r\n            {\r\n                logger.Error(\"Failed to call AssignProcessToJobObject! GetLastError=\" + Marshal.GetLastWin32Error());\r\n            }\r\n\r\n            return succ;\r\n        }\r\n\r\n        public bool AddProcess(int processId)\r\n        {\r\n            return AddProcess(Process.GetProcessById(processId).Handle);\r\n        }\r\n\r\n        #region IDisposable\r\n\r\n        private bool disposed;\r\n\r\n        public void Dispose()\r\n        {\r\n            Dispose(true);\r\n            GC.SuppressFinalize(this);\r\n        }\r\n\r\n        protected virtual void Dispose(bool disposing)\r\n        {\r\n            if (disposed) return;\r\n            disposed = true;\r\n\r\n            if (disposing)\r\n            {\r\n                // no managed objects to free\r\n            }\r\n\r\n            if (handle != IntPtr.Zero)\r\n            {\r\n                CloseHandle(handle);\r\n                handle = IntPtr.Zero;\r\n            }\r\n        }\r\n\r\n        ~Job()\r\n        {\r\n            Dispose(false);\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Interop\r\n\r\n        [DllImport(\"kernel32.dll\", CharSet = CharSet.Unicode)]\r\n        private static extern IntPtr CreateJobObject(IntPtr a, string lpName);\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true)]\r\n        private static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, UInt32 cbJobObjectInfoLength);\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true)]\r\n        private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true)]\r\n        [return: MarshalAs(UnmanagedType.Bool)]\r\n        private static extern bool CloseHandle(IntPtr hObject);\r\n\r\n        #endregion\r\n    }\r\n\r\n    #region Helper classes\r\n\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    struct IO_COUNTERS\r\n    {\r\n        public UInt64 ReadOperationCount;\r\n        public UInt64 WriteOperationCount;\r\n        public UInt64 OtherOperationCount;\r\n        public UInt64 ReadTransferCount;\r\n        public UInt64 WriteTransferCount;\r\n        public UInt64 OtherTransferCount;\r\n    }\r\n\r\n\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    struct JOBOBJECT_BASIC_LIMIT_INFORMATION\r\n    {\r\n        public Int64 PerProcessUserTimeLimit;\r\n        public Int64 PerJobUserTimeLimit;\r\n        public UInt32 LimitFlags;\r\n        public UIntPtr MinimumWorkingSetSize;\r\n        public UIntPtr MaximumWorkingSetSize;\r\n        public UInt32 ActiveProcessLimit;\r\n        public UIntPtr Affinity;\r\n        public UInt32 PriorityClass;\r\n        public UInt32 SchedulingClass;\r\n    }\r\n\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public struct SECURITY_ATTRIBUTES\r\n    {\r\n        public UInt32 nLength;\r\n        public IntPtr lpSecurityDescriptor;\r\n        public Int32 bInheritHandle;\r\n    }\r\n\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION\r\n    {\r\n        public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;\r\n        public IO_COUNTERS IoInfo;\r\n        public UIntPtr ProcessMemoryLimit;\r\n        public UIntPtr JobMemoryLimit;\r\n        public UIntPtr PeakProcessMemoryUsed;\r\n        public UIntPtr PeakJobMemoryUsed;\r\n    }\r\n\r\n    public enum JobObjectInfoType\r\n    {\r\n        AssociateCompletionPortInformation = 7,\r\n        BasicLimitInformation = 2,\r\n        BasicUIRestrictions = 4,\r\n        EndOfJobTimeInformation = 6,\r\n        ExtendedLimitInformation = 9,\r\n        SecurityLimitInformation = 5,\r\n        GroupInformation = 11\r\n    }\r\n\r\n    #endregion\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Util/ProcessManagement/ThreadUtil.cs",
    "content": "﻿using System.Diagnostics;\nusing System.Management;\nusing System.Text;\n\nnamespace Shadowsocks.Util.ProcessManagement\n{\n    static class ThreadUtil\n    {\n\n        /*\n         * See:\n         * http://stackoverflow.com/questions/2633628/can-i-get-command-line-arguments-of-other-processes-from-net-c\n         */\n        public static string GetCommandLine(this Process process)\n        {\n            var commandLine = new StringBuilder(process.MainModule.FileName);\n\n            commandLine.Append(\" \");\n            using (var searcher = new ManagementObjectSearcher(\"SELECT CommandLine FROM Win32_Process WHERE ProcessId = \" + process.Id))\n            {\n                foreach (var @object in searcher.Get())\n                {\n                    commandLine.Append(@object[\"CommandLine\"]);\n                    commandLine.Append(\" \");\n                }\n            }\n\n            return commandLine.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Util/Sockets/LineReader.cs",
    "content": "﻿using System;\nusing System.Text;\n\nnamespace Shadowsocks.Util.Sockets\n{\n    public class LineReader\n    {\n        private readonly WrappedSocket _socket;\n        private readonly Func<string, object, bool> _onLineRead;\n        private readonly Action<Exception, object> _onException;\n        private readonly Action<byte[], int, int, object> _onFinish;\n        private readonly Encoding _encoding;\n        // private readonly string _delimiter;\n        private readonly byte[] _delimiterBytes;\n        private readonly int[] _delimiterSearchCharTable;\n        private readonly int[] _delimiterSearchOffsetTable;\n        private readonly object _state;\n\n        private readonly byte[] _lineBuffer;\n\n        private int _bufferIndex;\n\n        public LineReader(WrappedSocket socket, Func<string, object, bool> onLineRead, Action<Exception, object> onException,\n            Action<byte[], int, int, object> onFinish, Encoding encoding, string delimiter, int maxLineBytes, object state)\n        {\n            if (socket == null)\n            {\n                throw new ArgumentNullException(nameof(socket));\n            }\n            if (onLineRead == null)\n            {\n                throw new ArgumentNullException(nameof(onLineRead));\n            }\n            if (encoding == null)\n            {\n                throw new ArgumentNullException(nameof(encoding));\n            }\n            if (delimiter == null)\n            {\n                throw new ArgumentNullException(nameof(delimiter));\n            }\n\n            _socket = socket;\n            _onLineRead = onLineRead;\n            _onException = onException;\n            _onFinish = onFinish;\n            _encoding = encoding;\n            // _delimiter = delimiter;\n            _state = state;\n\n            // decode delimiter\n            _delimiterBytes = encoding.GetBytes(delimiter);\n\n            if (_delimiterBytes.Length == 0)\n            {\n                throw new ArgumentException(\"Too short!\", nameof(delimiter));\n            }\n\n            if (maxLineBytes < _delimiterBytes.Length)\n            {\n                throw new ArgumentException(\"Too small!\", nameof(maxLineBytes));\n            }\n\n            _delimiterSearchCharTable = MakeCharTable(_delimiterBytes);\n            _delimiterSearchOffsetTable = MakeOffsetTable(_delimiterBytes);\n\n            _lineBuffer = new byte[maxLineBytes];\n\n            // start reading\n            socket.BeginReceive(_lineBuffer, 0, maxLineBytes, 0, ReceiveCallback, 0);\n        }\n\n        private void ReceiveCallback(IAsyncResult ar)\n        {\n            int length = (int)ar.AsyncState;\n            try\n            {\n                var bytesRead = _socket.EndReceive(ar);\n\n                if (bytesRead == 0)\n                {\n                    OnFinish(length);\n                    return;\n                }\n\n                length += bytesRead;\n\n                int i;\n                while ((i = IndexOf(_lineBuffer, _bufferIndex, length, _delimiterBytes, _delimiterSearchOffsetTable,\n                           _delimiterSearchCharTable)) != -1)\n                {\n                    var decodeLen = i - _bufferIndex;\n                    string line = _encoding.GetString(_lineBuffer, _bufferIndex, decodeLen);\n\n                    _bufferIndex = i + _delimiterBytes.Length;\n                    length -= decodeLen;\n                    length -= _delimiterBytes.Length;\n\n                    var stop = _onLineRead(line, _state);\n                    if (stop)\n                    {\n                        OnFinish(length);\n                        return;\n                    }\n                }\n                if (length == _lineBuffer.Length)\n                {\n                    OnException(new IndexOutOfRangeException(\"LineBuffer full! Try increace maxLineBytes!\"));\n                    OnFinish(length);\n\n                    return;\n                }\n\n                if (_bufferIndex > 0)\n                {\n                    Buffer.BlockCopy(_lineBuffer, _bufferIndex, _lineBuffer, 0, length);\n                    _bufferIndex = 0;\n                }\n\n                _socket.BeginReceive(_lineBuffer, length, _lineBuffer.Length - length, 0, ReceiveCallback, length);\n            }\n            catch (Exception ex)\n            {\n                OnException(ex);\n                OnFinish(length);\n            }\n        }\n\n        private void OnException(Exception ex)\n        {\n            _onException?.Invoke(ex, _state);\n        }\n\n        private void OnFinish(int length)\n        {\n            _onFinish?.Invoke(_lineBuffer, _bufferIndex, length, _state);\n        }\n\n        #region Boyer-Moore string search\n\n        public static int IndexOf(byte[] haystack, int index, int length, byte[] needle, int[] offsetTable, int[] charTable)\n        {\n            var end = index + length;\n            for (int i = needle.Length - 1 + index, j; i < end;)\n            {\n                for (j = needle.Length - 1; needle[j] == haystack[i]; --i, --j)\n                {\n                    if (j == 0)\n                    {\n                        return i;\n                    }\n                }\n                // i += needle.length - j; // For naive method\n                i += Math.Max(offsetTable[needle.Length - 1 - j], charTable[haystack[i]]);\n            }\n            return -1;\n        }\n\n        /**\n         * Makes the jump table based on the mismatched character information.\n         */\n        private static int[] MakeCharTable(byte[] needle)\n        {\n            const int ALPHABET_SIZE = 256;\n            int[] table = new int[ALPHABET_SIZE];\n            for (int i = 0; i < table.Length; ++i)\n            {\n                table[i] = needle.Length;\n            }\n            for (int i = 0; i < needle.Length - 1; ++i)\n            {\n                table[needle[i]] = needle.Length - 1 - i;\n            }\n            return table;\n        }\n\n        /**\n         * Makes the jump table based on the scan offset which mismatch occurs.\n         */\n        private static int[] MakeOffsetTable(byte[] needle)\n        {\n            int[] table = new int[needle.Length];\n            int lastPrefixPosition = needle.Length;\n            for (int i = needle.Length - 1; i >= 0; --i)\n            {\n                if (IsPrefix(needle, i + 1))\n                {\n                    lastPrefixPosition = i + 1;\n                }\n                table[needle.Length - 1 - i] = lastPrefixPosition - i + needle.Length - 1;\n            }\n            for (int i = 0; i < needle.Length - 1; ++i)\n            {\n                int slen = SuffixLength(needle, i);\n                table[slen] = needle.Length - 1 - i + slen;\n            }\n            return table;\n        }\n\n        /**\n         * Is needle[p:end] a prefix of needle?\n         */\n        private static bool IsPrefix(byte[] needle, int p)\n        {\n            for (int i = p, j = 0; i < needle.Length; ++i, ++j)\n            {\n                if (needle[i] != needle[j])\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        /**\n         * Returns the maximum length of the substring ends at p and is a suffix.\n         */\n        private static int SuffixLength(byte[] needle, int p)\n        {\n            int len = 0;\n            for (int i = p, j = needle.Length - 1;\n                     i >= 0 && needle[i] == needle[j]; --i, --j)\n            {\n                len += 1;\n            }\n            return len;\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Util/Sockets/SocketUtil.cs",
    "content": "﻿using System;\nusing System.Net;\nusing System.Net.Sockets;\n\nnamespace Shadowsocks.Util.Sockets\n{\n    public static class SocketUtil\n    {\n        private class DnsEndPoint2 : DnsEndPoint\n        {\n            public DnsEndPoint2(string host, int port) : base(host, port)\n            {\n            }\n\n            public DnsEndPoint2(string host, int port, AddressFamily addressFamily) : base(host, port, addressFamily)\n            {\n            }\n\n            public override string ToString()\n            {\n                return this.Host + \":\" + this.Port;\n            }\n        }\n\n        public static EndPoint GetEndPoint(string host, int port)\n        {\n            IPAddress ipAddress;\n            bool parsed = IPAddress.TryParse(host, out ipAddress);\n            if (parsed)\n            {\n                return new IPEndPoint(ipAddress, port);\n            }\n\n            // maybe is a domain name\n            return new DnsEndPoint2(host, port);\n        }\n\n\n        public static void FullClose(this System.Net.Sockets.Socket s)\n        {\n            try\n            {\n                s.Shutdown(SocketShutdown.Both);\n            }\n            catch (Exception)\n            {\n            }\n            try\n            {\n                s.Disconnect(false);\n            }\n            catch (Exception)\n            {\n            }\n            try\n            {\n                s.Close();\n            }\n            catch (Exception)\n            {\n            }\n        }\n        \n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Util/Sockets/WrappedSocket.cs",
    "content": "﻿using System;\r\nusing System.Net;\r\nusing System.Net.Sockets;\r\nusing System.Threading;\r\n\r\nnamespace Shadowsocks.Util.Sockets\r\n{\r\n    /*\r\n     * A wrapped socket class which support both ipv4 and ipv6 based on the\r\n     * connected remote endpoint.\r\n     * \r\n     * If the server address is host name, then it may have both ipv4 and ipv6 address\r\n     * after resolving. The main idea is we don't want to resolve and choose the address\r\n     * by ourself. Instead, Socket.ConnectAsync() do handle this thing internally by trying\r\n     * each address and returning an established socket connection.\r\n     */\r\n    public class WrappedSocket\r\n    {\r\n        public EndPoint LocalEndPoint => _activeSocket?.LocalEndPoint;\r\n\r\n        // Only used during connection and close, so it won't cost too much.\r\n        private SpinLock _socketSyncLock = new SpinLock();\r\n\r\n        private bool _disposed;\r\n        private bool Connected => _activeSocket != null;\r\n        private Socket _activeSocket;\r\n\r\n\r\n        public void BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                throw new ObjectDisposedException(GetType().FullName);\r\n            }\r\n            if (Connected)\r\n            {\r\n                throw new SocketException((int) SocketError.IsConnected);\r\n            }\r\n\r\n            var arg = new SocketAsyncEventArgs();\r\n            arg.RemoteEndPoint = remoteEP;\r\n            arg.Completed += OnTcpConnectCompleted;\r\n            arg.UserToken = new TcpUserToken(callback, state);\r\n\r\n            if(!Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, arg))\r\n            {\r\n                OnTcpConnectCompleted(this, arg);\r\n            }\r\n        }\r\n\r\n        private class FakeAsyncResult : IAsyncResult\r\n        {\r\n            public bool IsCompleted { get; } = true;\r\n            public WaitHandle AsyncWaitHandle { get; } = null;\r\n            public object AsyncState { get; set; }\r\n            public bool CompletedSynchronously { get; } = true;\r\n            public Exception InternalException { get; set; } = null;\r\n        }\r\n\r\n        private class TcpUserToken\r\n        {\r\n            public AsyncCallback Callback { get; }\r\n            public object AsyncState { get; }\r\n\r\n            public TcpUserToken(AsyncCallback callback, object state)\r\n            {\r\n                Callback = callback;\r\n                AsyncState = state;\r\n            }\r\n        }\r\n\r\n        private void OnTcpConnectCompleted(object sender, SocketAsyncEventArgs args)\r\n        {\r\n            using (args)\r\n            {\r\n                args.Completed -= OnTcpConnectCompleted;\r\n                var token = (TcpUserToken) args.UserToken;\r\n\r\n                if (args.SocketError != SocketError.Success)\r\n                {\r\n                    var ex = args.ConnectByNameError ?? new SocketException((int) args.SocketError);\r\n\r\n                    var r = new FakeAsyncResult()\r\n                    {\r\n                        AsyncState = token.AsyncState,\r\n                        InternalException = ex\r\n                    };\r\n\r\n                    token.Callback(r);\r\n                }\r\n                else\r\n                {\r\n                    var lockTaken = false;\r\n                    if (!_socketSyncLock.IsHeldByCurrentThread)\r\n                    {\r\n                        _socketSyncLock.TryEnter(ref lockTaken);\r\n                    }\r\n                    try\r\n                    {\r\n                        if (Connected)\r\n                        {\r\n                            args.ConnectSocket.FullClose();\r\n                        }\r\n                        else\r\n                        {\r\n                            _activeSocket = args.ConnectSocket;\r\n                            if (_disposed)\r\n                            {\r\n                                _activeSocket.FullClose();\r\n                            }\r\n\r\n                            var r = new FakeAsyncResult()\r\n                            {\r\n                                AsyncState = token.AsyncState\r\n                            };\r\n                            token.Callback(r);\r\n                        }\r\n                    }\r\n                    finally\r\n                    {\r\n                        if (lockTaken)\r\n                        {\r\n                            _socketSyncLock.Exit();\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        public void EndConnect(IAsyncResult asyncResult)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                throw new ObjectDisposedException(GetType().FullName);\r\n            }\r\n\r\n            var r = asyncResult as FakeAsyncResult;\r\n            if (r == null)\r\n            {\r\n                throw new ArgumentException(\"Invalid asyncResult.\", nameof(asyncResult));\r\n            }\r\n\r\n            if (r.InternalException != null)\r\n            {\r\n                throw r.InternalException;\r\n            }\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            if (_disposed)\r\n            {\r\n                return;\r\n            }\r\n            var lockTaken = false;\r\n            if (!_socketSyncLock.IsHeldByCurrentThread)\r\n            {\r\n                _socketSyncLock.TryEnter(ref lockTaken);\r\n            }\r\n            try\r\n            {\r\n                _disposed = true;\r\n                _activeSocket?.FullClose();\r\n            }\r\n            finally\r\n            {\r\n                if (lockTaken)\r\n                {\r\n                    _socketSyncLock.Exit();\r\n                }\r\n            }\r\n\r\n        }\r\n\r\n        public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags,\r\n            AsyncCallback callback,\r\n            object state)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                throw new ObjectDisposedException(GetType().FullName);\r\n            }\r\n            if (!Connected)\r\n            {\r\n                throw new SocketException((int) SocketError.NotConnected);\r\n            }\r\n\r\n            return _activeSocket.BeginSend(buffer, offset, size, socketFlags, callback, state);\r\n        }\r\n\r\n        public int EndSend(IAsyncResult asyncResult)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                throw new ObjectDisposedException(GetType().FullName);\r\n            }\r\n            if (!Connected)\r\n            {\r\n                throw new SocketException((int) SocketError.NotConnected);\r\n            }\r\n\r\n            return _activeSocket.EndSend(asyncResult);\r\n        }\r\n\r\n        public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags,\r\n            AsyncCallback callback,\r\n            object state)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                throw new ObjectDisposedException(GetType().FullName);\r\n            }\r\n            if (!Connected)\r\n            {\r\n                throw new SocketException((int) SocketError.NotConnected);\r\n            }\r\n\r\n            return _activeSocket.BeginReceive(buffer, offset, size, socketFlags, callback, state);\r\n        }\r\n\r\n        public int EndReceive(IAsyncResult asyncResult)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                throw new ObjectDisposedException(GetType().FullName);\r\n            }\r\n            if (!Connected)\r\n            {\r\n                throw new SocketException((int) SocketError.NotConnected);\r\n            }\r\n\r\n            return _activeSocket.EndReceive(asyncResult);\r\n        }\r\n\r\n        public void Shutdown(SocketShutdown how)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                throw new ObjectDisposedException(GetType().FullName);\r\n            }\r\n            if (!Connected)\r\n            {\r\n                return;\r\n            }\r\n\r\n            _activeSocket.Shutdown(how);\r\n        }\r\n\r\n        public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)\r\n        {\r\n            SetSocketOption(optionLevel, optionName, optionValue ? 1 : 0);\r\n        }\r\n\r\n        public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                throw new ObjectDisposedException(GetType().FullName);\r\n            }\r\n            if (!Connected)\r\n            {\r\n                throw new SocketException((int)SocketError.NotConnected);\r\n            }\r\n\r\n            _activeSocket.SetSocketOption(optionLevel, optionName, optionValue);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Util/SystemProxy/ProxyException.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.Serialization;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Shadowsocks.Util.SystemProxy\n{\n    enum ProxyExceptionType\n    {\n        Unspecific,\n        FailToRun,\n        QueryReturnEmpty,\n        SysproxyExitError,\n        QueryReturnMalformed\n    }\n\n    class ProxyException : Exception\n    {\n        // provide more specific information about exception\n        public ProxyExceptionType Type { get; }\n\n        public ProxyException()\n        {\n        }\n\n        public ProxyException(string message) : base(message)\n        {\n        }\n\n        public ProxyException(string message, Exception innerException) : base(message, innerException)\n        {\n        }\n\n        protected ProxyException(SerializationInfo info, StreamingContext context) : base(info, context)\n        {\n        }\n        public ProxyException(ProxyExceptionType type)\n        {\n            this.Type = type;\n        }\n\n        public ProxyException(ProxyExceptionType type, string message) : base(message)\n        {\n            this.Type = type;\n        }\n\n        public ProxyException(ProxyExceptionType type, string message, Exception innerException) : base(message, innerException)\n        {\n            this.Type = type;\n        }\n\n        protected ProxyException(ProxyExceptionType type, SerializationInfo info, StreamingContext context) : base(info, context)\n        {\n            this.Type = type;\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Util/SystemProxy/Sysproxy.cs",
    "content": "﻿using Newtonsoft.Json;\r\nusing NLog;\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Properties;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading;\r\n\r\nnamespace Shadowsocks.Util.SystemProxy\r\n{\r\n    public static class Sysproxy\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private const string _userWininetConfigFile = \"user-wininet.json\";\r\n\r\n        private readonly static string[] _lanIP = {\r\n            \"<local>\",\r\n            \"localhost\",\r\n            \"127.*\",\r\n            \"10.*\",\r\n            \"172.16.*\",\r\n            \"172.17.*\",\r\n            \"172.18.*\",\r\n            \"172.19.*\",\r\n            \"172.20.*\",\r\n            \"172.21.*\",\r\n            \"172.22.*\",\r\n            \"172.23.*\",\r\n            \"172.24.*\",\r\n            \"172.25.*\",\r\n            \"172.26.*\",\r\n            \"172.27.*\",\r\n            \"172.28.*\",\r\n            \"172.29.*\",\r\n            \"172.30.*\",\r\n            \"172.31.*\",\r\n            \"192.168.*\"\r\n            };\r\n\r\n\r\n        private static string _queryStr;\r\n\r\n        // In general, this won't change\r\n        // format:\r\n        //  <flags><CR-LF>\r\n        //  <proxy-server><CR-LF>\r\n        //  <bypass-list><CR-LF>\r\n        //  <pac-url>\r\n        private static SysproxyConfig _userSettings = null;\r\n\r\n        enum RET_ERRORS : int\r\n        {\r\n            RET_NO_ERROR = 0,\r\n            INVALID_FORMAT = 1,\r\n            NO_PERMISSION = 2,\r\n            SYSCALL_FAILED = 3,\r\n            NO_MEMORY = 4,\r\n            INVAILD_OPTION_COUNT = 5,\r\n        };\r\n\r\n        static Sysproxy()\r\n        {\r\n            try\r\n            {\r\n                FileManager.UncompressFile(Utils.GetTempPath(\"sysproxy.exe\"),\r\n                    Environment.Is64BitOperatingSystem ? Resources.sysproxy64_exe : Resources.sysproxy_exe);\r\n            }\r\n            catch (IOException e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n        }\r\n\r\n        public static void SetIEProxy(bool enable, bool global, string proxyServer, string pacURL)\r\n        {\r\n            Read();\r\n\r\n            if (!_userSettings.UserSettingsRecorded)\r\n            {\r\n                // record user settings\r\n                ExecSysproxy(\"query\");\r\n                ParseQueryStr(_queryStr);\r\n            }\r\n\r\n            string arguments;\r\n            if (enable)\r\n            {\r\n                string customBypassString = _userSettings.BypassList ?? \"\";\r\n                List<string> customBypassList = new List<string>(customBypassString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));\r\n                customBypassList.AddRange(_lanIP);\r\n                string[] realBypassList = customBypassList.Distinct().ToArray();\r\n                string realBypassString = string.Join(\";\", realBypassList);\r\n\r\n                arguments = global\r\n                    ? $\"global {proxyServer} {realBypassString}\"\r\n                    : $\"pac {pacURL}\";\r\n            }\r\n            else\r\n            {\r\n                // restore user settings\r\n                var flags = _userSettings.Flags;\r\n                var proxy_server = _userSettings.ProxyServer ?? \"-\";\r\n                var bypass_list = _userSettings.BypassList ?? \"-\";\r\n                var pac_url = _userSettings.PacUrl ?? \"-\";\r\n                arguments = $\"set {flags} {proxy_server} {bypass_list} {pac_url}\";\r\n\r\n                // have to get new settings\r\n                _userSettings.UserSettingsRecorded = false;\r\n            }\r\n\r\n            Save();\r\n            ExecSysproxy(arguments);\r\n        }\r\n\r\n        // set system proxy to 1 (null) (null) (null)\r\n        public static bool ResetIEProxy()\r\n        {\r\n            try\r\n            {\r\n                // clear user-wininet.json\r\n                _userSettings = new SysproxyConfig();\r\n                Save();\r\n                // clear system setting\r\n                ExecSysproxy(\"set 1 - - -\");\r\n            }\r\n            catch (Exception)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        private static void ExecSysproxy(string arguments)\r\n        {\r\n            // using event to avoid hanging when redirect standard output/error\r\n            // ref: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why\r\n            // and http://blog.csdn.net/zhangweixing0/article/details/7356841\r\n            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))\r\n            using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))\r\n            {\r\n                using (var process = new Process())\r\n                {\r\n                    // Configure the process using the StartInfo properties.\r\n                    process.StartInfo.FileName = Utils.GetTempPath(\"sysproxy.exe\");\r\n                    process.StartInfo.Arguments = arguments;\r\n                    process.StartInfo.WorkingDirectory = Utils.GetTempPath();\r\n                    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\r\n                    process.StartInfo.UseShellExecute = false;\r\n                    process.StartInfo.RedirectStandardError = true;\r\n                    process.StartInfo.RedirectStandardOutput = true;\r\n\r\n                    // Need to provide encoding info, or output/error strings we got will be wrong.\r\n                    process.StartInfo.StandardOutputEncoding = Encoding.Unicode;\r\n                    process.StartInfo.StandardErrorEncoding = Encoding.Unicode;\r\n\r\n                    process.StartInfo.CreateNoWindow = true;\r\n\r\n                    StringBuilder output = new StringBuilder();\r\n                    StringBuilder error = new StringBuilder();\r\n\r\n                    process.OutputDataReceived += (sender, e) =>\r\n                    {\r\n                        if (e.Data == null)\r\n                        {\r\n                            outputWaitHandle.Set();\r\n                        }\r\n                        else\r\n                        {\r\n                            output.AppendLine(e.Data);\r\n                        }\r\n                    };\r\n                    process.ErrorDataReceived += (sender, e) =>\r\n                    {\r\n                        if (e.Data == null)\r\n                        {\r\n                            errorWaitHandle.Set();\r\n                        }\r\n                        else\r\n                        {\r\n                            error.AppendLine(e.Data);\r\n                        }\r\n                    };\r\n                    try\r\n                    {\r\n                        process.Start();\r\n\r\n                        process.BeginErrorReadLine();\r\n                        process.BeginOutputReadLine();\r\n\r\n                        process.WaitForExit();\r\n                    }\r\n                    catch (System.ComponentModel.Win32Exception e)\r\n                    {\r\n                        // log the arguments\r\n                        throw new ProxyException(ProxyExceptionType.FailToRun, process.StartInfo.Arguments, e);\r\n                    }\r\n                    var stderr = error.ToString();\r\n                    var stdout = output.ToString();\r\n\r\n                    var exitCode = process.ExitCode;\r\n                    if (exitCode != (int)RET_ERRORS.RET_NO_ERROR)\r\n                    {\r\n                        throw new ProxyException(ProxyExceptionType.SysproxyExitError, stderr);\r\n                    }\r\n\r\n                    if (arguments == \"query\")\r\n                    {\r\n                        if (string.IsNullOrWhiteSpace(stdout))\r\n                        {\r\n                            // we cannot get user settings\r\n                            throw new ProxyException(ProxyExceptionType.QueryReturnEmpty);\r\n                        }\r\n                        _queryStr = stdout;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        private static void Save()\r\n        {\r\n            try\r\n            {\r\n                using (StreamWriter sw = new StreamWriter(File.Open(Utils.GetTempPath(_userWininetConfigFile), FileMode.Create)))\r\n                {\r\n                    string jsonString = JsonConvert.SerializeObject(_userSettings, Formatting.Indented);\r\n                    sw.Write(jsonString);\r\n                    sw.Flush();\r\n                }\r\n            }\r\n            catch (IOException e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n            }\r\n        }\r\n\r\n        private static void Read()\r\n        {\r\n            try\r\n            {\r\n                string configContent = File.ReadAllText(Utils.GetTempPath(_userWininetConfigFile));\r\n                _userSettings = JsonConvert.DeserializeObject<SysproxyConfig>(configContent);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                // Suppress all exceptions. finally block will initialize new user config settings.\r\n            }\r\n            finally\r\n            {\r\n                if (_userSettings == null) _userSettings = new SysproxyConfig();\r\n            }\r\n        }\r\n\r\n        private static void ParseQueryStr(string str)\r\n        {\r\n            string[] userSettingsArr = str.Split(new string[] { \"\\r\\n\" }, StringSplitOptions.RemoveEmptyEntries);\r\n\r\n            // sometimes sysproxy output in utf16le instead of ascii\r\n            // manually translate it\r\n            if (userSettingsArr.Length != 4)\r\n            {\r\n                byte[] strByte = Encoding.ASCII.GetBytes(str);\r\n                str = Encoding.Unicode.GetString(strByte);\r\n                userSettingsArr = str.Split(new string[] { \"\\r\\n\" }, StringSplitOptions.RemoveEmptyEntries);\r\n                // still fail, throw exception with string hexdump\r\n                if (userSettingsArr.Length != 4)\r\n                {\r\n                    throw new ProxyException(ProxyExceptionType.QueryReturnMalformed, BitConverter.ToString(strByte));\r\n                }\r\n            }\r\n\r\n            _userSettings.Flags = userSettingsArr[0];\r\n\r\n            // handle output from WinINET\r\n            if (userSettingsArr[1] == \"(null)\") _userSettings.ProxyServer = null;\r\n            else _userSettings.ProxyServer = userSettingsArr[1];\r\n            if (userSettingsArr[2] == \"(null)\") _userSettings.BypassList = null;\r\n            else _userSettings.BypassList = userSettingsArr[2];\r\n            if (userSettingsArr[3] == \"(null)\") _userSettings.PacUrl = null;\r\n            else _userSettings.PacUrl = userSettingsArr[3];\r\n\r\n            _userSettings.UserSettingsRecorded = true;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Util/Util.cs",
    "content": "﻿using NLog;\r\nusing System;\r\nusing System.Diagnostics;\r\nusing System.IO;\r\nusing System.IO.Compression;\r\nusing System.Runtime.InteropServices;\r\nusing System.Windows.Forms;\r\nusing Microsoft.Win32;\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Model;\r\nusing System.Drawing;\r\nusing ZXing;\r\nusing ZXing.QrCode;\r\nusing ZXing.Common;\r\n\r\nnamespace Shadowsocks.Util\r\n{\r\n    public struct BandwidthScaleInfo\r\n    {\r\n        public float value;\r\n        public string unitName;\r\n        public long unit;\r\n\r\n        public BandwidthScaleInfo(float value, string unitName, long unit)\r\n        {\r\n            this.value = value;\r\n            this.unitName = unitName;\r\n            this.unit = unit;\r\n        }\r\n    }\r\n\r\n    public static class Utils\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private static string _tempPath = null;\r\n\r\n        // return path to store temporary files\r\n        public static string GetTempPath()\r\n        {\r\n            if (_tempPath == null)\r\n            {\r\n                bool isPortableMode = Configuration.Load().portableMode;\r\n                try\r\n                {\r\n                    if (isPortableMode)\r\n                    {\r\n                        _tempPath = Directory.CreateDirectory(\"ss_win_temp\").FullName;\r\n                        // don't use \"/\", it will fail when we call explorer /select xxx/ss_win_temp\\xxx.log\r\n                    }\r\n                    else\r\n                    {\r\n                        _tempPath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), @\"Shadowsocks\\ss_win_temp_\" + Program.ExecutablePath.GetHashCode())).FullName;\r\n                    }\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    logger.Error(e);\r\n                    throw;\r\n                }\r\n            }\r\n            return _tempPath;\r\n        }\r\n\r\n        public enum WindowsThemeMode { Dark, Light }\r\n\r\n        // Support on Windows 10 1903+\r\n        public static WindowsThemeMode GetWindows10SystemThemeSetting()\r\n        {\r\n            WindowsThemeMode themeMode = WindowsThemeMode.Dark;\r\n            try\r\n            {\r\n                RegistryKey reg_ThemesPersonalize = Registry.CurrentUser.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\", false);\r\n                if (reg_ThemesPersonalize.GetValue(\"SystemUsesLightTheme\") != null)\r\n                {\r\n                    if ((int)(reg_ThemesPersonalize.GetValue(\"SystemUsesLightTheme\")) == 0) // 0:dark mode, 1:light mode\r\n                        themeMode = WindowsThemeMode.Dark;\r\n                    else\r\n                        themeMode = WindowsThemeMode.Light;\r\n                }\r\n                else\r\n                {\r\n                    throw new Exception(\"Reg-Value SystemUsesLightTheme not found.\");\r\n                }\r\n            }\r\n            catch\r\n            {\r\n\r\n                logger.Debug(\r\n                        $\"Cannot get Windows 10 system theme mode, return default value 0 (dark mode).\");\r\n\r\n            }\r\n            return themeMode;\r\n        }\r\n\r\n        // return a full path with filename combined which pointed to the temporary directory\r\n        public static string GetTempPath(string filename)\r\n        {\r\n            return Path.Combine(GetTempPath(), filename);\r\n        }\r\n\r\n        public static string UnGzip(byte[] buf)\r\n        {\r\n            byte[] buffer = new byte[1024];\r\n            int n;\r\n            using (MemoryStream sb = new MemoryStream())\r\n            {\r\n                using (GZipStream input = new GZipStream(new MemoryStream(buf),\r\n                                                         CompressionMode.Decompress,\r\n                                                         false))\r\n                {\r\n                    while ((n = input.Read(buffer, 0, buffer.Length)) > 0)\r\n                    {\r\n                        sb.Write(buffer, 0, n);\r\n                    }\r\n                }\r\n                return System.Text.Encoding.UTF8.GetString(sb.ToArray());\r\n            }\r\n        }\r\n\r\n        public static string FormatBandwidth(long n)\r\n        {\r\n            var result = GetBandwidthScale(n);\r\n            return $\"{result.value:0.##}{result.unitName}\";\r\n        }\r\n\r\n        public static string FormatBytes(long bytes)\r\n        {\r\n            const long K = 1024L;\r\n            const long M = K * 1024L;\r\n            const long G = M * 1024L;\r\n            const long T = G * 1024L;\r\n            const long P = T * 1024L;\r\n            const long E = P * 1024L;\r\n\r\n            if (bytes >= P * 990)\r\n                return (bytes / (double)E).ToString(\"F5\") + \"EiB\";\r\n            if (bytes >= T * 990)\r\n                return (bytes / (double)P).ToString(\"F5\") + \"PiB\";\r\n            if (bytes >= G * 990)\r\n                return (bytes / (double)T).ToString(\"F5\") + \"TiB\";\r\n            if (bytes >= M * 990)\r\n            {\r\n                return (bytes / (double)G).ToString(\"F4\") + \"GiB\";\r\n            }\r\n            if (bytes >= M * 100)\r\n            {\r\n                return (bytes / (double)M).ToString(\"F1\") + \"MiB\";\r\n            }\r\n            if (bytes >= M * 10)\r\n            {\r\n                return (bytes / (double)M).ToString(\"F2\") + \"MiB\";\r\n            }\r\n            if (bytes >= K * 990)\r\n            {\r\n                return (bytes / (double)M).ToString(\"F3\") + \"MiB\";\r\n            }\r\n            if (bytes > K * 2)\r\n            {\r\n                return (bytes / (double)K).ToString(\"F1\") + \"KiB\";\r\n            }\r\n            return bytes.ToString() + \"B\";\r\n        }\r\n\r\n        /// <summary>\r\n        /// Return scaled bandwidth\r\n        /// </summary>\r\n        /// <param name=\"n\">Raw bandwidth</param>\r\n        /// <returns>\r\n        /// The BandwidthScaleInfo struct\r\n        /// </returns>\r\n        public static BandwidthScaleInfo GetBandwidthScale(long n)\r\n        {\r\n            long scale = 1;\r\n            float f = n;\r\n            string unit = \"B\";\r\n            if (f > 1024)\r\n            {\r\n                f = f / 1024;\r\n                scale <<= 10;\r\n                unit = \"KiB\";\r\n            }\r\n            if (f > 1024)\r\n            {\r\n                f = f / 1024;\r\n                scale <<= 10;\r\n                unit = \"MiB\";\r\n            }\r\n            if (f > 1024)\r\n            {\r\n                f = f / 1024;\r\n                scale <<= 10;\r\n                unit = \"GiB\";\r\n            }\r\n            if (f > 1024)\r\n            {\r\n                f = f / 1024;\r\n                scale <<= 10;\r\n                unit = \"TiB\";\r\n            }\r\n            return new BandwidthScaleInfo(f, unit, scale);\r\n        }\r\n\r\n        public static RegistryKey OpenRegKey(string name, bool writable, RegistryHive hive = RegistryHive.CurrentUser)\r\n        {\r\n            // we are building x86 binary for both x86 and x64, which will\r\n            // cause problem when opening registry key\r\n            // detect operating system instead of CPU\r\n            if (string.IsNullOrEmpty(name)) throw new ArgumentException(nameof(name));\r\n            try\r\n            {\r\n                RegistryKey userKey = RegistryKey.OpenBaseKey(hive,\r\n                        Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32)\r\n                    .OpenSubKey(name, writable);\r\n                return userKey;\r\n            }\r\n            catch (ArgumentException ae)\r\n            {\r\n                MessageBox.Show(\"OpenRegKey: \" + ae.ToString());\r\n                return null;\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.LogUsefulException(e);\r\n                return null;\r\n            }\r\n        }\r\n\r\n        public static bool IsWinVistaOrHigher()\r\n        {\r\n            return Environment.OSVersion.Version.Major > 5;\r\n        }\r\n\r\n        public static string ScanQRCodeFromScreen()\r\n        {\r\n            foreach (Screen screen in Screen.AllScreens)\r\n            {\r\n                using (Bitmap fullImage = new Bitmap(screen.Bounds.Width,\r\n                                                screen.Bounds.Height))\r\n                {\r\n                    using (Graphics g = Graphics.FromImage(fullImage))\r\n                    {\r\n                        g.CopyFromScreen(screen.Bounds.X,\r\n                                         screen.Bounds.Y,\r\n                                         0, 0,\r\n                                         fullImage.Size,\r\n                                         CopyPixelOperation.SourceCopy);\r\n                    }\r\n                    int maxTry = 10;\r\n                    for (int i = 0; i < maxTry; i++)\r\n                    {\r\n                        int marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry);\r\n                        int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry);\r\n                        Rectangle cropRect = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2);\r\n                        Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);\r\n\r\n                        double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width;\r\n                        using (Graphics g = Graphics.FromImage(target))\r\n                        {\r\n                            g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),\r\n                                            cropRect,\r\n                                            GraphicsUnit.Pixel);\r\n                        }\r\n                        var source = new BitmapLuminanceSource(target);\r\n                        var bitmap = new BinaryBitmap(new HybridBinarizer(source));\r\n                        QRCodeReader reader = new QRCodeReader();\r\n                        var result = reader.decode(bitmap);\r\n                        if (result != null)\r\n                            return result.Text;\r\n                    }\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n\r\n        // See: https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx\r\n        public static bool IsSupportedRuntimeVersion()\r\n        {\r\n            /*\r\n             * +-----------------------------------------------------------------+----------------------------+\r\n             * | Version                                                         | Value of the Release DWORD |\r\n             * +-----------------------------------------------------------------+----------------------------+\r\n             * | .NET Framework 4.6.2 installed on Windows 10 Anniversary Update | 394802                     |\r\n             * | .NET Framework 4.6.2 installed on all other Windows OS versions | 394806                     |\r\n             * +-----------------------------------------------------------------+----------------------------+\r\n             */\r\n            const int minSupportedRelease = 394802;\r\n\r\n            const string subkey = @\"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\\";\r\n            using (var ndpKey = OpenRegKey(subkey, false, RegistryHive.LocalMachine))\r\n            {\r\n                if (ndpKey?.GetValue(\"Release\") != null)\r\n                {\r\n                    var releaseKey = (int)ndpKey.GetValue(\"Release\");\r\n\r\n                    if (releaseKey >= minSupportedRelease)\r\n                    {\r\n                        return true;\r\n                    }\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/Util/ViewUtils.cs",
    "content": "﻿using Shadowsocks.Controller;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Drawing;\r\nusing System.Drawing.Drawing2D;\r\nusing System.Drawing.Imaging;\r\nusing System.Linq;\r\nusing System.Reflection;\r\nusing System.Windows.Forms;\r\n\r\nnamespace Shadowsocks.Util\r\n{\r\n    public static class ViewUtils\r\n    {\r\n        public static IEnumerable<TControl> GetChildControls<TControl>(this Control control) where TControl : Control\r\n        {\r\n            if (control.Controls.Count == 0)\r\n            {\r\n                return Enumerable.Empty<TControl>();\r\n            }\r\n            var children = control.Controls.OfType<TControl>().ToList();\r\n            return children.SelectMany(GetChildControls<TControl>).Concat(children);\r\n        }\r\n\r\n        public static IEnumerable<MenuItem> GetMenuItems(Menu m)\r\n        {\r\n            if (m?.MenuItems == null || m.MenuItems.Count == 0) return Enumerable.Empty<MenuItem>();\r\n            var children = new List<MenuItem>();\r\n            foreach (var item in m.MenuItems)\r\n            {\r\n                children.Add((MenuItem)item);\r\n            }\r\n            return children.SelectMany(GetMenuItems).Concat(children);\r\n        }\r\n\r\n        // Workaround NotifyIcon's 63 chars limit\r\n        // https://stackoverflow.com/questions/579665/how-can-i-show-a-systray-tooltip-longer-than-63-chars\r\n        public static void SetNotifyIconText(NotifyIcon ni, string text)\r\n        {\r\n            if (text.Length >= 128)\r\n                throw new ArgumentOutOfRangeException(\"Text limited to 127 characters\");\r\n            Type t = typeof(NotifyIcon);\r\n            BindingFlags hidden = BindingFlags.NonPublic | BindingFlags.Instance;\r\n            t.GetField(\"text\", hidden).SetValue(ni, text);\r\n            if ((bool)t.GetField(\"added\", hidden).GetValue(ni))\r\n                t.GetMethod(\"UpdateIcon\", hidden).Invoke(ni, new object[] { true });\r\n        }\r\n\r\n        public static Bitmap AddBitmapOverlay(Bitmap original, params Bitmap[] overlays)\r\n        {\r\n            Bitmap bitmap = new Bitmap(original.Width, original.Height, PixelFormat.Format64bppArgb);\r\n            Graphics canvas = Graphics.FromImage(bitmap);\r\n            canvas.DrawImage(original, new Point(0, 0));\r\n            foreach (Bitmap overlay in overlays)\r\n            {\r\n                canvas.DrawImage(new Bitmap(overlay, original.Size), new Point(0, 0));\r\n            }\r\n            canvas.Save();\r\n            return bitmap;\r\n        }\r\n\r\n        public static Bitmap ChangeBitmapColor(Bitmap original, Color colorMask)\r\n        {\r\n            Bitmap newBitmap = new Bitmap(original);\r\n\r\n            for (int x = 0; x < newBitmap.Width; x++)\r\n            {\r\n                for (int y = 0; y < newBitmap.Height; y++)\r\n                {\r\n                    Color color = original.GetPixel(x, y);\r\n                    if (color.A != 0)\r\n                    {\r\n                        int red = color.R * colorMask.R / 255;\r\n                        int green = color.G * colorMask.G / 255;\r\n                        int blue = color.B * colorMask.B / 255;\r\n                        int alpha = color.A * colorMask.A / 255;\r\n                        newBitmap.SetPixel(x, y, Color.FromArgb(alpha, red, green, blue));\r\n                    }\r\n                    else\r\n                    {\r\n                        newBitmap.SetPixel(x, y, color);\r\n                    }\r\n                }\r\n            }\r\n            return newBitmap;\r\n        }\r\n\r\n        public static Bitmap ResizeBitmap(Bitmap original, int width, int height)\r\n        {\r\n            Bitmap newBitmap = new Bitmap(width, height);\r\n            using (Graphics g = Graphics.FromImage(newBitmap))\r\n            {\r\n                g.SmoothingMode = SmoothingMode.HighQuality;\r\n                g.InterpolationMode = InterpolationMode.HighQualityBicubic;\r\n                g.PixelOffsetMode = PixelOffsetMode.HighQuality;\r\n                g.CompositingQuality = CompositingQuality.HighQuality;\r\n                g.DrawImage(original, new Rectangle(0, 0, width, height));\r\n            }\r\n            return newBitmap;\r\n        }\r\n\r\n        public static int GetScreenDpi()\r\n        {\r\n            Graphics graphics = Graphics.FromHwnd(IntPtr.Zero);\r\n            int dpi = (int)graphics.DpiX;\r\n            graphics.Dispose();\r\n            return dpi;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/View/ConfigForm.Designer.cs",
    "content": "﻿namespace Shadowsocks.View\r\n{\r\n    partial class ConfigForm\r\n    {\r\n        /// <summary>\r\n        /// Required designer variable.\r\n        /// </summary>\r\n        private System.ComponentModel.IContainer components = null;\r\n\r\n        /// <summary>\r\n        /// Clean up any resources being used.\r\n        /// </summary>\r\n        /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\r\n        protected override void Dispose(bool disposing)\r\n        {\r\n            if (disposing && (components != null))\r\n            {\r\n                components.Dispose();\r\n            }\r\n            base.Dispose(disposing);\r\n        }\r\n\r\n        #region Windows Form Designer generated code\r\n\r\n        /// <summary>\r\n        /// Required method for Designer support - do not modify\r\n        /// the contents of this method with the code editor.\r\n        /// </summary>\r\n        private void InitializeComponent()\r\n        {\r\n            this.components = new System.ComponentModel.Container();\r\n            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();\r\n            this.PluginOptionsLabel = new System.Windows.Forms.Label();\r\n            this.PluginTextBox = new System.Windows.Forms.TextBox();\r\n            this.RemarksTextBox = new System.Windows.Forms.TextBox();\r\n            this.IPLabel = new System.Windows.Forms.Label();\r\n            this.ServerPortLabel = new System.Windows.Forms.Label();\r\n            this.PasswordLabel = new System.Windows.Forms.Label();\r\n            this.IPTextBox = new System.Windows.Forms.TextBox();\r\n            this.ServerPortTextBox = new System.Windows.Forms.TextBox();\r\n            this.PasswordTextBox = new System.Windows.Forms.TextBox();\r\n            this.EncryptionLabel = new System.Windows.Forms.Label();\r\n            this.EncryptionSelect = new System.Windows.Forms.ComboBox();\r\n            this.TimeoutLabel = new System.Windows.Forms.Label();\r\n            this.TimeoutTextBox = new System.Windows.Forms.TextBox();\r\n            this.PluginLabel = new System.Windows.Forms.Label();\r\n            this.PluginOptionsTextBox = new System.Windows.Forms.TextBox();\r\n            this.ShowPasswdCheckBox = new System.Windows.Forms.CheckBox();\r\n            this.PluginArgumentsTextBox = new System.Windows.Forms.TextBox();\r\n            this.PluginArgumentsLabel = new System.Windows.Forms.Label();\r\n            this.RemarksLabel = new System.Windows.Forms.Label();\r\n            this.NeedPluginArgCheckBox = new System.Windows.Forms.CheckBox();\r\n            this.panel2 = new System.Windows.Forms.Panel();\r\n            this.OKButton = new System.Windows.Forms.Button();\r\n            this.MyCancelButton = new System.Windows.Forms.Button();\r\n            this.ApplyButton = new System.Windows.Forms.Button();\r\n            this.DeleteButton = new System.Windows.Forms.Button();\r\n            this.AddButton = new System.Windows.Forms.Button();\r\n            this.ServerGroupBox = new System.Windows.Forms.GroupBox();\r\n            this.ServersListBox = new System.Windows.Forms.ListBox();\r\n            this.MoveDownButton = new System.Windows.Forms.Button();\r\n            this.MoveUpButton = new System.Windows.Forms.Button();\r\n            this.ProxyPortTextBox = new System.Windows.Forms.TextBox();\r\n            this.ProxyPortLabel = new System.Windows.Forms.Label();\r\n            this.PortableModeCheckBox = new System.Windows.Forms.CheckBox();\r\n            this.DuplicateButton = new System.Windows.Forms.Button();\r\n            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);\r\n            this.tableLayoutPanel7 = new System.Windows.Forms.TableLayoutPanel();\r\n            this.GroupLabel = new System.Windows.Forms.Label();\r\n            this.GroupTextBox = new System.Windows.Forms.TextBox();\r\n            this.tableLayoutPanel1.SuspendLayout();\r\n            this.ServerGroupBox.SuspendLayout();\r\n            this.tableLayoutPanel7.SuspendLayout();\r\n            this.SuspendLayout();\r\n            // \r\n            // tableLayoutPanel1\r\n            // \r\n            this.tableLayoutPanel1.AutoSize = true;\r\n            this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;\r\n            this.tableLayoutPanel1.ColumnCount = 2;\r\n            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());\r\n            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));\r\n            this.tableLayoutPanel1.Controls.Add(this.PluginOptionsLabel, 0, 6);\r\n            this.tableLayoutPanel1.Controls.Add(this.PluginTextBox, 1, 5);\r\n            this.tableLayoutPanel1.Controls.Add(this.RemarksTextBox, 1, 10);\r\n            this.tableLayoutPanel1.Controls.Add(this.IPLabel, 0, 0);\r\n            this.tableLayoutPanel1.Controls.Add(this.ServerPortLabel, 0, 1);\r\n            this.tableLayoutPanel1.Controls.Add(this.PasswordLabel, 0, 2);\r\n            this.tableLayoutPanel1.Controls.Add(this.IPTextBox, 1, 0);\r\n            this.tableLayoutPanel1.Controls.Add(this.ServerPortTextBox, 1, 1);\r\n            this.tableLayoutPanel1.Controls.Add(this.PasswordTextBox, 1, 2);\r\n            this.tableLayoutPanel1.Controls.Add(this.EncryptionLabel, 0, 4);\r\n            this.tableLayoutPanel1.Controls.Add(this.EncryptionSelect, 1, 4);\r\n            this.tableLayoutPanel1.Controls.Add(this.TimeoutLabel, 0, 11);\r\n            this.tableLayoutPanel1.Controls.Add(this.TimeoutTextBox, 1, 11);\r\n            this.tableLayoutPanel1.Controls.Add(this.PluginLabel, 0, 5);\r\n            this.tableLayoutPanel1.Controls.Add(this.PluginOptionsTextBox, 1, 6);\r\n            this.tableLayoutPanel1.Controls.Add(this.ShowPasswdCheckBox, 1, 3);\r\n            this.tableLayoutPanel1.Controls.Add(this.PluginArgumentsTextBox, 1, 8);\r\n            this.tableLayoutPanel1.Controls.Add(this.PluginArgumentsLabel, 0, 8);\r\n            this.tableLayoutPanel1.Controls.Add(this.NeedPluginArgCheckBox, 1, 7);\r\n            this.tableLayoutPanel1.Controls.Add(this.GroupTextBox, 1, 12);\r\n            this.tableLayoutPanel1.Controls.Add(this.GroupLabel, 0, 12);\r\n            this.tableLayoutPanel1.Controls.Add(this.RemarksLabel, 0, 10);\r\n            this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.tableLayoutPanel1.Location = new System.Drawing.Point(4, 22);\r\n            this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(0);\r\n            this.tableLayoutPanel1.Name = \"tableLayoutPanel1\";\r\n            this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(4);\r\n            this.tableLayoutPanel1.RowCount = 14;\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));\r\n            this.tableLayoutPanel1.Size = new System.Drawing.Size(362, 399);\r\n            this.tableLayoutPanel1.TabIndex = 0;\r\n            // \r\n            // PluginOptionsLabel\r\n            // \r\n            this.PluginOptionsLabel.Anchor = System.Windows.Forms.AnchorStyles.Right;\r\n            this.PluginOptionsLabel.AutoSize = true;\r\n            this.PluginOptionsLabel.Location = new System.Drawing.Point(24, 199);\r\n            this.PluginOptionsLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.PluginOptionsLabel.Name = \"PluginOptionsLabel\";\r\n            this.PluginOptionsLabel.Size = new System.Drawing.Size(119, 15);\r\n            this.PluginOptionsLabel.TabIndex = 6;\r\n            this.PluginOptionsLabel.Text = \"Plugin Options\";\r\n            this.toolTip1.SetToolTip(this.PluginOptionsLabel, \"Environment variables for plugin program\");\r\n            // \r\n            // PluginTextBox\r\n            // \r\n            this.PluginTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.PluginTextBox.Location = new System.Drawing.Point(150, 163);\r\n            this.PluginTextBox.MaxLength = 256;\r\n            this.PluginTextBox.Name = \"PluginTextBox\";\r\n            this.PluginTextBox.Size = new System.Drawing.Size(205, 25);\r\n            this.PluginTextBox.TabIndex = 5;\r\n            this.PluginTextBox.WordWrap = false;\r\n            // \r\n            // RemarksTextBox\r\n            // \r\n            this.RemarksTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.RemarksTextBox.Location = new System.Drawing.Point(150, 283);\r\n            this.RemarksTextBox.MaxLength = 32;\r\n            this.RemarksTextBox.Name = \"RemarksTextBox\";\r\n            this.RemarksTextBox.Size = new System.Drawing.Size(205, 25);\r\n            this.RemarksTextBox.TabIndex = 8;\r\n            this.RemarksTextBox.WordWrap = false;\r\n            // \r\n            // IPLabel\r\n            // \r\n            this.IPLabel.Anchor = System.Windows.Forms.AnchorStyles.Right;\r\n            this.IPLabel.AutoSize = true;\r\n            this.IPLabel.Location = new System.Drawing.Point(64, 12);\r\n            this.IPLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.IPLabel.Name = \"IPLabel\";\r\n            this.IPLabel.Size = new System.Drawing.Size(79, 15);\r\n            this.IPLabel.TabIndex = 0;\r\n            this.IPLabel.Text = \"Server IP\";\r\n            // \r\n            // ServerPortLabel\r\n            // \r\n            this.ServerPortLabel.Anchor = System.Windows.Forms.AnchorStyles.Right;\r\n            this.ServerPortLabel.AutoSize = true;\r\n            this.ServerPortLabel.Location = new System.Drawing.Point(48, 43);\r\n            this.ServerPortLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.ServerPortLabel.Name = \"ServerPortLabel\";\r\n            this.ServerPortLabel.Size = new System.Drawing.Size(95, 15);\r\n            this.ServerPortLabel.TabIndex = 1;\r\n            this.ServerPortLabel.Text = \"Server Port\";\r\n            // \r\n            // PasswordLabel\r\n            // \r\n            this.PasswordLabel.Anchor = System.Windows.Forms.AnchorStyles.Right;\r\n            this.PasswordLabel.AutoSize = true;\r\n            this.PasswordLabel.Location = new System.Drawing.Point(72, 74);\r\n            this.PasswordLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.PasswordLabel.Name = \"PasswordLabel\";\r\n            this.PasswordLabel.Size = new System.Drawing.Size(71, 15);\r\n            this.PasswordLabel.TabIndex = 2;\r\n            this.PasswordLabel.Text = \"Password\";\r\n            this.PasswordLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;\r\n            // \r\n            // IPTextBox\r\n            // \r\n            this.IPTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.IPTextBox.Location = new System.Drawing.Point(150, 7);\r\n            this.IPTextBox.MaxLength = 512;\r\n            this.IPTextBox.Name = \"IPTextBox\";\r\n            this.IPTextBox.Size = new System.Drawing.Size(205, 25);\r\n            this.IPTextBox.TabIndex = 0;\r\n            this.IPTextBox.WordWrap = false;\r\n            // \r\n            // ServerPortTextBox\r\n            // \r\n            this.ServerPortTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.ServerPortTextBox.Location = new System.Drawing.Point(150, 38);\r\n            this.ServerPortTextBox.MaxLength = 10;\r\n            this.ServerPortTextBox.Name = \"ServerPortTextBox\";\r\n            this.ServerPortTextBox.Size = new System.Drawing.Size(205, 25);\r\n            this.ServerPortTextBox.TabIndex = 1;\r\n            this.ServerPortTextBox.WordWrap = false;\r\n            // \r\n            // PasswordTextBox\r\n            // \r\n            this.PasswordTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.PasswordTextBox.Font = new System.Drawing.Font(\"Consolas\", 9F);\r\n            this.PasswordTextBox.Location = new System.Drawing.Point(150, 69);\r\n            this.PasswordTextBox.MaxLength = 256;\r\n            this.PasswordTextBox.Name = \"PasswordTextBox\";\r\n            this.PasswordTextBox.Size = new System.Drawing.Size(205, 25);\r\n            this.PasswordTextBox.TabIndex = 2;\r\n            this.PasswordTextBox.UseSystemPasswordChar = true;\r\n            this.PasswordTextBox.WordWrap = false;\r\n            // \r\n            // EncryptionLabel\r\n            // \r\n            this.EncryptionLabel.Anchor = System.Windows.Forms.AnchorStyles.Right;\r\n            this.EncryptionLabel.AutoSize = true;\r\n            this.EncryptionLabel.Location = new System.Drawing.Point(56, 134);\r\n            this.EncryptionLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.EncryptionLabel.Name = \"EncryptionLabel\";\r\n            this.EncryptionLabel.Size = new System.Drawing.Size(87, 15);\r\n            this.EncryptionLabel.TabIndex = 4;\r\n            this.EncryptionLabel.Text = \"Encryption\";\r\n            // \r\n            // EncryptionSelect\r\n            // \r\n            this.EncryptionSelect.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.EncryptionSelect.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;\r\n            this.EncryptionSelect.FormattingEnabled = true;\r\n            this.EncryptionSelect.ImeMode = System.Windows.Forms.ImeMode.NoControl;\r\n            this.EncryptionSelect.ItemHeight = 15;\r\n            this.EncryptionSelect.Location = new System.Drawing.Point(150, 129);\r\n            this.EncryptionSelect.Margin = new System.Windows.Forms.Padding(3, 5, 3, 8);\r\n            this.EncryptionSelect.Name = \"EncryptionSelect\";\r\n            this.EncryptionSelect.Size = new System.Drawing.Size(205, 23);\r\n            this.EncryptionSelect.TabIndex = 4;\r\n            // \r\n            // TimeoutLabel\r\n            // \r\n            this.TimeoutLabel.Anchor = System.Windows.Forms.AnchorStyles.Right;\r\n            this.TimeoutLabel.AutoSize = true;\r\n            this.TimeoutLabel.Location = new System.Drawing.Point(40, 319);\r\n            this.TimeoutLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.TimeoutLabel.Name = \"TimeoutLabel\";\r\n            this.TimeoutLabel.RightToLeft = System.Windows.Forms.RightToLeft.No;\r\n            this.TimeoutLabel.Size = new System.Drawing.Size(103, 15);\r\n            this.TimeoutLabel.TabIndex = 9;\r\n            this.TimeoutLabel.Text = \"Timeout(Sec)\";\r\n            // \r\n            // TimeoutTextBox\r\n            // \r\n            this.TimeoutTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.TimeoutTextBox.Location = new System.Drawing.Point(150, 314);\r\n            this.TimeoutTextBox.MaxLength = 5;\r\n            this.TimeoutTextBox.Name = \"TimeoutTextBox\";\r\n            this.TimeoutTextBox.Size = new System.Drawing.Size(205, 25);\r\n            this.TimeoutTextBox.TabIndex = 9;\r\n            // \r\n            // PluginLabel\r\n            // \r\n            this.PluginLabel.Anchor = System.Windows.Forms.AnchorStyles.Right;\r\n            this.PluginLabel.AutoSize = true;\r\n            this.PluginLabel.Location = new System.Drawing.Point(24, 168);\r\n            this.PluginLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.PluginLabel.Name = \"PluginLabel\";\r\n            this.PluginLabel.Size = new System.Drawing.Size(119, 15);\r\n            this.PluginLabel.TabIndex = 5;\r\n            this.PluginLabel.Text = \"Plugin Program\";\r\n            // \r\n            // PluginOptionsTextBox\r\n            // \r\n            this.PluginOptionsTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.PluginOptionsTextBox.Location = new System.Drawing.Point(150, 194);\r\n            this.PluginOptionsTextBox.MaxLength = 256;\r\n            this.PluginOptionsTextBox.Name = \"PluginOptionsTextBox\";\r\n            this.PluginOptionsTextBox.Size = new System.Drawing.Size(205, 25);\r\n            this.PluginOptionsTextBox.TabIndex = 6;\r\n            this.PluginOptionsTextBox.WordWrap = false;\r\n            // \r\n            // ShowPasswdCheckBox\r\n            // \r\n            this.ShowPasswdCheckBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) \r\n            | System.Windows.Forms.AnchorStyles.Left)));\r\n            this.ShowPasswdCheckBox.AutoSize = true;\r\n            this.ShowPasswdCheckBox.Location = new System.Drawing.Point(151, 101);\r\n            this.ShowPasswdCheckBox.Margin = new System.Windows.Forms.Padding(4);\r\n            this.ShowPasswdCheckBox.Name = \"ShowPasswdCheckBox\";\r\n            this.ShowPasswdCheckBox.Size = new System.Drawing.Size(133, 19);\r\n            this.ShowPasswdCheckBox.TabIndex = 3;\r\n            this.ShowPasswdCheckBox.Text = \"Show Password\";\r\n            this.ShowPasswdCheckBox.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;\r\n            this.ShowPasswdCheckBox.UseVisualStyleBackColor = true;\r\n            this.ShowPasswdCheckBox.CheckedChanged += new System.EventHandler(this.ShowPasswdCheckBox_CheckedChanged);\r\n            // \r\n            // PluginArgumentsTextBox\r\n            // \r\n            this.PluginArgumentsTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.PluginArgumentsTextBox.Location = new System.Drawing.Point(150, 252);\r\n            this.PluginArgumentsTextBox.MaxLength = 512;\r\n            this.PluginArgumentsTextBox.Name = \"PluginArgumentsTextBox\";\r\n            this.PluginArgumentsTextBox.Size = new System.Drawing.Size(205, 25);\r\n            this.PluginArgumentsTextBox.TabIndex = 7;\r\n            this.PluginArgumentsTextBox.WordWrap = false;\r\n            // \r\n            // PluginArgumentsLabel\r\n            // \r\n            this.PluginArgumentsLabel.Anchor = System.Windows.Forms.AnchorStyles.Right;\r\n            this.PluginArgumentsLabel.AutoSize = true;\r\n            this.PluginArgumentsLabel.Location = new System.Drawing.Point(8, 257);\r\n            this.PluginArgumentsLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.PluginArgumentsLabel.Name = \"PluginArgumentsLabel\";\r\n            this.PluginArgumentsLabel.Size = new System.Drawing.Size(135, 15);\r\n            this.PluginArgumentsLabel.TabIndex = 7;\r\n            this.PluginArgumentsLabel.Text = \"Plugin Arguments\";\r\n            this.toolTip1.SetToolTip(this.PluginArgumentsLabel, \"Not a SIP003 standard. Used as CLI arguments.\\r\\nMandatory:\\r\\n%SS_LOCAL_HOST%, %SS_L\" +\r\n        \"OCAL_PORT%, %SS_REMOTE_HOST%, %SS_REMOTE_PORT%\\r\\nOptional:\\r\\n%SS_PLUGIN_OPTIONS%\");\r\n            // \r\n            // RemarksLabel\r\n            // \r\n            this.RemarksLabel.Anchor = System.Windows.Forms.AnchorStyles.Right;\r\n            this.RemarksLabel.AutoSize = true;\r\n            this.RemarksLabel.Location = new System.Drawing.Point(80, 288);\r\n            this.RemarksLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.RemarksLabel.Name = \"RemarksLabel\";\r\n            this.RemarksLabel.Size = new System.Drawing.Size(63, 15);\r\n            this.RemarksLabel.TabIndex = 8;\r\n            this.RemarksLabel.Text = \"Remarks\";\r\n            // \r\n            // NeedPluginArgCheckBox\r\n            // \r\n            this.NeedPluginArgCheckBox.AutoSize = true;\r\n            this.NeedPluginArgCheckBox.Location = new System.Drawing.Point(151, 226);\r\n            this.NeedPluginArgCheckBox.Margin = new System.Windows.Forms.Padding(4);\r\n            this.NeedPluginArgCheckBox.Name = \"NeedPluginArgCheckBox\";\r\n            this.NeedPluginArgCheckBox.Size = new System.Drawing.Size(189, 19);\r\n            this.NeedPluginArgCheckBox.TabIndex = 10;\r\n            this.NeedPluginArgCheckBox.Text = \"Need Plugin Argument\";\r\n            this.NeedPluginArgCheckBox.UseVisualStyleBackColor = true;\r\n            this.NeedPluginArgCheckBox.CheckedChanged += new System.EventHandler(this.UsePluginArgCheckBox_CheckedChanged);\r\n            // \r\n            // panel2\r\n            // \r\n            this.panel2.Anchor = System.Windows.Forms.AnchorStyles.Top;\r\n            this.panel2.AutoSize = true;\r\n            this.panel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;\r\n            this.panel2.Location = new System.Drawing.Point(190, 229);\r\n            this.panel2.Margin = new System.Windows.Forms.Padding(4);\r\n            this.panel2.Name = \"panel2\";\r\n            this.panel2.Size = new System.Drawing.Size(0, 0);\r\n            this.panel2.TabIndex = 1;\r\n            // \r\n            // OKButton\r\n            // \r\n            this.OKButton.DialogResult = System.Windows.Forms.DialogResult.OK;\r\n            this.OKButton.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.OKButton.Location = new System.Drawing.Point(282, 501);\r\n            this.OKButton.Name = \"OKButton\";\r\n            this.OKButton.Size = new System.Drawing.Size(87, 29);\r\n            this.OKButton.TabIndex = 17;\r\n            this.OKButton.Text = \"OK\";\r\n            this.OKButton.UseVisualStyleBackColor = true;\r\n            this.OKButton.Click += new System.EventHandler(this.OKButton_Click);\r\n            // \r\n            // MyCancelButton\r\n            // \r\n            this.MyCancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;\r\n            this.MyCancelButton.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.MyCancelButton.Location = new System.Drawing.Point(375, 501);\r\n            this.MyCancelButton.Name = \"MyCancelButton\";\r\n            this.MyCancelButton.Size = new System.Drawing.Size(87, 29);\r\n            this.MyCancelButton.TabIndex = 18;\r\n            this.MyCancelButton.Text = \"Cancel\";\r\n            this.MyCancelButton.UseVisualStyleBackColor = true;\r\n            this.MyCancelButton.Click += new System.EventHandler(this.CancelButton_Click);\r\n            // \r\n            // ApplyButton\r\n            // \r\n            this.ApplyButton.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.ApplyButton.Enabled = false;\r\n            this.ApplyButton.Location = new System.Drawing.Point(468, 501);\r\n            this.ApplyButton.Name = \"ApplyButton\";\r\n            this.ApplyButton.Size = new System.Drawing.Size(91, 29);\r\n            this.ApplyButton.TabIndex = 19;\r\n            this.ApplyButton.Text = \"Apply\";\r\n            this.ApplyButton.UseVisualStyleBackColor = true;\r\n            this.ApplyButton.Click += new System.EventHandler(this.ApplyButton_Click);\r\n            // \r\n            // DeleteButton\r\n            // \r\n            this.DeleteButton.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.DeleteButton.Location = new System.Drawing.Point(96, 431);\r\n            this.DeleteButton.Name = \"DeleteButton\";\r\n            this.DeleteButton.Size = new System.Drawing.Size(87, 29);\r\n            this.DeleteButton.TabIndex = 13;\r\n            this.DeleteButton.Text = \"&Delete\";\r\n            this.DeleteButton.UseVisualStyleBackColor = true;\r\n            this.DeleteButton.Click += new System.EventHandler(this.DeleteButton_Click);\r\n            // \r\n            // AddButton\r\n            // \r\n            this.AddButton.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.AddButton.Location = new System.Drawing.Point(3, 431);\r\n            this.AddButton.Name = \"AddButton\";\r\n            this.AddButton.Size = new System.Drawing.Size(87, 29);\r\n            this.AddButton.TabIndex = 12;\r\n            this.AddButton.Text = \"&Add\";\r\n            this.AddButton.UseVisualStyleBackColor = true;\r\n            this.AddButton.Click += new System.EventHandler(this.AddButton_Click);\r\n            // \r\n            // ServerGroupBox\r\n            // \r\n            this.ServerGroupBox.AutoSize = true;\r\n            this.ServerGroupBox.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;\r\n            this.tableLayoutPanel7.SetColumnSpan(this.ServerGroupBox, 4);\r\n            this.ServerGroupBox.Controls.Add(this.tableLayoutPanel1);\r\n            this.ServerGroupBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.ServerGroupBox.Location = new System.Drawing.Point(189, 0);\r\n            this.ServerGroupBox.Margin = new System.Windows.Forms.Padding(3, 0, 3, 3);\r\n            this.ServerGroupBox.Name = \"ServerGroupBox\";\r\n            this.ServerGroupBox.Padding = new System.Windows.Forms.Padding(4);\r\n            this.ServerGroupBox.Size = new System.Drawing.Size(370, 425);\r\n            this.ServerGroupBox.TabIndex = 0;\r\n            this.ServerGroupBox.TabStop = false;\r\n            this.ServerGroupBox.Text = \"Server\";\r\n            // \r\n            // ServersListBox\r\n            // \r\n            this.tableLayoutPanel7.SetColumnSpan(this.ServersListBox, 2);\r\n            this.ServersListBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.ServersListBox.FormattingEnabled = true;\r\n            this.ServersListBox.IntegralHeight = false;\r\n            this.ServersListBox.ItemHeight = 15;\r\n            this.ServersListBox.Location = new System.Drawing.Point(3, 3);\r\n            this.ServersListBox.Name = \"ServersListBox\";\r\n            this.ServersListBox.Size = new System.Drawing.Size(180, 422);\r\n            this.ServersListBox.TabIndex = 11;\r\n            this.ServersListBox.SelectedIndexChanged += new System.EventHandler(this.ServersListBox_SelectedIndexChanged);\r\n            // \r\n            // MoveDownButton\r\n            // \r\n            this.MoveDownButton.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.MoveDownButton.Location = new System.Drawing.Point(96, 501);\r\n            this.MoveDownButton.Name = \"MoveDownButton\";\r\n            this.MoveDownButton.Size = new System.Drawing.Size(87, 29);\r\n            this.MoveDownButton.TabIndex = 16;\r\n            this.MoveDownButton.Text = \"Move D&own\";\r\n            this.MoveDownButton.UseVisualStyleBackColor = true;\r\n            this.MoveDownButton.Click += new System.EventHandler(this.MoveDownButton_Click);\r\n            // \r\n            // MoveUpButton\r\n            // \r\n            this.MoveUpButton.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.MoveUpButton.Location = new System.Drawing.Point(3, 501);\r\n            this.MoveUpButton.Name = \"MoveUpButton\";\r\n            this.MoveUpButton.Size = new System.Drawing.Size(87, 29);\r\n            this.MoveUpButton.TabIndex = 15;\r\n            this.MoveUpButton.Text = \"Move &Up\";\r\n            this.MoveUpButton.UseVisualStyleBackColor = true;\r\n            this.MoveUpButton.Click += new System.EventHandler(this.MoveUpButton_Click);\r\n            // \r\n            // ProxyPortTextBox\r\n            // \r\n            this.tableLayoutPanel7.SetColumnSpan(this.ProxyPortTextBox, 2);\r\n            this.ProxyPortTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.ProxyPortTextBox.Location = new System.Drawing.Point(283, 432);\r\n            this.ProxyPortTextBox.Margin = new System.Windows.Forms.Padding(4);\r\n            this.ProxyPortTextBox.MaxLength = 10;\r\n            this.ProxyPortTextBox.Name = \"ProxyPortTextBox\";\r\n            this.ProxyPortTextBox.Size = new System.Drawing.Size(178, 25);\r\n            this.ProxyPortTextBox.TabIndex = 10;\r\n            this.ProxyPortTextBox.WordWrap = false;\r\n            // \r\n            // ProxyPortLabel\r\n            // \r\n            this.ProxyPortLabel.AutoSize = true;\r\n            this.ProxyPortLabel.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.ProxyPortLabel.Location = new System.Drawing.Point(190, 428);\r\n            this.ProxyPortLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.ProxyPortLabel.Name = \"ProxyPortLabel\";\r\n            this.ProxyPortLabel.Size = new System.Drawing.Size(85, 35);\r\n            this.ProxyPortLabel.TabIndex = 10;\r\n            this.ProxyPortLabel.Text = \"Proxy Port\";\r\n            this.ProxyPortLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;\r\n            // \r\n            // PortableModeCheckBox\r\n            // \r\n            this.PortableModeCheckBox.AutoSize = true;\r\n            this.tableLayoutPanel7.SetColumnSpan(this.PortableModeCheckBox, 2);\r\n            this.PortableModeCheckBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.PortableModeCheckBox.Location = new System.Drawing.Point(283, 467);\r\n            this.PortableModeCheckBox.Margin = new System.Windows.Forms.Padding(4);\r\n            this.PortableModeCheckBox.Name = \"PortableModeCheckBox\";\r\n            this.PortableModeCheckBox.Size = new System.Drawing.Size(178, 27);\r\n            this.PortableModeCheckBox.TabIndex = 11;\r\n            this.PortableModeCheckBox.Text = \"Portable Mode\";\r\n            this.toolTip1.SetToolTip(this.PortableModeCheckBox, \"restart required\");\r\n            this.PortableModeCheckBox.UseVisualStyleBackColor = true;\r\n            // \r\n            // DuplicateButton\r\n            // \r\n            this.DuplicateButton.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.DuplicateButton.Location = new System.Drawing.Point(3, 466);\r\n            this.DuplicateButton.Name = \"DuplicateButton\";\r\n            this.DuplicateButton.Size = new System.Drawing.Size(87, 29);\r\n            this.DuplicateButton.TabIndex = 14;\r\n            this.DuplicateButton.Text = \"Dupli&cate\";\r\n            this.DuplicateButton.UseVisualStyleBackColor = true;\r\n            this.DuplicateButton.Click += new System.EventHandler(this.DuplicateButton_Click);\r\n            // \r\n            // tableLayoutPanel7\r\n            // \r\n            this.tableLayoutPanel7.AutoSize = true;\r\n            this.tableLayoutPanel7.ColumnCount = 6;\r\n            this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));\r\n            this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));\r\n            this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));\r\n            this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));\r\n            this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));\r\n            this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));\r\n            this.tableLayoutPanel7.Controls.Add(this.ApplyButton, 5, 3);\r\n            this.tableLayoutPanel7.Controls.Add(this.MyCancelButton, 4, 3);\r\n            this.tableLayoutPanel7.Controls.Add(this.OKButton, 3, 3);\r\n            this.tableLayoutPanel7.Controls.Add(this.ProxyPortTextBox, 3, 1);\r\n            this.tableLayoutPanel7.Controls.Add(this.MoveDownButton, 1, 3);\r\n            this.tableLayoutPanel7.Controls.Add(this.ProxyPortLabel, 2, 1);\r\n            this.tableLayoutPanel7.Controls.Add(this.MoveUpButton, 0, 3);\r\n            this.tableLayoutPanel7.Controls.Add(this.AddButton, 0, 1);\r\n            this.tableLayoutPanel7.Controls.Add(this.DeleteButton, 1, 1);\r\n            this.tableLayoutPanel7.Controls.Add(this.DuplicateButton, 0, 2);\r\n            this.tableLayoutPanel7.Controls.Add(this.ServersListBox, 0, 0);\r\n            this.tableLayoutPanel7.Controls.Add(this.ServerGroupBox, 2, 0);\r\n            this.tableLayoutPanel7.Controls.Add(this.PortableModeCheckBox, 3, 2);\r\n            this.tableLayoutPanel7.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.tableLayoutPanel7.GrowStyle = System.Windows.Forms.TableLayoutPanelGrowStyle.FixedSize;\r\n            this.tableLayoutPanel7.Location = new System.Drawing.Point(10, 10);\r\n            this.tableLayoutPanel7.Name = \"tableLayoutPanel7\";\r\n            this.tableLayoutPanel7.RowCount = 4;\r\n            this.tableLayoutPanel7.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));\r\n            this.tableLayoutPanel7.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel7.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel7.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel7.Size = new System.Drawing.Size(562, 533);\r\n            this.tableLayoutPanel7.TabIndex = 8;\r\n            // \r\n            // GroupLabel\r\n            // \r\n            this.GroupLabel.Anchor = System.Windows.Forms.AnchorStyles.Right;\r\n            this.GroupLabel.AutoSize = true;\r\n            this.GroupLabel.Location = new System.Drawing.Point(96, 350);\r\n            this.GroupLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);\r\n            this.GroupLabel.Name = \"GroupLabel\";\r\n            this.GroupLabel.RightToLeft = System.Windows.Forms.RightToLeft.No;\r\n            this.GroupLabel.Size = new System.Drawing.Size(47, 15);\r\n            this.GroupLabel.TabIndex = 11;\r\n            this.GroupLabel.Text = \"Group\";\r\n            // \r\n            // GroupTextBox\r\n            // \r\n            this.GroupTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.GroupTextBox.Location = new System.Drawing.Point(150, 345);\r\n            this.GroupTextBox.MaxLength = 5;\r\n            this.GroupTextBox.Name = \"GroupTextBox\";\r\n            this.GroupTextBox.ReadOnly = true;\r\n            this.GroupTextBox.Size = new System.Drawing.Size(205, 25);\r\n            this.GroupTextBox.TabIndex = 12;\r\n            // \r\n            // ConfigForm\r\n            // \r\n            this.AcceptButton = this.OKButton;\r\n            this.AutoScaleDimensions = new System.Drawing.SizeF(120F, 120F);\r\n            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;\r\n            this.CancelButton = this.MyCancelButton;\r\n            this.ClientSize = new System.Drawing.Size(582, 553);\r\n            this.Controls.Add(this.tableLayoutPanel7);\r\n            this.Controls.Add(this.panel2);\r\n            this.Margin = new System.Windows.Forms.Padding(4);\r\n            this.MinimizeBox = false;\r\n            this.MinimumSize = new System.Drawing.Size(400, 575);\r\n            this.Name = \"ConfigForm\";\r\n            this.Padding = new System.Windows.Forms.Padding(10);\r\n            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;\r\n            this.Text = \"Edit Servers\";\r\n            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.ConfigForm_FormClosed);\r\n            this.Shown += new System.EventHandler(this.ConfigForm_Shown);\r\n            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ConfigForm_KeyDown);\r\n            this.tableLayoutPanel1.ResumeLayout(false);\r\n            this.tableLayoutPanel1.PerformLayout();\r\n            this.ServerGroupBox.ResumeLayout(false);\r\n            this.ServerGroupBox.PerformLayout();\r\n            this.tableLayoutPanel7.ResumeLayout(false);\r\n            this.tableLayoutPanel7.PerformLayout();\r\n            this.ResumeLayout(false);\r\n            this.PerformLayout();\r\n\r\n        }\r\n\r\n        #endregion\r\n\r\n        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;\r\n        private System.Windows.Forms.Label IPLabel;\r\n        private System.Windows.Forms.Label ServerPortLabel;\r\n        private System.Windows.Forms.Label PasswordLabel;\r\n        private System.Windows.Forms.TextBox IPTextBox;\r\n        private System.Windows.Forms.TextBox ServerPortTextBox;\r\n        private System.Windows.Forms.Label EncryptionLabel;\r\n        private System.Windows.Forms.ComboBox EncryptionSelect;\r\n        private System.Windows.Forms.Panel panel2;\r\n        private System.Windows.Forms.Button OKButton;\r\n        private System.Windows.Forms.Button MyCancelButton;\r\n        private System.Windows.Forms.Button ApplyButton;\r\n        private System.Windows.Forms.Button DeleteButton;\r\n        private System.Windows.Forms.Button AddButton;\r\n        private System.Windows.Forms.GroupBox ServerGroupBox;\r\n        private System.Windows.Forms.ListBox ServersListBox;\r\n        private System.Windows.Forms.TextBox RemarksTextBox;\r\n        private System.Windows.Forms.Label RemarksLabel;\r\n        private System.Windows.Forms.TextBox ProxyPortTextBox;\r\n        private System.Windows.Forms.Label ProxyPortLabel;\r\n        private System.Windows.Forms.Button MoveDownButton;\r\n        private System.Windows.Forms.Button MoveUpButton;\r\n        private System.Windows.Forms.Button DuplicateButton;\r\n        private System.Windows.Forms.Label TimeoutLabel;\r\n        private System.Windows.Forms.TextBox TimeoutTextBox;\r\n        private System.Windows.Forms.Label PluginOptionsLabel;\r\n        private System.Windows.Forms.TextBox PluginTextBox;\r\n        private System.Windows.Forms.Label PluginLabel;\r\n        private System.Windows.Forms.TextBox PluginOptionsTextBox;\r\n        private System.Windows.Forms.CheckBox ShowPasswdCheckBox;\r\n        private System.Windows.Forms.TextBox PasswordTextBox;\r\n        private System.Windows.Forms.TextBox PluginArgumentsTextBox;\r\n        private System.Windows.Forms.Label PluginArgumentsLabel;\r\n        private System.Windows.Forms.ToolTip toolTip1;\r\n        private System.Windows.Forms.CheckBox PortableModeCheckBox;\r\n        private System.Windows.Forms.CheckBox NeedPluginArgCheckBox;\r\n        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel7;\r\n        private System.Windows.Forms.Label GroupLabel;\r\n        private System.Windows.Forms.TextBox GroupTextBox;\r\n    }\r\n}\r\n\r\n"
  },
  {
    "path": "shadowsocks-csharp/View/ConfigForm.cs",
    "content": "using Shadowsocks.Controller;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Properties;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Windows.Forms;\r\n\r\nnamespace Shadowsocks.View\r\n{\r\n    public partial class ConfigForm : Form\r\n    {\r\n        private ShadowsocksController controller;\r\n\r\n        // this is a copy of configuration that we are working on\r\n        private Configuration _modifiedConfiguration;\r\n        private int _lastSelectedIndex = -1;\r\n\r\n        private bool isChange = false;\r\n\r\n        private class EncryptionMethod\r\n        {\r\n            public readonly string name;\r\n            public readonly bool deprecated;\r\n\r\n            // Edit here to add/delete encryption method displayed in UI\r\n            private static string[] inuseMethod = new string[]\r\n            {\r\n                \"none\",\r\n                \"plain\",\r\n                \"aes-256-gcm\",\r\n                \"aes-192-gcm\",\r\n                \"aes-128-gcm\",\r\n                \"chacha20-ietf-poly1305\",\r\n                \"xchacha20-ietf-poly1305\",\r\n            };\r\n            public static EncryptionMethod[] AllMethods\r\n            {\r\n                get\r\n                {\r\n                    if (!init) Init();\r\n                    return allMethods;\r\n                }\r\n            }\r\n            private static bool init = false;\r\n            private static EncryptionMethod[] allMethods;\r\n            private static Dictionary<string, EncryptionMethod> methodByName = new Dictionary<string, EncryptionMethod>();\r\n            private static void Init()\r\n            {\r\n                var all = new List<EncryptionMethod>();\r\n\r\n                all.AddRange(inuseMethod.Select(i => new EncryptionMethod(i, false)));\r\n\r\n                allMethods = all.ToArray();\r\n                foreach (var item in all)\r\n                {\r\n                    methodByName[item.name] = item;\r\n                }\r\n                init = true;\r\n            }\r\n\r\n            public static EncryptionMethod GetMethod(string name)\r\n            {\r\n                if (!init) Init();\r\n                bool success = methodByName.TryGetValue(name, out EncryptionMethod method);\r\n                if (!success)\r\n                {\r\n                    string defaultMethod = Server.DefaultMethod;\r\n                    MessageBox.Show(I18N.GetString(\"Encryption method {0} not exist, will replace with {1}\", name, defaultMethod), I18N.GetString(\"Shadowsocks\"));\r\n                    return methodByName[defaultMethod];\r\n                }\r\n                return method;\r\n            }\r\n\r\n            private EncryptionMethod(string name, bool deprecated)\r\n            {\r\n                this.name = name;\r\n                this.deprecated = deprecated;\r\n            }\r\n\r\n            public override string ToString()\r\n            {\r\n                return deprecated ? $\"{name} ({I18N.GetString(\"deprecated\")})\" : name;\r\n            }\r\n        }\r\n\r\n        public ConfigForm(ShadowsocksController controller)\r\n        {\r\n            Font = SystemFonts.MessageBoxFont;\r\n            InitializeComponent();\r\n            EncryptionSelect.Items.AddRange(EncryptionMethod.AllMethods);\r\n\r\n            PerformLayout();\r\n\r\n            UpdateTexts();\r\n            SetupValueChangedListeners();\r\n            Icon = Icon.FromHandle(Resources.ssw128.GetHicon());\r\n\r\n            this.controller = controller;\r\n            controller.ConfigChanged += Controller_ConfigChanged;\r\n\r\n            LoadCurrentConfiguration();\r\n        }\r\n\r\n        private void UpdateTexts()\r\n        {\r\n            I18N.TranslateForm(this);\r\n            toolTip1.SetToolTip(PortableModeCheckBox, I18N.GetString(\"Restart required\"));\r\n        }\r\n\r\n        private void SetupValueChangedListeners()\r\n        {\r\n            IPTextBox.TextChanged += ConfigValueChanged;\r\n            ProxyPortTextBox.TextChanged += ConfigValueChanged;\r\n            PasswordTextBox.TextChanged += ConfigValueChanged;\r\n            EncryptionSelect.SelectedIndexChanged += ConfigValueChanged;\r\n            PluginTextBox.TextChanged += ConfigValueChanged;\r\n            PluginArgumentsTextBox.TextChanged += ConfigValueChanged;\r\n            PluginOptionsTextBox.TextChanged += ConfigValueChanged;\r\n            RemarksTextBox.TextChanged += ConfigValueChanged;\r\n            TimeoutTextBox.TextChanged += ConfigValueChanged;\r\n            PortableModeCheckBox.CheckedChanged += ConfigValueChanged;\r\n            ServerPortTextBox.TextChanged += ConfigValueChanged;\r\n        }\r\n\r\n        private void Controller_ConfigChanged(object sender, EventArgs e)\r\n        {\r\n            LoadCurrentConfiguration();\r\n        }\r\n\r\n        private void ConfigValueChanged(object sender, EventArgs e)\r\n        {\r\n            isChange = true;\r\n            ApplyButton.Enabled = true;\r\n        }\r\n\r\n        private bool ValidateAndSaveSelectedServerDetails(bool isSave = false, bool isCopy = false)\r\n        {\r\n            try\r\n            {\r\n                if (_lastSelectedIndex == -1 || _lastSelectedIndex >= _modifiedConfiguration.configs.Count)\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                bool verify = GetServerDetailsFromUI(out Server server, isSave, isCopy);\r\n\r\n                if (server != null)\r\n                {\r\n                    if (isSave || isCopy)\r\n                        Configuration.CheckServer(server);\r\n\r\n                    _modifiedConfiguration.configs[_lastSelectedIndex] = server;\r\n                }\r\n                return verify;\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                MessageBox.Show(ex.Message);\r\n            }\r\n            return false;\r\n        }\r\n\r\n        private bool GetServerDetailsFromUI(out Server server, bool isSave = false, bool isCopy = false)\r\n        {\r\n            server = null;\r\n\r\n            bool? checkIP = false;\r\n            bool? checkPort = false;\r\n            bool? checkPassword = false;\r\n            bool? checkTimeout = false;\r\n\r\n            if ((checkIP = CheckIPTextBox(out string address, isSave, isCopy)).GetValueOrDefault(false) && address != null\r\n                    && (checkPort = CheckServerPortTextBox(out int? addressPort, isSave, isCopy)).GetValueOrDefault(false) && addressPort.HasValue\r\n                        && (checkPassword = CheckPasswordTextBox(out string serverPassword, isSave, isCopy)).GetValueOrDefault(false) && serverPassword != null\r\n                            && (checkTimeout = CheckTimeoutTextBox(out int? timeout, isSave, isCopy)).GetValueOrDefault(false) && timeout.HasValue)\r\n            {\r\n                server = new Server()\r\n                {\r\n                    server = address,\r\n                    server_port = addressPort.Value,\r\n                    password = serverPassword,\r\n                    method = ((EncryptionMethod)EncryptionSelect.SelectedItem).name,\r\n                    plugin = PluginTextBox.Text,\r\n                    plugin_opts = PluginOptionsTextBox.Text,\r\n                    plugin_args = PluginArgumentsTextBox.Text,\r\n                    remarks = RemarksTextBox.Text,\r\n                    timeout = timeout.Value,\r\n                    group = GroupTextBox.Text\r\n                };\r\n\r\n                return true;\r\n            }\r\n\r\n            if (checkIP == null || checkPort == null || checkTimeout == null)\r\n            {\r\n                _modifiedConfiguration.configs.RemoveAt(_lastSelectedIndex);\r\n                ServersListBox.SelectedIndexChanged -= ServersListBox_SelectedIndexChanged;\r\n\r\n                int lastIndex = ServersListBox.SelectedIndex;\r\n\r\n                LoadServerNameListToUI(_modifiedConfiguration);\r\n\r\n                _lastSelectedIndex = (ServersListBox.SelectedIndex = (_lastSelectedIndex == ServersListBox.Items.Count ? lastIndex : lastIndex - 1));\r\n\r\n                ServersListBox.SelectedIndexChanged += ServersListBox_SelectedIndexChanged;\r\n                return true;\r\n            }\r\n            else\r\n                return false;\r\n        }\r\n\r\n        #region GetServerDetailsFromUI Check\r\n\r\n        private bool? CheckIPTextBox(out string address, bool isSave, bool isCopy)\r\n        {\r\n            address = null;\r\n            string outAddress;\r\n            if (Uri.CheckHostName(outAddress = IPTextBox.Text.Trim()) == UriHostNameType.Unknown)\r\n            {\r\n                if (!isSave && !isCopy && ServersListBox.Items.Count > 1 && I18N.GetString(\"New server\").Equals(ServersListBox.Items[_lastSelectedIndex].ToString()))\r\n                {\r\n                    DialogResult result = MessageBox.Show(I18N.GetString(\"Whether to discard unconfigured servers\"), I18N.GetString(\"Operation failure\"), MessageBoxButtons.OKCancel);\r\n\r\n                    if (result == DialogResult.OK)\r\n                        return null;\r\n                }\r\n                else if (isChange && !isSave && !isCopy)\r\n                {\r\n                    var result = MessageBox.Show(I18N.GetString(\"Invalid server address, Cannot automatically save or discard changes\"), I18N.GetString(\"Auto save failed\"), MessageBoxButtons.OKCancel);\r\n\r\n                    if (result == DialogResult.Cancel)\r\n                        return false;\r\n                    else\r\n                    {\r\n                        address = _modifiedConfiguration.configs[_lastSelectedIndex].server;\r\n                        return true;\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    MessageBox.Show(I18N.GetString(\"Invalid server address\"), I18N.GetString(\"Operation failure\"));\r\n                    IPTextBox.Focus();\r\n                }\r\n                return false;\r\n            }\r\n            else\r\n            {\r\n                address = outAddress;\r\n            }\r\n            return true;\r\n        }\r\n\r\n        private bool? CheckServerPortTextBox(out int? addressPort, bool isSave, bool isCopy)\r\n        {\r\n            addressPort = null;\r\n            if (!int.TryParse(ServerPortTextBox.Text, out int outaddressPort))\r\n            {\r\n                if (!isSave && !isCopy && ServersListBox.Items.Count > 1 && I18N.GetString(\"New server\").Equals(ServersListBox.Items[_lastSelectedIndex].ToString()))\r\n                {\r\n                    DialogResult result = MessageBox.Show(I18N.GetString(\"Whether to discard unconfigured servers\"), I18N.GetString(\"Operation failure\"), MessageBoxButtons.OKCancel);\r\n\r\n                    if (result == DialogResult.OK)\r\n                        return null;\r\n                }\r\n                else if (isChange && !isSave && !isCopy)\r\n                {\r\n                    var result = MessageBox.Show(I18N.GetString(\"Illegal port number format, Cannot automatically save or discard changes\"), I18N.GetString(\"Auto save failed\"), MessageBoxButtons.OKCancel);\r\n\r\n                    if (result == DialogResult.Cancel)\r\n                        return false;\r\n                    else\r\n                    {\r\n                        addressPort = _modifiedConfiguration.configs[_lastSelectedIndex].server_port;\r\n                        return true;\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    MessageBox.Show(I18N.GetString(\"Illegal port number format\"), I18N.GetString(\"Operation failure\"));\r\n                    ServerPortTextBox.Focus();\r\n                }\r\n                return false;\r\n            }\r\n            else\r\n            {\r\n                addressPort = outaddressPort;\r\n            }\r\n            return true;\r\n        }\r\n\r\n        private bool? CheckPasswordTextBox(out string password, bool isSave, bool isCopy)\r\n        {\r\n            password = null;\r\n            string outPassword;\r\n            if (string.IsNullOrWhiteSpace(outPassword = PasswordTextBox.Text))\r\n            {\r\n                if (!isSave && !isCopy && ServersListBox.Items.Count > 1 && I18N.GetString(\"New server\").Equals(ServersListBox.Items[_lastSelectedIndex].ToString()))\r\n                {\r\n                    DialogResult result = MessageBox.Show(I18N.GetString(\"Whether to discard unconfigured servers\"), I18N.GetString(\"Operation failure\"), MessageBoxButtons.OKCancel);\r\n\r\n                    if (result == DialogResult.OK)\r\n                        return null;\r\n                }\r\n                else if (isChange && !isSave && !isCopy)\r\n                {\r\n                    var result = MessageBox.Show(I18N.GetString(\"Password can not be blank, Cannot automatically save or discard changes\"), I18N.GetString(\"Auto save failed\"), MessageBoxButtons.OKCancel);\r\n\r\n                    if (result == DialogResult.Cancel)\r\n                        return false;\r\n                    else\r\n                    {\r\n                        password = _modifiedConfiguration.configs[_lastSelectedIndex].password;\r\n                        return true;\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    MessageBox.Show(I18N.GetString(\"Password can not be blank\"), I18N.GetString(\"Operation failure\"));\r\n                    PasswordTextBox.Focus();\r\n                }\r\n                return false;\r\n            }\r\n            else\r\n            {\r\n                password = outPassword;\r\n            }\r\n            return true;\r\n        }\r\n\r\n        private bool? CheckTimeoutTextBox(out int? timeout, bool isSave, bool isCopy)\r\n        {\r\n            timeout = null;\r\n            if (!int.TryParse(TimeoutTextBox.Text, out int outTimeout))\r\n            {\r\n                if (!isSave && !isCopy && ServersListBox.Items.Count > 1 && I18N.GetString(\"New server\").Equals(ServersListBox.Items[_lastSelectedIndex].ToString()))\r\n                {\r\n                    DialogResult result = MessageBox.Show(I18N.GetString(\"Whether to discard unconfigured servers\"), I18N.GetString(\"Operation failure\"), MessageBoxButtons.OKCancel);\r\n\r\n                    if (result == DialogResult.OK)\r\n                        return null;\r\n                }\r\n                else if (isChange && !isSave && !isCopy)\r\n                {\r\n                    var result = MessageBox.Show(I18N.GetString(\"Illegal timeout format, Cannot automatically save or discard changes\"), I18N.GetString(\"Auto save failed\"), MessageBoxButtons.OKCancel);\r\n\r\n                    if (result == DialogResult.Cancel)\r\n                        return false;\r\n                    else\r\n                    {\r\n                        timeout = _modifiedConfiguration.configs[_lastSelectedIndex].timeout;\r\n                        return true;\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    MessageBox.Show(I18N.GetString(\"Illegal timeout format\"), I18N.GetString(\"Operation failure\"));\r\n                    TimeoutTextBox.Focus();\r\n                }\r\n                return false;\r\n            }\r\n            else\r\n            {\r\n                timeout = outTimeout;\r\n            }\r\n            return true;\r\n        }\r\n\r\n        #endregion\r\n\r\n        private void LoadSelectedServerDetails()\r\n        {\r\n            if (ServersListBox.SelectedIndex >= 0 && ServersListBox.SelectedIndex < _modifiedConfiguration.configs.Count)\r\n            {\r\n                Server server = _modifiedConfiguration.configs[ServersListBox.SelectedIndex];\r\n                SetServerDetailsToUI(server);\r\n            }\r\n        }\r\n\r\n        private void SetServerDetailsToUI(Server server)\r\n        {\r\n            IPTextBox.Text = server.server;\r\n            ServerPortTextBox.Text = server.server_port.ToString();\r\n            PasswordTextBox.Text = server.password;\r\n            EncryptionSelect.SelectedItem = EncryptionMethod.GetMethod(server.method ?? Server.DefaultMethod);\r\n            PluginTextBox.Text = server.plugin;\r\n            PluginOptionsTextBox.Text = server.plugin_opts;\r\n            PluginArgumentsTextBox.Text = server.plugin_args;\r\n\r\n            bool showPluginArgInput = !string.IsNullOrEmpty(server.plugin_args);\r\n            NeedPluginArgCheckBox.Checked = showPluginArgInput;\r\n            ShowHidePluginArgInput(showPluginArgInput);\r\n\r\n            RemarksTextBox.Text = server.remarks;\r\n            TimeoutTextBox.Text = server.timeout.ToString();\r\n\r\n            GroupTextBox.Text = server.group;\r\n\r\n            isChange = false;\r\n        }\r\n\r\n        private void ShowHidePluginArgInput(bool show)\r\n        {\r\n            PluginArgumentsTextBox.Visible = show;\r\n            PluginArgumentsLabel.Visible = show;\r\n        }\r\n\r\n        private void LoadServerNameListToUI(Configuration configuration)\r\n        {\r\n            ServersListBox.Items.Clear();\r\n            foreach (Server server in configuration.configs)\r\n            {\r\n                ServersListBox.Items.Add(server.ToString());\r\n            }\r\n        }\r\n\r\n        private void LoadCurrentConfiguration()\r\n        {\r\n            _modifiedConfiguration = controller.GetCurrentConfiguration();\r\n            LoadServerNameListToUI(_modifiedConfiguration);\r\n\r\n            _lastSelectedIndex = _modifiedConfiguration.index;\r\n            if (_lastSelectedIndex < 0 || _lastSelectedIndex >= ServersListBox.Items.Count)\r\n            {\r\n                _lastSelectedIndex = 0;\r\n            }\r\n\r\n            ServersListBox.SelectedIndex = _lastSelectedIndex;\r\n            UpdateButtons();\r\n            LoadSelectedServerDetails();\r\n\r\n            ProxyPortTextBox.Text = _modifiedConfiguration.localPort.ToString();\r\n            PortableModeCheckBox.Checked = _modifiedConfiguration.portableMode;\r\n\r\n            ApplyButton.Enabled = false;\r\n        }\r\n\r\n        private bool SaveValidConfiguration()\r\n        {\r\n            if (!ValidateAndSaveSelectedServerDetails(isSave: true))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            int localPort = int.Parse(ProxyPortTextBox.Text);\r\n            Configuration.CheckLocalPort(localPort);\r\n            _modifiedConfiguration.localPort = localPort;\r\n\r\n            _modifiedConfiguration.portableMode = PortableModeCheckBox.Checked;\r\n\r\n            controller.SaveServers(_modifiedConfiguration.configs, _modifiedConfiguration.localPort, _modifiedConfiguration.portableMode);\r\n            // SelectedIndex remains valid\r\n            // We handled this in event handlers, e.g. Add/DeleteButton, SelectedIndexChanged\r\n            // and move operations\r\n            controller.SelectServerIndex(ServersListBox.SelectedIndex);\r\n            return true;\r\n        }\r\n\r\n        private void ConfigForm_KeyDown(object sender, KeyEventArgs e)\r\n        {\r\n            // Sometimes the users may hit enter key by mistake, and the form will close without saving entries.\r\n\r\n            if (e.KeyCode == Keys.Enter)\r\n            {\r\n                SaveValidConfiguration();\r\n            }\r\n        }\r\n\r\n        private void ServersListBox_SelectedIndexChanged(object sender, EventArgs e)\r\n        {\r\n            if (!ServersListBox.CanSelect)\r\n            {\r\n                return;\r\n            }\r\n            if (_lastSelectedIndex == ServersListBox.SelectedIndex)\r\n            {\r\n                // we are moving back to oldSelectedIndex or doing a force move\r\n                return;\r\n            }\r\n            if (!ValidateAndSaveSelectedServerDetails())\r\n            {\r\n                // why this won't cause stack overflow?\r\n                ServersListBox.SelectedIndex = _lastSelectedIndex;\r\n                return;\r\n            }\r\n            if (_lastSelectedIndex >= 0 && _lastSelectedIndex < _modifiedConfiguration.configs.Count)\r\n            {\r\n                ServersListBox.Items[_lastSelectedIndex] = _modifiedConfiguration.configs[_lastSelectedIndex].ToString();\r\n            }\r\n            UpdateButtons();\r\n            LoadSelectedServerDetails();\r\n            _lastSelectedIndex = ServersListBox.SelectedIndex;\r\n        }\r\n\r\n        private void AddButton_Click(object sender, EventArgs e)\r\n        {\r\n            if (ValidateAndSaveSelectedServerDetails(isSave: true))\r\n            {\r\n                Configuration.AddDefaultServerOrServer(_modifiedConfiguration);\r\n                LoadServerNameListToUI(_modifiedConfiguration);\r\n                _lastSelectedIndex = (ServersListBox.SelectedIndex = _modifiedConfiguration.configs.Count - 1);\r\n            }\r\n        }\r\n\r\n        private void DuplicateButton_Click(object sender, EventArgs e)\r\n        {\r\n            if (ValidateAndSaveSelectedServerDetails(isCopy: true))\r\n            {\r\n                Server currServer = _modifiedConfiguration.configs[_lastSelectedIndex];\r\n                Configuration.AddDefaultServerOrServer(_modifiedConfiguration, currServer, _lastSelectedIndex + 1);\r\n                LoadServerNameListToUI(_modifiedConfiguration);\r\n                _lastSelectedIndex = (ServersListBox.SelectedIndex = (_lastSelectedIndex + 1));\r\n            }\r\n        }\r\n\r\n        private void DeleteButton_Click(object sender, EventArgs e)\r\n        {\r\n            _modifiedConfiguration.configs.RemoveAt(_lastSelectedIndex);\r\n\r\n            if (_modifiedConfiguration.configs.Count == 0)\r\n            {\r\n                Configuration.AddDefaultServerOrServer(_modifiedConfiguration);\r\n            }\r\n\r\n            LoadServerNameListToUI(_modifiedConfiguration);\r\n            ServersListBox.SelectedIndexChanged -= ServersListBox_SelectedIndexChanged;\r\n\r\n            _lastSelectedIndex = (ServersListBox.SelectedIndex = (_lastSelectedIndex >= _modifiedConfiguration.configs.Count ? (_modifiedConfiguration.configs.Count - 1) : _lastSelectedIndex));\r\n\r\n            ServersListBox.SelectedIndexChanged += ServersListBox_SelectedIndexChanged;\r\n            LoadSelectedServerDetails();\r\n\r\n            UpdateButtons();\r\n        }\r\n\r\n        private void UpdateButtons()\r\n        {\r\n            DeleteButton.Enabled = (ServersListBox.Items.Count > 0);\r\n            MoveUpButton.Enabled = (ServersListBox.SelectedIndex > 0);\r\n            MoveDownButton.Enabled = (ServersListBox.SelectedIndex < ServersListBox.Items.Count - 1);\r\n        }\r\n\r\n        private void MoveUpButton_Click(object sender, EventArgs e)\r\n        {\r\n            if (ServersListBox.SelectedIndex > 0)\r\n            {\r\n                MoveConfigItem(-1);  // -1 means move backward\r\n            }\r\n        }\r\n\r\n        private void MoveDownButton_Click(object sender, EventArgs e)\r\n        {\r\n            if (ServersListBox.SelectedIndex < ServersListBox.Items.Count - 1)\r\n            {\r\n                MoveConfigItem(+1);  // +1 means move forward\r\n            }\r\n        }\r\n\r\n        private void MoveConfigItem(int step)\r\n        {\r\n            var server = _modifiedConfiguration.configs[_lastSelectedIndex];\r\n            var newIndex = _lastSelectedIndex + step;\r\n\r\n            _modifiedConfiguration.configs.RemoveAt(_lastSelectedIndex);\r\n            _modifiedConfiguration.configs.Insert(newIndex, server);\r\n\r\n            ServersListBox.BeginUpdate();\r\n\r\n            LoadServerNameListToUI(_modifiedConfiguration);\r\n\r\n            _lastSelectedIndex = newIndex;\r\n            ServersListBox.SelectedIndex = newIndex;\r\n            ServersListBox.EndUpdate();\r\n\r\n            UpdateButtons();\r\n        }\r\n\r\n        private void OKButton_Click(object sender, EventArgs e)\r\n        {\r\n            if (SaveValidConfiguration())\r\n            {\r\n                Close();\r\n            }\r\n        }\r\n\r\n        private void CancelButton_Click(object sender, EventArgs e)\r\n        {\r\n            Close();\r\n        }\r\n\r\n        private void ApplyButton_Click(object sender, EventArgs e)\r\n        {\r\n            SaveValidConfiguration();\r\n        }\r\n\r\n        private void ConfigForm_Shown(object sender, EventArgs e)\r\n        {\r\n            IPTextBox.Focus();\r\n        }\r\n\r\n        private void ConfigForm_FormClosed(object sender, FormClosedEventArgs e)\r\n        {\r\n            controller.ConfigChanged -= Controller_ConfigChanged;\r\n        }\r\n\r\n        private void ShowPasswdCheckBox_CheckedChanged(object sender, EventArgs e)\r\n        {\r\n            PasswordTextBox.UseSystemPasswordChar = !ShowPasswdCheckBox.Checked;\r\n        }\r\n\r\n        private void UsePluginArgCheckBox_CheckedChanged(object sender, EventArgs e)\r\n        {\r\n            ShowHidePluginArgInput(NeedPluginArgCheckBox.Checked);\r\n        }\r\n\r\n        private void EncryptionSelect_SelectedIndexChanged(object sender, EventArgs e)\r\n        {\r\n\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/View/ConfigForm.resx",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<root>\r\n  <!-- \r\n    Microsoft ResX Schema \r\n    \r\n    Version 2.0\r\n    \r\n    The primary goals of this format is to allow a simple XML format \r\n    that is mostly human readable. The generation and parsing of the \r\n    various data types are done through the TypeConverter classes \r\n    associated with the data types.\r\n    \r\n    Example:\r\n    \r\n    ... ado.net/XML headers & schema ...\r\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\r\n    <resheader name=\"version\">2.0</resheader>\r\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\r\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\r\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\r\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\r\n    </data>\r\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\r\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r\n        <comment>This is a comment</comment>\r\n    </data>\r\n                \r\n    There are any number of \"resheader\" rows that contain simple \r\n    name/value pairs.\r\n    \r\n    Each data row contains a name, and value. The row also contains a \r\n    type or mimetype. Type corresponds to a .NET class that support \r\n    text/value conversion through the TypeConverter architecture. \r\n    Classes that don't support this are serialized and stored with the \r\n    mimetype set.\r\n    \r\n    The mimetype is used for serialized objects, and tells the \r\n    ResXResourceReader how to depersist the object. This is currently not \r\n    extensible. For a given mimetype the value must be set accordingly:\r\n    \r\n    Note - application/x-microsoft.net.object.binary.base64 is the format \r\n    that the ResXResourceWriter will generate, however the reader can \r\n    read any of the formats listed below.\r\n    \r\n    mimetype: application/x-microsoft.net.object.binary.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r\n            : and then encoded with base64 encoding.\r\n    \r\n    mimetype: application/x-microsoft.net.object.soap.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r\n            : and then encoded with base64 encoding.\r\n\r\n    mimetype: application/x-microsoft.net.object.bytearray.base64\r\n    value   : The object must be serialized into a byte array \r\n            : using a System.ComponentModel.TypeConverter\r\n            : and then encoded with base64 encoding.\r\n    -->\r\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\r\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\r\n      <xsd:complexType>\r\n        <xsd:choice maxOccurs=\"unbounded\">\r\n          <xsd:element name=\"metadata\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"assembly\">\r\n            <xsd:complexType>\r\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"data\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"resheader\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n        </xsd:choice>\r\n      </xsd:complexType>\r\n    </xsd:element>\r\n  </xsd:schema>\r\n  <resheader name=\"resmimetype\">\r\n    <value>text/microsoft-resx</value>\r\n  </resheader>\r\n  <resheader name=\"version\">\r\n    <value>2.0</value>\r\n  </resheader>\r\n  <resheader name=\"reader\">\r\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <resheader name=\"writer\">\r\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <metadata name=\"toolTip1.TrayLocation\" type=\"System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\">\r\n    <value>17, 17</value>\r\n  </metadata>\r\n  <metadata name=\"toolTip1.TrayLocation\" type=\"System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\">\r\n    <value>17, 17</value>\r\n  </metadata>\r\n</root>"
  },
  {
    "path": "shadowsocks-csharp/View/LogForm.Designer.cs",
    "content": "﻿namespace Shadowsocks.View\r\n{\r\n    partial class LogForm\r\n    {\r\n        /// <summary>\r\n        /// Required designer variable.\r\n        /// </summary>\r\n        private System.ComponentModel.IContainer components = null;\r\n\r\n        /// <summary>\r\n        /// Clean up any resources being used.\r\n        /// </summary>\r\n        /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\r\n        protected override void Dispose(bool disposing)\r\n        {\r\n            if (disposing && (components != null))\r\n            {\r\n                components.Dispose();\r\n            }\r\n            base.Dispose(disposing);\r\n        }\r\n\r\n        #region Windows Form Designer generated code\r\n\r\n        /// <summary>\r\n        /// Required method for Designer support - do not modify\r\n        /// the contents of this method with the code editor.\r\n        /// </summary>\r\n        private void InitializeComponent()\r\n        {\r\n            this.components = new System.ComponentModel.Container();\r\n            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();\r\n            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();\r\n            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();\r\n            System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series();\r\n            this.LogMessageTextBox = new System.Windows.Forms.TextBox();\r\n            this.MainMenu = new System.Windows.Forms.MainMenu(this.components);\r\n            this.FileMenuItem = new System.Windows.Forms.MenuItem();\r\n            this.OpenLocationMenuItem = new System.Windows.Forms.MenuItem();\r\n            this.ExitMenuItem = new System.Windows.Forms.MenuItem();\r\n            this.ViewMenuItem = new System.Windows.Forms.MenuItem();\r\n            this.ClearLogsMenuItem = new System.Windows.Forms.MenuItem();\r\n            this.ChangeFontMenuItem = new System.Windows.Forms.MenuItem();\r\n            this.WrapTextMenuItem = new System.Windows.Forms.MenuItem();\r\n            this.TopMostMenuItem = new System.Windows.Forms.MenuItem();\r\n            this.MenuItemSeparater = new System.Windows.Forms.MenuItem();\r\n            this.ShowToolbarMenuItem = new System.Windows.Forms.MenuItem();\r\n            this.TopMostCheckBox = new System.Windows.Forms.CheckBox();\r\n            this.ChangeFontButton = new System.Windows.Forms.Button();\r\n            this.ClearLogsButton = new System.Windows.Forms.Button();\r\n            this.WrapTextCheckBox = new System.Windows.Forms.CheckBox();\r\n            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();\r\n            this.ToolbarFlowLayoutPanel = new System.Windows.Forms.FlowLayoutPanel();\r\n            this.splitContainer1 = new System.Windows.Forms.SplitContainer();\r\n            this.trafficChart = new System.Windows.Forms.DataVisualization.Charting.Chart();\r\n            this.tableLayoutPanel1.SuspendLayout();\r\n            this.ToolbarFlowLayoutPanel.SuspendLayout();\r\n            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();\r\n            this.splitContainer1.Panel1.SuspendLayout();\r\n            this.splitContainer1.Panel2.SuspendLayout();\r\n            this.splitContainer1.SuspendLayout();\r\n            ((System.ComponentModel.ISupportInitialize)(this.trafficChart)).BeginInit();\r\n            this.SuspendLayout();\r\n            // \r\n            // LogMessageTextBox\r\n            // \r\n            this.LogMessageTextBox.BackColor = System.Drawing.Color.Black;\r\n            this.LogMessageTextBox.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.LogMessageTextBox.Font = new System.Drawing.Font(\"Consolas\", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));\r\n            this.LogMessageTextBox.ForeColor = System.Drawing.Color.White;\r\n            this.LogMessageTextBox.Location = new System.Drawing.Point(0, 0);\r\n            this.LogMessageTextBox.MaxLength = 2147483647;\r\n            this.LogMessageTextBox.Multiline = true;\r\n            this.LogMessageTextBox.Name = \"LogMessageTextBox\";\r\n            this.LogMessageTextBox.ReadOnly = true;\r\n            this.LogMessageTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;\r\n            this.LogMessageTextBox.Size = new System.Drawing.Size(378, 74);\r\n            this.LogMessageTextBox.TabIndex = 0;\r\n            // \r\n            // MainMenu\r\n            // \r\n            this.MainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {\r\n            this.FileMenuItem,\r\n            this.ViewMenuItem});\r\n            // \r\n            // FileMenuItem\r\n            // \r\n            this.FileMenuItem.Index = 0;\r\n            this.FileMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {\r\n            this.OpenLocationMenuItem,\r\n            this.ExitMenuItem});\r\n            this.FileMenuItem.Text = \"&File\";\r\n            // \r\n            // OpenLocationMenuItem\r\n            // \r\n            this.OpenLocationMenuItem.Index = 0;\r\n            this.OpenLocationMenuItem.Text = \"&Open Location\";\r\n            this.OpenLocationMenuItem.Click += new System.EventHandler(this.OpenLocationMenuItem_Click);\r\n            // \r\n            // ExitMenuItem\r\n            // \r\n            this.ExitMenuItem.Index = 1;\r\n            this.ExitMenuItem.Text = \"E&xit\";\r\n            this.ExitMenuItem.Click += new System.EventHandler(this.ExitMenuItem_Click);\r\n            // \r\n            // ViewMenuItem\r\n            // \r\n            this.ViewMenuItem.Index = 1;\r\n            this.ViewMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {\r\n            this.ClearLogsMenuItem,\r\n            this.ChangeFontMenuItem,\r\n            this.WrapTextMenuItem,\r\n            this.TopMostMenuItem,\r\n            this.MenuItemSeparater,\r\n            this.ShowToolbarMenuItem});\r\n            this.ViewMenuItem.Text = \"&View\";\r\n            // \r\n            // ClearLogsMenuItem\r\n            // \r\n            this.ClearLogsMenuItem.Index = 0;\r\n            this.ClearLogsMenuItem.Text = \"&Clear Logs\";\r\n            this.ClearLogsMenuItem.Click += new System.EventHandler(this.ClearLogsMenuItem_Click);\r\n            // \r\n            // ChangeFontMenuItem\r\n            // \r\n            this.ChangeFontMenuItem.Index = 1;\r\n            this.ChangeFontMenuItem.Text = \"Change &Font\";\r\n            this.ChangeFontMenuItem.Click += new System.EventHandler(this.ChangeFontMenuItem_Click);\r\n            // \r\n            // WrapTextMenuItem\r\n            // \r\n            this.WrapTextMenuItem.Index = 2;\r\n            this.WrapTextMenuItem.Text = \"&Wrap Text\";\r\n            this.WrapTextMenuItem.Click += new System.EventHandler(this.WrapTextMenuItem_Click);\r\n            // \r\n            // TopMostMenuItem\r\n            // \r\n            this.TopMostMenuItem.Index = 3;\r\n            this.TopMostMenuItem.Text = \"&Top Most\";\r\n            this.TopMostMenuItem.Click += new System.EventHandler(this.TopMostMenuItem_Click);\r\n            // \r\n            // MenuItemSeparater\r\n            // \r\n            this.MenuItemSeparater.Index = 4;\r\n            this.MenuItemSeparater.Text = \"-\";\r\n            // \r\n            // ShowToolbarMenuItem\r\n            // \r\n            this.ShowToolbarMenuItem.Index = 5;\r\n            this.ShowToolbarMenuItem.Text = \"&Show Toolbar\";\r\n            this.ShowToolbarMenuItem.Click += new System.EventHandler(this.ShowToolbarMenuItem_Click);\r\n            // \r\n            // TopMostCheckBox\r\n            // \r\n            this.TopMostCheckBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) \r\n            | System.Windows.Forms.AnchorStyles.Left)));\r\n            this.TopMostCheckBox.AutoSize = true;\r\n            this.TopMostCheckBox.Location = new System.Drawing.Point(249, 3);\r\n            this.TopMostCheckBox.Name = \"TopMostCheckBox\";\r\n            this.TopMostCheckBox.Size = new System.Drawing.Size(72, 23);\r\n            this.TopMostCheckBox.TabIndex = 3;\r\n            this.TopMostCheckBox.Text = \"&Top Most\";\r\n            this.TopMostCheckBox.UseVisualStyleBackColor = true;\r\n            this.TopMostCheckBox.CheckedChanged += new System.EventHandler(this.TopMostCheckBox_CheckedChanged);\r\n            // \r\n            // ChangeFontButton\r\n            // \r\n            this.ChangeFontButton.AutoSize = true;\r\n            this.ChangeFontButton.Location = new System.Drawing.Point(84, 3);\r\n            this.ChangeFontButton.Name = \"ChangeFontButton\";\r\n            this.ChangeFontButton.Size = new System.Drawing.Size(75, 23);\r\n            this.ChangeFontButton.TabIndex = 2;\r\n            this.ChangeFontButton.Text = \"&Font\";\r\n            this.ChangeFontButton.UseVisualStyleBackColor = true;\r\n            this.ChangeFontButton.Click += new System.EventHandler(this.ChangeFontButton_Click);\r\n            // \r\n            // ClearLogsButton\r\n            // \r\n            this.ClearLogsButton.AutoSize = true;\r\n            this.ClearLogsButton.Location = new System.Drawing.Point(3, 3);\r\n            this.ClearLogsButton.Name = \"ClearLogsButton\";\r\n            this.ClearLogsButton.Size = new System.Drawing.Size(75, 23);\r\n            this.ClearLogsButton.TabIndex = 1;\r\n            this.ClearLogsButton.Text = \"&Clear Logs\";\r\n            this.ClearLogsButton.UseVisualStyleBackColor = true;\r\n            this.ClearLogsButton.Click += new System.EventHandler(this.ClearLogsButton_Click);\r\n            // \r\n            // WrapTextCheckBox\r\n            // \r\n            this.WrapTextCheckBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) \r\n            | System.Windows.Forms.AnchorStyles.Left)));\r\n            this.WrapTextCheckBox.AutoSize = true;\r\n            this.WrapTextCheckBox.Location = new System.Drawing.Point(165, 3);\r\n            this.WrapTextCheckBox.Name = \"WrapTextCheckBox\";\r\n            this.WrapTextCheckBox.Size = new System.Drawing.Size(78, 23);\r\n            this.WrapTextCheckBox.TabIndex = 0;\r\n            this.WrapTextCheckBox.Text = \"&Wrap Text\";\r\n            this.WrapTextCheckBox.UseVisualStyleBackColor = true;\r\n            this.WrapTextCheckBox.CheckedChanged += new System.EventHandler(this.WrapTextCheckBox_CheckedChanged);\r\n            // \r\n            // tableLayoutPanel1\r\n            // \r\n            this.tableLayoutPanel1.ColumnCount = 1;\r\n            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));\r\n            this.tableLayoutPanel1.Controls.Add(this.ToolbarFlowLayoutPanel, 0, 0);\r\n            this.tableLayoutPanel1.Controls.Add(this.splitContainer1, 0, 1);\r\n            this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);\r\n            this.tableLayoutPanel1.Name = \"tableLayoutPanel1\";\r\n            this.tableLayoutPanel1.RowCount = 2;\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());\r\n            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));\r\n            this.tableLayoutPanel1.Size = new System.Drawing.Size(384, 161);\r\n            this.tableLayoutPanel1.TabIndex = 2;\r\n            // \r\n            // ToolbarFlowLayoutPanel\r\n            // \r\n            this.ToolbarFlowLayoutPanel.AutoSize = true;\r\n            this.ToolbarFlowLayoutPanel.Controls.Add(this.ClearLogsButton);\r\n            this.ToolbarFlowLayoutPanel.Controls.Add(this.ChangeFontButton);\r\n            this.ToolbarFlowLayoutPanel.Controls.Add(this.WrapTextCheckBox);\r\n            this.ToolbarFlowLayoutPanel.Controls.Add(this.TopMostCheckBox);\r\n            this.ToolbarFlowLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.ToolbarFlowLayoutPanel.Location = new System.Drawing.Point(3, 3);\r\n            this.ToolbarFlowLayoutPanel.Name = \"ToolbarFlowLayoutPanel\";\r\n            this.ToolbarFlowLayoutPanel.Size = new System.Drawing.Size(378, 29);\r\n            this.ToolbarFlowLayoutPanel.TabIndex = 2;\r\n            // \r\n            // splitContainer1\r\n            // \r\n            this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            this.splitContainer1.Location = new System.Drawing.Point(3, 38);\r\n            this.splitContainer1.Name = \"splitContainer1\";\r\n            this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;\r\n            // \r\n            // splitContainer1.Panel1\r\n            // \r\n            this.splitContainer1.Panel1.Controls.Add(this.LogMessageTextBox);\r\n            // \r\n            // splitContainer1.Panel2\r\n            // \r\n            this.splitContainer1.Panel2.Controls.Add(this.trafficChart);\r\n            this.splitContainer1.Size = new System.Drawing.Size(378, 120);\r\n            this.splitContainer1.SplitterDistance = 74;\r\n            this.splitContainer1.TabIndex = 3;\r\n            // \r\n            // trafficChart\r\n            // \r\n            chartArea1.AxisX.LabelStyle.Enabled = false;\r\n            chartArea1.AxisX.MajorGrid.Interval = 5D;\r\n            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.LightGray;\r\n            chartArea1.AxisX.MajorTickMark.Enabled = false;\r\n            chartArea1.AxisX.Maximum = 61D;\r\n            chartArea1.AxisX.Minimum = 1D;\r\n            chartArea1.AxisY.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;\r\n            chartArea1.AxisY.LabelAutoFitMaxFontSize = 8;\r\n            chartArea1.AxisY.LabelStyle.Interval = 0D;\r\n            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.LightGray;\r\n            chartArea1.AxisY.MajorTickMark.Enabled = false;\r\n            chartArea1.AxisY2.MajorGrid.LineColor = System.Drawing.Color.LightGray;\r\n            chartArea1.AxisY2.Minimum = 0D;\r\n            chartArea1.Name = \"ChartArea1\";\r\n            this.trafficChart.ChartAreas.Add(chartArea1);\r\n            this.trafficChart.Dock = System.Windows.Forms.DockStyle.Fill;\r\n            legend1.MaximumAutoSize = 25F;\r\n            legend1.Name = \"Legend1\";\r\n            this.trafficChart.Legends.Add(legend1);\r\n            this.trafficChart.Location = new System.Drawing.Point(0, 0);\r\n            this.trafficChart.Name = \"trafficChart\";\r\n            this.trafficChart.Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.None;\r\n            series1.BorderWidth = 2;\r\n            series1.ChartArea = \"ChartArea1\";\r\n            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;\r\n            series1.Color = System.Drawing.Color.FromArgb(255, 128, 0);\r\n            series1.IsXValueIndexed = true;\r\n            series1.Legend = \"Legend1\";\r\n            series1.Name = \"Inbound\";\r\n            series2.BorderWidth = 2;\r\n            series2.ChartArea = \"ChartArea1\";\r\n            series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;\r\n            series2.Color = System.Drawing.Color.FromArgb(128, 128, 255);\r\n            series2.IsXValueIndexed = true;\r\n            series2.Legend = \"Legend1\";\r\n            series2.Name = \"Outbound\";\r\n            this.trafficChart.Series.Add(series1);\r\n            this.trafficChart.Series.Add(series2);\r\n            this.trafficChart.Size = new System.Drawing.Size(378, 42);\r\n            this.trafficChart.TabIndex = 0;\r\n            this.trafficChart.Text = \"chart1\";\r\n            // \r\n            // LogForm\r\n            // \r\n            this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);\r\n            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;\r\n            this.ClientSize = new System.Drawing.Size(384, 161);\r\n            this.Controls.Add(this.tableLayoutPanel1);\r\n            this.Menu = this.MainMenu;\r\n            this.MinimumSize = new System.Drawing.Size(400, 200);\r\n            this.Name = \"LogForm\";\r\n            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;\r\n            this.Text = \"Log Viewer\";\r\n            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.LogForm_FormClosing);\r\n            this.Load += new System.EventHandler(this.LogForm_Load);\r\n            this.Shown += new System.EventHandler(this.LogForm_Shown);\r\n            this.tableLayoutPanel1.ResumeLayout(false);\r\n            this.tableLayoutPanel1.PerformLayout();\r\n            this.ToolbarFlowLayoutPanel.ResumeLayout(false);\r\n            this.ToolbarFlowLayoutPanel.PerformLayout();\r\n            this.splitContainer1.Panel1.ResumeLayout(false);\r\n            this.splitContainer1.Panel1.PerformLayout();\r\n            this.splitContainer1.Panel2.ResumeLayout(false);\r\n            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();\r\n            this.splitContainer1.ResumeLayout(false);\r\n            ((System.ComponentModel.ISupportInitialize)(this.trafficChart)).EndInit();\r\n            this.ResumeLayout(false);\r\n\r\n        }\r\n\r\n        #endregion\r\n\r\n        private System.Windows.Forms.TextBox LogMessageTextBox;\r\n        private System.Windows.Forms.MainMenu MainMenu;\r\n        private System.Windows.Forms.MenuItem FileMenuItem;\r\n        private System.Windows.Forms.MenuItem OpenLocationMenuItem;\r\n        private System.Windows.Forms.MenuItem ExitMenuItem;\r\n        private System.Windows.Forms.CheckBox WrapTextCheckBox;\r\n        private System.Windows.Forms.Button ClearLogsButton;\r\n        private System.Windows.Forms.Button ChangeFontButton;\r\n        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;\r\n        private System.Windows.Forms.CheckBox TopMostCheckBox;\r\n        private System.Windows.Forms.MenuItem ViewMenuItem;\r\n        private System.Windows.Forms.MenuItem ClearLogsMenuItem;\r\n        private System.Windows.Forms.MenuItem ChangeFontMenuItem;\r\n        private System.Windows.Forms.MenuItem WrapTextMenuItem;\r\n        private System.Windows.Forms.MenuItem TopMostMenuItem;\r\n        private System.Windows.Forms.FlowLayoutPanel ToolbarFlowLayoutPanel;\r\n        private System.Windows.Forms.MenuItem MenuItemSeparater;\r\n        private System.Windows.Forms.MenuItem ShowToolbarMenuItem;\r\n        private System.Windows.Forms.SplitContainer splitContainer1;\r\n        private System.Windows.Forms.DataVisualization.Charting.Chart trafficChart;\r\n    }\r\n}"
  },
  {
    "path": "shadowsocks-csharp/View/LogForm.cs",
    "content": "﻿using System;\r\nusing System.Drawing;\r\nusing System.IO;\r\nusing System.Windows.Forms;\r\nusing System.Windows.Forms.DataVisualization.Charting;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\n\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Properties;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Util;\r\nusing System.Text;\r\nusing NLog;\r\n\r\nnamespace Shadowsocks.View\r\n{\r\n    public partial class LogForm : Form\r\n    {\r\n        private static Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        long lastOffset;\r\n        string filename;\r\n        Timer timer;\r\n        const int BACK_OFFSET = 65536;\r\n        ShadowsocksController controller;\r\n\r\n        // global traffic update lock, make it static\r\n        private static readonly object _lock = new object();\r\n\r\n        #region Traffic Chart\r\n        Queue<TrafficInfo> trafficInfoQueue = new Queue<TrafficInfo>();\r\n        const int queueMaxLength = 60;\r\n        long lastInbound, lastOutbound;\r\n        long maxSpeed = 0, lastMaxSpeed = 0;\r\n        const long minScale = 50;\r\n        BandwidthScaleInfo bandwidthScale;\r\n        List<float> inboundPoints = new List<float>();\r\n        List<float> outboundPoints = new List<float>();\r\n        TextAnnotation inboundAnnotation = new TextAnnotation();\r\n        TextAnnotation outboundAnnotation = new TextAnnotation();\r\n        #endregion\r\n\r\n        public LogForm(ShadowsocksController controller)\r\n        {\r\n            this.controller = controller;\r\n\r\n            InitializeComponent();\r\n            Icon = Icon.FromHandle(Resources.ssw128.GetHicon());\r\n\r\n            var nLogConfig = NLogConfig.LoadXML();\r\n            try\r\n            {\r\n                this.filename = nLogConfig.GetLogFileName();\r\n            }\r\n            catch(Exception)\r\n            {\r\n                // failed to get the file name\r\n            }\r\n            if (string.IsNullOrEmpty(this.filename))\r\n            {\r\n                LogMessageTextBox.AppendText(\"Cannot get the log file name from NLog config file. Please check if the nlog config file exists with corresponding XML nodes.\");\r\n            }\r\n\r\n            LogViewerConfig config = controller.GetCurrentConfiguration().logViewer;\r\n\r\n            topMostTrigger = config.topMost;\r\n            wrapTextTrigger = config.wrapText;\r\n            toolbarTrigger = config.toolbarShown;\r\n            LogMessageTextBox.BackColor = config.BackgroundColor;\r\n            LogMessageTextBox.ForeColor = config.TextColor;\r\n            LogMessageTextBox.Font = config.Font;\r\n\r\n            controller.TrafficChanged += controller_TrafficChanged;\r\n\r\n            UpdateTexts();\r\n        }\r\n\r\n        private void UpdateTrafficChart()\r\n        {\r\n            lock (_lock)\r\n            {\r\n                if (trafficInfoQueue.Count == 0)\r\n                    return;\r\n\r\n                inboundPoints.Clear();\r\n                outboundPoints.Clear();\r\n                maxSpeed = 0;\r\n                foreach (var trafficInfo in trafficInfoQueue)\r\n                {\r\n                    inboundPoints.Add(trafficInfo.inbound);\r\n                    outboundPoints.Add(trafficInfo.outbound);\r\n                    maxSpeed = Math.Max(maxSpeed, Math.Max(trafficInfo.inbound, trafficInfo.outbound));\r\n                }\r\n                lastInbound = trafficInfoQueue.Last().inbound;\r\n                lastOutbound = trafficInfoQueue.Last().outbound;\r\n            }\r\n\r\n            if (maxSpeed > 0)\r\n            {\r\n                lastMaxSpeed -= lastMaxSpeed / 32;\r\n                maxSpeed = Math.Max(minScale, Math.Max(maxSpeed, lastMaxSpeed));\r\n                lastMaxSpeed = maxSpeed;\r\n            }\r\n            else\r\n            {\r\n                maxSpeed = lastMaxSpeed = minScale;\r\n            }\r\n\r\n            bandwidthScale = Utils.GetBandwidthScale(maxSpeed);\r\n\r\n            // re-scale the original data points, since it is List<float>, .ForEach does not work\r\n            inboundPoints = inboundPoints.Select(p => p / bandwidthScale.unit).ToList();\r\n            outboundPoints = outboundPoints.Select(p => p / bandwidthScale.unit).ToList();\r\n\r\n            if (trafficChart.IsHandleCreated)\r\n            {\r\n                trafficChart.Series[\"Inbound\"].Points.DataBindY(inboundPoints);\r\n                trafficChart.Series[\"Outbound\"].Points.DataBindY(outboundPoints);\r\n                trafficChart.ChartAreas[0].AxisY.LabelStyle.Format = \"{0:0.##} \" + bandwidthScale.unitName;\r\n                trafficChart.ChartAreas[0].AxisY.Maximum = bandwidthScale.value;\r\n                inboundAnnotation.AnchorDataPoint = trafficChart.Series[\"Inbound\"].Points.Last();\r\n                inboundAnnotation.Text = Utils.FormatBandwidth(lastInbound);\r\n                outboundAnnotation.AnchorDataPoint = trafficChart.Series[\"Outbound\"].Points.Last();\r\n                outboundAnnotation.Text = Utils.FormatBandwidth(lastOutbound);\r\n                trafficChart.Annotations.Clear();\r\n                trafficChart.Annotations.Add(inboundAnnotation);\r\n                trafficChart.Annotations.Add(outboundAnnotation);\r\n            }\r\n        }\r\n\r\n        private void controller_TrafficChanged(object sender, EventArgs e)\r\n        {\r\n            lock (_lock)\r\n            {\r\n                if (trafficInfoQueue.Count == 0)\r\n                {\r\n                    // Init an empty queue\r\n                    for (int i = 0; i < queueMaxLength; i++)\r\n                    {\r\n                        trafficInfoQueue.Enqueue(new TrafficInfo(0, 0));\r\n                    }\r\n\r\n                    foreach (var trafficPerSecond in controller.trafficPerSecondQueue)\r\n                    {\r\n                        trafficInfoQueue.Enqueue(new TrafficInfo(trafficPerSecond.inboundIncreasement,\r\n                                                                 trafficPerSecond.outboundIncreasement));\r\n                        if (trafficInfoQueue.Count > queueMaxLength)\r\n                            trafficInfoQueue.Dequeue();\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    var lastTraffic = controller.trafficPerSecondQueue.Last();\r\n                    trafficInfoQueue.Enqueue(new TrafficInfo(lastTraffic.inboundIncreasement,\r\n                                                             lastTraffic.outboundIncreasement));\r\n                    if (trafficInfoQueue.Count > queueMaxLength)\r\n                        trafficInfoQueue.Dequeue();\r\n                }\r\n            }\r\n        }\r\n\r\n        private void UpdateTexts()\r\n        {\r\n            I18N.TranslateForm(this);\r\n            trafficChart.Series[\"Inbound\"].LegendText = I18N.GetString(\"Inbound\");\r\n            trafficChart.Series[\"Outbound\"].LegendText = I18N.GetString(\"Outbound\");\r\n        }\r\n\r\n        private void Timer_Tick(object sender, EventArgs e)\r\n        {\r\n            UpdateContent();\r\n            UpdateTrafficChart();\r\n        }\r\n\r\n        private void InitContent()\r\n        {\r\n            if (string.IsNullOrEmpty(filename) || !File.Exists(filename))\r\n                return;\r\n            using (StreamReader reader = new StreamReader(new FileStream(filename,\r\n                     FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))\r\n            {\r\n                if (reader.BaseStream.Length > BACK_OFFSET)\r\n                {\r\n                    reader.BaseStream.Seek(-BACK_OFFSET, SeekOrigin.End);\r\n                    reader.ReadLine();\r\n                }\r\n\r\n                string line = \"\";\r\n                StringBuilder appendText = new StringBuilder(1024);\r\n                while ((line = reader.ReadLine()) != null)\r\n                    appendText.AppendLine(line);\r\n\r\n                LogMessageTextBox.AppendText(appendText.ToString());\r\n                LogMessageTextBox.ScrollToCaret();\r\n\r\n                lastOffset = reader.BaseStream.Position;\r\n            }\r\n        }\r\n\r\n        private void UpdateContent()\r\n        {\r\n            this.Text = I18N.GetString(\"Log Viewer\") +\r\n                        $\" [in: {Utils.FormatBytes(controller.InboundCounter)}, out: {Utils.FormatBytes(controller.OutboundCounter)}]\";\r\n\r\n            if (string.IsNullOrEmpty(filename) || !File.Exists(filename))\r\n                return;\r\n            try\r\n            {\r\n                using (StreamReader reader = new StreamReader(new FileStream(filename,\r\n                         FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))\r\n                {\r\n                    reader.BaseStream.Seek(lastOffset, SeekOrigin.Begin);\r\n\r\n                    string line = \"\";\r\n                    bool changed = false;\r\n                    StringBuilder appendText = new StringBuilder(128);\r\n                    while ((line = reader.ReadLine()) != null)\r\n                    {\r\n                        changed = true;\r\n                        appendText.AppendLine(line);\r\n                    }\r\n\r\n                    if (changed)\r\n                    {\r\n                        LogMessageTextBox.AppendText(appendText.ToString());\r\n                        LogMessageTextBox.ScrollToCaret();\r\n                    }\r\n\r\n                    lastOffset = reader.BaseStream.Position;\r\n                }\r\n            }\r\n            catch (FileNotFoundException)\r\n            {\r\n            }\r\n        }\r\n\r\n        private void LogForm_Load(object sender, EventArgs e)\r\n        {\r\n            InitContent();\r\n\r\n            timer = new Timer();\r\n            timer.Interval = 100;\r\n            timer.Tick += Timer_Tick;\r\n            timer.Start();\r\n\r\n            LogViewerConfig config = controller.GetCurrentConfiguration().logViewer;\r\n\r\n            Height = config.Height;\r\n            Width = config.Width;\r\n            Top = config.BestTop;\r\n            Left = config.BestLeft;\r\n            if (config.Maximized)\r\n            {\r\n                WindowState = FormWindowState.Maximized;\r\n            }\r\n\r\n            topMostTriggerLock = true;\r\n            TopMost = TopMostMenuItem.Checked = TopMostCheckBox.Checked = topMostTrigger;\r\n            topMostTriggerLock = false;\r\n\r\n            wrapTextTriggerLock = true;\r\n            LogMessageTextBox.WordWrap = WrapTextMenuItem.Checked = WrapTextCheckBox.Checked = wrapTextTrigger;\r\n            wrapTextTriggerLock = false;\r\n\r\n            ToolbarFlowLayoutPanel.Visible = ShowToolbarMenuItem.Checked = toolbarTrigger;\r\n        }\r\n\r\n        private void LogForm_FormClosing(object sender, FormClosingEventArgs e)\r\n        {\r\n            timer.Stop();\r\n            controller.TrafficChanged -= controller_TrafficChanged;\r\n            LogViewerConfig config = controller.GetCurrentConfiguration().logViewer;\r\n\r\n            config.topMost = topMostTrigger;\r\n            config.wrapText = wrapTextTrigger;\r\n            config.toolbarShown = toolbarTrigger;\r\n            config.Font = LogMessageTextBox.Font;\r\n            config.BackgroundColor = LogMessageTextBox.BackColor;\r\n            config.TextColor = LogMessageTextBox.ForeColor;\r\n            if (WindowState != FormWindowState.Minimized && !(config.Maximized = WindowState == FormWindowState.Maximized))\r\n            {\r\n                config.Top = Top;\r\n                config.Left = Left;\r\n                config.Height = Height;\r\n                config.Width = Width;\r\n            }\r\n            controller.SaveLogViewerConfig(config);\r\n        }\r\n\r\n        private void OpenLocationMenuItem_Click(object sender, EventArgs e)\r\n        {\r\n            string argument = \"/select, \\\"\" + filename + \"\\\"\";\r\n            logger.Debug(argument);\r\n            System.Diagnostics.Process.Start(\"explorer.exe\", argument);\r\n        }\r\n\r\n        private void ExitMenuItem_Click(object sender, EventArgs e)\r\n        {\r\n            Close();\r\n        }\r\n\r\n        private void LogForm_Shown(object sender, EventArgs e)\r\n        {\r\n            LogMessageTextBox.ScrollToCaret();\r\n        }\r\n\r\n        #region Clean up the content in LogMessageTextBox.\r\n        private void DoClearLogs()\r\n        {\r\n            try\r\n            {\r\n                File.Delete(filename);\r\n            }\r\n            catch { }\r\n            lastOffset = 0;\r\n            LogMessageTextBox.Clear();\r\n        }\r\n\r\n        private void ClearLogsMenuItem_Click(object sender, EventArgs e)\r\n        {\r\n            DoClearLogs();\r\n        }\r\n\r\n        private void ClearLogsButton_Click(object sender, EventArgs e)\r\n        {\r\n            DoClearLogs();\r\n        }\r\n        #endregion\r\n\r\n        #region Change the font settings applied in LogMessageTextBox.\r\n        private void DoChangeFont()\r\n        {\r\n            try\r\n            {\r\n                FontDialog fd = new FontDialog();\r\n                fd.Font = LogMessageTextBox.Font;\r\n                if (fd.ShowDialog() == DialogResult.OK)\r\n                {\r\n                    LogMessageTextBox.Font = new Font(fd.Font.FontFamily, fd.Font.Size, fd.Font.Style);\r\n                }\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                logger.LogUsefulException(ex);\r\n                MessageBox.Show(ex.Message);\r\n            }\r\n        }\r\n\r\n        private void ChangeFontMenuItem_Click(object sender, EventArgs e)\r\n        {\r\n            DoChangeFont();\r\n        }\r\n\r\n        private void ChangeFontButton_Click(object sender, EventArgs e)\r\n        {\r\n            DoChangeFont();\r\n        }\r\n        #endregion\r\n\r\n        #region Trigger the log messages to wrapable, or not.\r\n        bool wrapTextTrigger = false;\r\n        bool wrapTextTriggerLock = false;\r\n\r\n        private void TriggerWrapText()\r\n        {\r\n            wrapTextTriggerLock = true;\r\n\r\n            wrapTextTrigger = !wrapTextTrigger;\r\n            LogMessageTextBox.WordWrap = wrapTextTrigger;\r\n            LogMessageTextBox.ScrollToCaret();\r\n            WrapTextMenuItem.Checked = WrapTextCheckBox.Checked = wrapTextTrigger;\r\n\r\n            wrapTextTriggerLock = false;\r\n        }\r\n\r\n        private void WrapTextMenuItem_Click(object sender, EventArgs e)\r\n        {\r\n            if (!wrapTextTriggerLock)\r\n            {\r\n                TriggerWrapText();\r\n            }\r\n        }\r\n\r\n        private void WrapTextCheckBox_CheckedChanged(object sender, EventArgs e)\r\n        {\r\n            if (!wrapTextTriggerLock)\r\n            {\r\n                TriggerWrapText();\r\n            }\r\n        }\r\n        #endregion\r\n\r\n        #region Trigger the window to top most, or not.\r\n        bool topMostTrigger = false;\r\n        bool topMostTriggerLock = false;\r\n\r\n        private void TriggerTopMost()\r\n        {\r\n            topMostTriggerLock = true;\r\n\r\n            topMostTrigger = !topMostTrigger;\r\n            TopMost = topMostTrigger;\r\n            TopMostMenuItem.Checked = TopMostCheckBox.Checked = topMostTrigger;\r\n\r\n            topMostTriggerLock = false;\r\n        }\r\n\r\n        private void TopMostCheckBox_CheckedChanged(object sender, EventArgs e)\r\n        {\r\n            if (!topMostTriggerLock)\r\n            {\r\n                TriggerTopMost();\r\n            }\r\n        }\r\n\r\n        private void TopMostMenuItem_Click(object sender, EventArgs e)\r\n        {\r\n            if (!topMostTriggerLock)\r\n            {\r\n                TriggerTopMost();\r\n            }\r\n        }\r\n        #endregion\r\n\r\n        private bool toolbarTrigger = false;\r\n\r\n        private void ShowToolbarMenuItem_Click(object sender, EventArgs e)\r\n        {\r\n            toolbarTrigger = !toolbarTrigger;\r\n            ToolbarFlowLayoutPanel.Visible = toolbarTrigger;\r\n            ShowToolbarMenuItem.Checked = toolbarTrigger;\r\n        }\r\n\r\n        private class TrafficInfo\r\n        {\r\n            public long inbound;\r\n            public long outbound;\r\n\r\n            public TrafficInfo(long inbound, long outbound)\r\n            {\r\n                this.inbound = inbound;\r\n                this.outbound = outbound;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/View/LogForm.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<root>\r\n  <!-- \r\n    Microsoft ResX Schema \r\n    \r\n    Version 2.0\r\n    \r\n    The primary goals of this format is to allow a simple XML format \r\n    that is mostly human readable. The generation and parsing of the \r\n    various data types are done through the TypeConverter classes \r\n    associated with the data types.\r\n    \r\n    Example:\r\n    \r\n    ... ado.net/XML headers & schema ...\r\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\r\n    <resheader name=\"version\">2.0</resheader>\r\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\r\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\r\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\r\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\r\n    </data>\r\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\r\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r\n        <comment>This is a comment</comment>\r\n    </data>\r\n                \r\n    There are any number of \"resheader\" rows that contain simple \r\n    name/value pairs.\r\n    \r\n    Each data row contains a name, and value. The row also contains a \r\n    type or mimetype. Type corresponds to a .NET class that support \r\n    text/value conversion through the TypeConverter architecture. \r\n    Classes that don't support this are serialized and stored with the \r\n    mimetype set.\r\n    \r\n    The mimetype is used for serialized objects, and tells the \r\n    ResXResourceReader how to depersist the object. This is currently not \r\n    extensible. For a given mimetype the value must be set accordingly:\r\n    \r\n    Note - application/x-microsoft.net.object.binary.base64 is the format \r\n    that the ResXResourceWriter will generate, however the reader can \r\n    read any of the formats listed below.\r\n    \r\n    mimetype: application/x-microsoft.net.object.binary.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r\n            : and then encoded with base64 encoding.\r\n    \r\n    mimetype: application/x-microsoft.net.object.soap.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r\n            : and then encoded with base64 encoding.\r\n\r\n    mimetype: application/x-microsoft.net.object.bytearray.base64\r\n    value   : The object must be serialized into a byte array \r\n            : using a System.ComponentModel.TypeConverter\r\n            : and then encoded with base64 encoding.\r\n    -->\r\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\r\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\r\n      <xsd:complexType>\r\n        <xsd:choice maxOccurs=\"unbounded\">\r\n          <xsd:element name=\"metadata\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"assembly\">\r\n            <xsd:complexType>\r\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"data\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"resheader\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n        </xsd:choice>\r\n      </xsd:complexType>\r\n    </xsd:element>\r\n  </xsd:schema>\r\n  <resheader name=\"resmimetype\">\r\n    <value>text/microsoft-resx</value>\r\n  </resheader>\r\n  <resheader name=\"version\">\r\n    <value>2.0</value>\r\n  </resheader>\r\n  <resheader name=\"reader\">\r\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <resheader name=\"writer\">\r\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <metadata name=\"LogMessageTextBox.Locked\" type=\"System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\r\n    <value>True</value>\r\n  </metadata>\r\n  <metadata name=\"MainMenu.TrayLocation\" type=\"System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\">\r\n    <value>17, 17</value>\r\n  </metadata>\r\n  <metadata name=\"TopMostCheckBox.Locked\" type=\"System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\r\n    <value>True</value>\r\n  </metadata>\r\n  <metadata name=\"ChangeFontButton.Locked\" type=\"System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\r\n    <value>True</value>\r\n  </metadata>\r\n  <metadata name=\"ClearLogsButton.Locked\" type=\"System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\r\n    <value>True</value>\r\n  </metadata>\r\n  <metadata name=\"WrapTextCheckBox.Locked\" type=\"System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\r\n    <value>True</value>\r\n  </metadata>\r\n  <metadata name=\"tableLayoutPanel1.Locked\" type=\"System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\r\n    <value>True</value>\r\n  </metadata>\r\n  <metadata name=\"ToolbarFlowLayoutPanel.Locked\" type=\"System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\r\n    <value>True</value>\r\n  </metadata>\r\n  <metadata name=\"$this.Locked\" type=\"System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\r\n    <value>True</value>\r\n  </metadata>\r\n  <metadata name=\"$this.TrayHeight\" type=\"System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\r\n    <value>39</value>\r\n  </metadata>\r\n</root>"
  },
  {
    "path": "shadowsocks-csharp/View/MenuViewController.cs",
    "content": "﻿using NLog;\r\nusing Shadowsocks.Controller;\r\nusing Shadowsocks.Localization;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Properties;\r\nusing Shadowsocks.Util;\r\nusing Shadowsocks.Views;\r\nusing System;\r\nusing System.Diagnostics;\r\nusing System.Drawing;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Windows.Forms;\r\nusing System.Windows.Forms.Integration;\r\nusing System.Windows.Threading;\r\nusing ZXing;\r\nusing ZXing.Common;\r\nusing ZXing.QrCode;\r\n\r\nnamespace Shadowsocks.View\r\n{\r\n    public class MenuViewController\r\n    {\r\n        private readonly Logger logger = LogManager.GetCurrentClassLogger();\r\n\r\n        private ShadowsocksController controller;\r\n        public UpdateChecker updateChecker;\r\n\r\n        private NotifyIcon _notifyIcon;\r\n        private Icon icon, icon_in, icon_out, icon_both, previousIcon;\r\n\r\n        private bool _isStartupCheck;\r\n        private string _urlToOpen;\r\n\r\n        private ContextMenu contextMenu1;\r\n        private MenuItem disableItem;\r\n        private MenuItem AutoStartupItem;\r\n        private MenuItem ProtocolHandlerItem;\r\n        private MenuItem ShareOverLANItem;\r\n        private MenuItem SeperatorItem;\r\n        private MenuItem ConfigItem;\r\n        private MenuItem ServersItem;\r\n        private MenuItem globalModeItem;\r\n        private MenuItem PACModeItem;\r\n        private MenuItem localPACItem;\r\n        private MenuItem onlinePACItem;\r\n        private MenuItem editLocalPACItem;\r\n        private MenuItem updateFromGeositeItem;\r\n        private MenuItem editGFWUserRuleItem;\r\n        private MenuItem editOnlinePACItem;\r\n        private MenuItem secureLocalPacUrlToggleItem;\r\n        private MenuItem regenerateLocalPacOnUpdateItem;\r\n        private MenuItem autoCheckUpdatesToggleItem;\r\n        private MenuItem checkPreReleaseToggleItem;\r\n        private MenuItem proxyItem;\r\n        private MenuItem hotKeyItem;\r\n        private MenuItem VerboseLoggingToggleItem;\r\n        private MenuItem ShowPluginOutputToggleItem;\r\n        private MenuItem WriteI18NFileItem;\r\n        private MenuItem onlineConfigItem;\r\n\r\n        private ConfigForm configForm;\r\n        private LogForm logForm;\r\n\r\n        private System.Windows.Window serverSharingWindow;\r\n        private System.Windows.Window hotkeysWindow;\r\n        private System.Windows.Window forwardProxyWindow;\r\n        private System.Windows.Window onlineConfigWindow;\r\n\r\n        // color definition for icon color transformation\r\n        private readonly Color colorMaskBlue = Color.FromArgb(255, 25, 125, 191);\r\n        private readonly Color colorMaskDarkSilver = Color.FromArgb(128, 192, 192, 192);\r\n        private readonly Color colorMaskLightSilver = Color.FromArgb(192, 192, 192);\r\n        private readonly Color colorMaskEclipse = Color.FromArgb(192, 64, 64, 64);\r\n\r\n        public MenuViewController(ShadowsocksController controller)\r\n        {\r\n            this.controller = controller;\r\n\r\n            LoadMenu();\r\n\r\n            controller.EnableStatusChanged += controller_EnableStatusChanged;\r\n            controller.ConfigChanged += controller_ConfigChanged;\r\n            controller.PACFileReadyToOpen += controller_FileReadyToOpen;\r\n            controller.UserRuleFileReadyToOpen += controller_FileReadyToOpen;\r\n            controller.ShareOverLANStatusChanged += controller_ShareOverLANStatusChanged;\r\n            controller.VerboseLoggingStatusChanged += controller_VerboseLoggingStatusChanged;\r\n            controller.ShowPluginOutputChanged += controller_ShowPluginOutputChanged;\r\n            controller.EnableGlobalChanged += controller_EnableGlobalChanged;\r\n            controller.Errored += controller_Errored;\r\n            controller.UpdatePACFromGeositeCompleted += controller_UpdatePACFromGeositeCompleted;\r\n            controller.UpdatePACFromGeositeError += controller_UpdatePACFromGeositeError;\r\n\r\n            _notifyIcon = new NotifyIcon();\r\n            UpdateTrayIconAndNotifyText();\r\n            _notifyIcon.Visible = true;\r\n            _notifyIcon.ContextMenu = contextMenu1;\r\n            _notifyIcon.BalloonTipClicked += notifyIcon1_BalloonTipClicked;\r\n            _notifyIcon.MouseClick += notifyIcon1_Click;\r\n            _notifyIcon.MouseDoubleClick += notifyIcon1_DoubleClick;\r\n            _notifyIcon.BalloonTipClosed += _notifyIcon_BalloonTipClosed;\r\n            controller.TrafficChanged += controller_TrafficChanged;\r\n\r\n            updateChecker = new UpdateChecker();\r\n            updateChecker.CheckUpdateCompleted += updateChecker_CheckUpdateCompleted;\r\n\r\n            LoadCurrentConfiguration();\r\n\r\n            Configuration config = controller.GetCurrentConfiguration();\r\n\r\n            if (config.firstRun)\r\n            {\r\n                ShowConfigForm();\r\n            }\r\n            else if (config.autoCheckUpdate)\r\n            {\r\n                _isStartupCheck = true;\r\n                Dispatcher.CurrentDispatcher.Invoke(() => updateChecker.CheckForVersionUpdate(3000));\r\n            }\r\n        }\r\n\r\n        #region Tray Icon\r\n\r\n        private void UpdateTrayIconAndNotifyText()\r\n        {\r\n            Configuration config = controller.GetCurrentConfiguration();\r\n            bool enabled = config.enabled;\r\n            bool global = config.global;\r\n\r\n            Color colorMask = SelectColorMask(enabled, global);\r\n            Size iconSize = SelectIconSize();\r\n\r\n            UpdateIconSet(colorMask, iconSize, out icon, out icon_in, out icon_out, out icon_both);\r\n\r\n            previousIcon = icon;\r\n            _notifyIcon.Icon = previousIcon;\r\n\r\n            string serverInfo = null;\r\n            if (controller.GetCurrentStrategy() != null)\r\n            {\r\n                serverInfo = controller.GetCurrentStrategy().Name;\r\n            }\r\n            else\r\n            {\r\n                serverInfo = config.GetCurrentServer().ToString();\r\n            }\r\n            // show more info by hacking the P/Invoke declaration for NOTIFYICONDATA inside Windows Forms\r\n            string text = I18N.GetString(\"Shadowsocks\") + \" \" + UpdateChecker.Version + \"\\n\" +\r\n                          (enabled ?\r\n                              I18N.GetString(\"System Proxy On: \") + (global ? I18N.GetString(\"Global\") : I18N.GetString(\"PAC\")) :\r\n                              I18N.GetString(\"Running: Port {0}\", config.localPort))  // this feedback is very important because they need to know Shadowsocks is running\r\n                          + \"\\n\" + serverInfo;\r\n            if (text.Length > 127)\r\n            {\r\n                text = text.Substring(0, 126 - 3) + \"...\";\r\n            }\r\n            ViewUtils.SetNotifyIconText(_notifyIcon, text);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determine the icon size based on the screen DPI.\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        /// https://stackoverflow.com/a/40851713/2075611\r\n        private Size SelectIconSize()\r\n        {\r\n            Size size = new Size(32, 32);\r\n            int dpi = ViewUtils.GetScreenDpi();\r\n            if (dpi < 97)\r\n            {\r\n                // dpi = 96;\r\n                size = new Size(16, 16);\r\n            }\r\n            else if (dpi < 121)\r\n            {\r\n                // dpi = 120;\r\n                size = new Size(20, 20);\r\n            }\r\n            else if (dpi < 145)\r\n            {\r\n                // dpi = 144;\r\n                size = new Size(24, 24);\r\n            }\r\n            else\r\n            {\r\n                // dpi = 168;\r\n                size = new Size(28, 28);\r\n            }\r\n            return size;\r\n        }\r\n\r\n        private Color SelectColorMask(bool isProxyEnabled, bool isGlobalProxy)\r\n        {\r\n            Color colorMask = Color.White;\r\n\r\n            Utils.WindowsThemeMode currentWindowsThemeMode = Utils.GetWindows10SystemThemeSetting();\r\n\r\n            if (isProxyEnabled)\r\n            {\r\n                if (isGlobalProxy)  // global\r\n                {\r\n                    colorMask = colorMaskBlue;\r\n                }\r\n                else  // PAC\r\n                {\r\n                    if (currentWindowsThemeMode == Utils.WindowsThemeMode.Light)\r\n                    {\r\n                        colorMask = colorMaskEclipse;\r\n                    }\r\n                }\r\n            }\r\n            else  // disabled\r\n            {\r\n                if (currentWindowsThemeMode == Utils.WindowsThemeMode.Light)\r\n                {\r\n                    colorMask = colorMaskDarkSilver;\r\n                }\r\n                else\r\n                {\r\n                    colorMask = colorMaskLightSilver;\r\n                }\r\n            }\r\n\r\n            return colorMask;\r\n        }\r\n\r\n        private void UpdateIconSet(Color colorMask, Size size,\r\n            out Icon icon, out Icon icon_in, out Icon icon_out, out Icon icon_both)\r\n        {\r\n            Bitmap iconBitmap;\r\n\r\n            // generate the base icon\r\n            iconBitmap = ViewUtils.ChangeBitmapColor(Resources.ss32Fill, colorMask);\r\n            iconBitmap = ViewUtils.AddBitmapOverlay(iconBitmap, Resources.ss32Outline);\r\n\r\n            icon = Icon.FromHandle(ViewUtils.ResizeBitmap(iconBitmap, size.Width, size.Height).GetHicon());\r\n            icon_in = Icon.FromHandle(ViewUtils.ResizeBitmap(ViewUtils.AddBitmapOverlay(iconBitmap, Resources.ss32In), size.Width, size.Height).GetHicon());\r\n            icon_out = Icon.FromHandle(ViewUtils.ResizeBitmap(ViewUtils.AddBitmapOverlay(iconBitmap, Resources.ss32In), size.Width, size.Height).GetHicon());\r\n            icon_both = Icon.FromHandle(ViewUtils.ResizeBitmap(ViewUtils.AddBitmapOverlay(iconBitmap, Resources.ss32In, Resources.ss32Out), size.Width, size.Height).GetHicon());\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region MenuItems and MenuGroups\r\n\r\n        private MenuItem CreateMenuItem(string text, EventHandler click)\r\n        {\r\n            return new MenuItem(I18N.GetString(text), click);\r\n        }\r\n\r\n        private MenuItem CreateMenuGroup(string text, MenuItem[] items)\r\n        {\r\n            return new MenuItem(I18N.GetString(text), items);\r\n        }\r\n\r\n        private void LoadMenu()\r\n        {\r\n            this.contextMenu1 = new ContextMenu(new MenuItem[] {\r\n                CreateMenuGroup(\"System Proxy\", new MenuItem[] {\r\n                    this.disableItem = CreateMenuItem(\"Disable\", new EventHandler(this.EnableItem_Click)),\r\n                    this.PACModeItem = CreateMenuItem(\"PAC\", new EventHandler(this.PACModeItem_Click)),\r\n                    this.globalModeItem = CreateMenuItem(\"Global\", new EventHandler(this.GlobalModeItem_Click))\r\n                }),\r\n                this.ServersItem = CreateMenuGroup(\"Servers\", new MenuItem[] {\r\n                    this.SeperatorItem = new MenuItem(\"-\"),\r\n                    this.ConfigItem = CreateMenuItem(\"Edit Servers...\", new EventHandler(this.Config_Click)),\r\n                    new MenuItem(\"-\"),\r\n                    CreateMenuItem(\"Share Server Config...\", new EventHandler(this.QRCodeItem_Click)),\r\n                    CreateMenuItem(\"Scan QRCode from Screen...\", new EventHandler(this.ScanQRCodeItem_Click)),\r\n                    CreateMenuItem(\"Import URL from Clipboard...\", new EventHandler(this.ImportURLItem_Click))\r\n                }),\r\n                CreateMenuGroup(\"PAC \", new MenuItem[] {\r\n                    this.localPACItem = CreateMenuItem(\"Local PAC\", new EventHandler(this.LocalPACItem_Click)),\r\n                    this.onlinePACItem = CreateMenuItem(\"Online PAC\", new EventHandler(this.OnlinePACItem_Click)),\r\n                    new MenuItem(\"-\"),\r\n                    this.editLocalPACItem = CreateMenuItem(\"Edit Local PAC File...\", new EventHandler(this.EditPACFileItem_Click)),\r\n                    this.updateFromGeositeItem = CreateMenuItem(\"Update Local PAC from Geosite\", new EventHandler(this.UpdatePACFromGeositeItem_Click)),\r\n                    this.editGFWUserRuleItem = CreateMenuItem(\"Edit User Rule for Geosite...\", new EventHandler(this.EditUserRuleFileForGeositeItem_Click)),\r\n                    this.secureLocalPacUrlToggleItem = CreateMenuItem(\"Secure Local PAC\", new EventHandler(this.SecureLocalPacUrlToggleItem_Click)),\r\n                    this.regenerateLocalPacOnUpdateItem = CreateMenuItem(\"Regenerate local PAC on version update\", new EventHandler(this.RegenerateLocalPacOnUpdateItem_Click)),\r\n                    CreateMenuItem(\"Copy Local PAC URL\", new EventHandler(this.CopyLocalPacUrlItem_Click)),\r\n                    this.editOnlinePACItem = CreateMenuItem(\"Edit Online PAC URL...\", new EventHandler(this.UpdateOnlinePACURLItem_Click)),\r\n                }),\r\n                this.proxyItem = CreateMenuItem(\"Forward Proxy...\", new EventHandler(this.proxyItem_Click)),\r\n                this.onlineConfigItem = CreateMenuItem(\"Online Config...\", new EventHandler(this.OnlineConfig_Click)),\r\n                new MenuItem(\"-\"),\r\n                this.AutoStartupItem = CreateMenuItem(\"Start on Boot\", new EventHandler(this.AutoStartupItem_Click)),\r\n                this.ProtocolHandlerItem = CreateMenuItem(\"Associate ss:// Links\", new EventHandler(this.ProtocolHandlerItem_Click)),\r\n                this.ShareOverLANItem = CreateMenuItem(\"Allow other Devices to connect\", new EventHandler(this.ShareOverLANItem_Click)),\r\n                new MenuItem(\"-\"),\r\n                this.hotKeyItem = CreateMenuItem(\"Edit Hotkeys...\", new EventHandler(this.hotKeyItem_Click)),\r\n                CreateMenuGroup(\"Help\", new MenuItem[] {\r\n                    CreateMenuItem(\"Show Logs...\", new EventHandler(this.ShowLogItem_Click)),\r\n                    this.VerboseLoggingToggleItem = CreateMenuItem( \"Verbose Logging\", new EventHandler(this.VerboseLoggingToggleItem_Click) ),\r\n                    this.ShowPluginOutputToggleItem = CreateMenuItem(\"Show Plugin Output\", new EventHandler(this.ShowPluginOutputToggleItem_Click)),\r\n                    this.WriteI18NFileItem = CreateMenuItem(\"Write translation template\",new EventHandler(WriteI18NFileItem_Click)),\r\n                    CreateMenuGroup(\"Updates...\", new MenuItem[] {\r\n                        CreateMenuItem(\"Check for Updates...\", new EventHandler(this.checkUpdatesItem_Click)),\r\n                        new MenuItem(\"-\"),\r\n                        this.autoCheckUpdatesToggleItem = CreateMenuItem(\"Check for Updates at Startup\", new EventHandler(this.autoCheckUpdatesToggleItem_Click)),\r\n                        this.checkPreReleaseToggleItem = CreateMenuItem(\"Check Pre-release Version\", new EventHandler(this.checkPreReleaseToggleItem_Click)),\r\n                    }),\r\n                    CreateMenuItem(\"About...\", new EventHandler(this.AboutItem_Click)),\r\n                }),\r\n                new MenuItem(\"-\"),\r\n                CreateMenuItem(\"Quit\", new EventHandler(this.Quit_Click))\r\n            });\r\n        }\r\n\r\n        #endregion\r\n\r\n        private void controller_TrafficChanged(object sender, EventArgs e)\r\n        {\r\n            if (icon == null)\r\n                return;\r\n\r\n            Icon newIcon;\r\n\r\n            bool hasInbound = controller.trafficPerSecondQueue.Last().inboundIncreasement > 0;\r\n            bool hasOutbound = controller.trafficPerSecondQueue.Last().outboundIncreasement > 0;\r\n\r\n            if (hasInbound && hasOutbound)\r\n                newIcon = icon_both;\r\n            else if (hasInbound)\r\n                newIcon = icon_in;\r\n            else if (hasOutbound)\r\n                newIcon = icon_out;\r\n            else\r\n                newIcon = icon;\r\n\r\n            if (newIcon != this.previousIcon)\r\n            {\r\n                this.previousIcon = newIcon;\r\n                _notifyIcon.Icon = newIcon;\r\n            }\r\n        }\r\n\r\n        void controller_Errored(object sender, ErrorEventArgs e)\r\n        {\r\n            MessageBox.Show(e.GetException().ToString(), I18N.GetString(\"Shadowsocks Error: {0}\", e.GetException().Message));\r\n        }\r\n\r\n        private void controller_ConfigChanged(object sender, EventArgs e)\r\n        {\r\n            LoadCurrentConfiguration();\r\n            UpdateTrayIconAndNotifyText();\r\n        }\r\n\r\n        private void LoadCurrentConfiguration()\r\n        {\r\n            Configuration config = controller.GetCurrentConfiguration();\r\n            UpdateServersMenu();\r\n            UpdateSystemProxyItemsEnabledStatus(config);\r\n            ShareOverLANItem.Checked = config.shareOverLan;\r\n            VerboseLoggingToggleItem.Checked = config.isVerboseLogging;\r\n            ShowPluginOutputToggleItem.Checked = config.showPluginOutput;\r\n            AutoStartupItem.Checked = AutoStartup.Check();\r\n            ProtocolHandlerItem.Checked = ProtocolHandler.Check();\r\n            onlinePACItem.Checked = onlinePACItem.Enabled && config.useOnlinePac;\r\n            localPACItem.Checked = !onlinePACItem.Checked;\r\n            secureLocalPacUrlToggleItem.Checked = config.secureLocalPac;\r\n            regenerateLocalPacOnUpdateItem.Checked = config.regeneratePacOnUpdate;\r\n            UpdatePACItemsEnabledStatus();\r\n            UpdateUpdateMenu();\r\n        }\r\n\r\n        #region Forms\r\n\r\n        private void ShowConfigForm()\r\n        {\r\n            if (configForm != null)\r\n            {\r\n                configForm.Activate();\r\n            }\r\n            else\r\n            {\r\n                configForm = new ConfigForm(controller);\r\n                configForm.Show();\r\n                configForm.Activate();\r\n                configForm.FormClosed += configForm_FormClosed;\r\n            }\r\n        }\r\n\r\n        private void ShowLogForm()\r\n        {\r\n            if (logForm != null)\r\n            {\r\n                logForm.Activate();\r\n            }\r\n            else\r\n            {\r\n                logForm = new LogForm(controller);\r\n                logForm.Show();\r\n                logForm.Activate();\r\n                logForm.FormClosed += logForm_FormClosed;\r\n            }\r\n        }\r\n\r\n        void logForm_FormClosed(object sender, FormClosedEventArgs e)\r\n        {\r\n            logForm.Dispose();\r\n            logForm = null;\r\n        }\r\n\r\n        void configForm_FormClosed(object sender, FormClosedEventArgs e)\r\n        {\r\n            configForm.Dispose();\r\n            configForm = null;\r\n            var config = controller.GetCurrentConfiguration();\r\n            if (config.firstRun)\r\n            {\r\n                CheckUpdateForFirstRun();\r\n                ShowBalloonTip(\r\n                    I18N.GetString(\"Shadowsocks is here\"),\r\n                    I18N.GetString(\"You can turn on/off Shadowsocks in the context menu\"),\r\n                    ToolTipIcon.Info,\r\n                    0\r\n                );\r\n                config.firstRun = false;\r\n            }\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Misc\r\n\r\n        void ShowBalloonTip(string title, string content, ToolTipIcon icon, int timeout)\r\n        {\r\n            _notifyIcon.BalloonTipTitle = title;\r\n            _notifyIcon.BalloonTipText = content;\r\n            _notifyIcon.BalloonTipIcon = icon;\r\n            _notifyIcon.ShowBalloonTip(timeout);\r\n        }\r\n\r\n        void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)\r\n        {\r\n        }\r\n\r\n        private void _notifyIcon_BalloonTipClosed(object sender, EventArgs e)\r\n        {\r\n        }\r\n\r\n        private void notifyIcon1_Click(object sender, MouseEventArgs e)\r\n        {\r\n            UpdateTrayIconAndNotifyText();\r\n            if (e.Button == MouseButtons.Middle)\r\n            {\r\n                ShowLogForm();\r\n            }\r\n        }\r\n\r\n        private void notifyIcon1_DoubleClick(object sender, MouseEventArgs e)\r\n        {\r\n            if (e.Button == MouseButtons.Left)\r\n            {\r\n                ShowConfigForm();\r\n            }\r\n        }\r\n\r\n        private void CheckUpdateForFirstRun()\r\n        {\r\n            Configuration config = controller.GetCurrentConfiguration();\r\n            if (config.firstRun)\r\n                return;\r\n            _isStartupCheck = true;\r\n            Dispatcher.CurrentDispatcher.Invoke(() => updateChecker.CheckForVersionUpdate(3000));\r\n        }\r\n\r\n        public void ShowLogForm_HotKey()\r\n        {\r\n            ShowLogForm();\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Main menu\r\n\r\n        void controller_ShareOverLANStatusChanged(object sender, EventArgs e)\r\n        {\r\n            ShareOverLANItem.Checked = controller.GetCurrentConfiguration().shareOverLan;\r\n        }\r\n\r\n        private void proxyItem_Click(object sender, EventArgs e)\r\n        {\r\n            if (forwardProxyWindow == null)\r\n            {\r\n                forwardProxyWindow = new System.Windows.Window()\r\n                {\r\n                    Title = LocalizationProvider.GetLocalizedValue<string>(\"ForwardProxy\"),\r\n                    Height = 400,\r\n                    Width = 280,\r\n                    MinHeight = 400,\r\n                    MinWidth = 280,\r\n                    Content = new ForwardProxyView()\r\n                };\r\n                forwardProxyWindow.Closed += ForwardProxyWindow_Closed;\r\n                ElementHost.EnableModelessKeyboardInterop(forwardProxyWindow);\r\n                forwardProxyWindow.Show();\r\n            }\r\n            forwardProxyWindow.Activate();\r\n        }\r\n\r\n        private void ForwardProxyWindow_Closed(object sender, EventArgs e)\r\n        {\r\n            forwardProxyWindow = null;\r\n        }\r\n\r\n        public void CloseForwardProxyWindow() => forwardProxyWindow.Close();\r\n\r\n        private void OnlineConfig_Click(object sender, EventArgs e)\r\n        {\r\n            if (onlineConfigWindow == null)\r\n            {\r\n                onlineConfigWindow = new System.Windows.Window()\r\n                {\r\n                    Title = LocalizationProvider.GetLocalizedValue<string>(\"OnlineConfigDelivery\"),\r\n                    Height = 510,\r\n                    Width = 480,\r\n                    MinHeight = 510,\r\n                    MinWidth = 480,\r\n                    Content = new OnlineConfigView()\r\n                };\r\n                onlineConfigWindow.Closed += OnlineConfigWindow_Closed;\r\n                ElementHost.EnableModelessKeyboardInterop(onlineConfigWindow);\r\n                onlineConfigWindow.Show();\r\n            }\r\n            onlineConfigWindow.Activate();\r\n        }\r\n\r\n        private void OnlineConfigWindow_Closed(object sender, EventArgs e)\r\n        {\r\n            onlineConfigWindow = null;\r\n        }\r\n\r\n        private void hotKeyItem_Click(object sender, EventArgs e)\r\n        {\r\n            if (hotkeysWindow == null)\r\n            {\r\n                hotkeysWindow = new System.Windows.Window()\r\n                {\r\n                    Title = LocalizationProvider.GetLocalizedValue<string>(\"Hotkeys\"),\r\n                    Height = 260,\r\n                    Width = 320,\r\n                    MinHeight = 260,\r\n                    MinWidth = 320,\r\n                    Content = new HotkeysView()\r\n                };\r\n                hotkeysWindow.Closed += HotkeysWindow_Closed;\r\n                ElementHost.EnableModelessKeyboardInterop(hotkeysWindow);\r\n                hotkeysWindow.Show();\r\n            }\r\n            hotkeysWindow.Activate();\r\n        }\r\n\r\n        private void HotkeysWindow_Closed(object sender, EventArgs e)\r\n        {\r\n            hotkeysWindow = null;\r\n        }\r\n\r\n        public void CloseHotkeysWindow() => hotkeysWindow.Close();\r\n\r\n        private void ShareOverLANItem_Click(object sender, EventArgs e)\r\n        {\r\n            ShareOverLANItem.Checked = !ShareOverLANItem.Checked;\r\n            controller.ToggleShareOverLAN(ShareOverLANItem.Checked);\r\n        }\r\n\r\n        private void AutoStartupItem_Click(object sender, EventArgs e)\r\n        {\r\n            AutoStartupItem.Checked = !AutoStartupItem.Checked;\r\n            if (!AutoStartup.Set(AutoStartupItem.Checked))\r\n            {\r\n                MessageBox.Show(I18N.GetString(\"Failed to update registry\"));\r\n            }\r\n            LoadCurrentConfiguration();\r\n        }\r\n\r\n        private void ProtocolHandlerItem_Click(object sender, EventArgs e)\r\n        {\r\n            ProtocolHandlerItem.Checked = !ProtocolHandlerItem.Checked;\r\n            if (!ProtocolHandler.Set(ProtocolHandlerItem.Checked))\r\n            {\r\n                MessageBox.Show(I18N.GetString(\"Failed to update registry\"));\r\n            }\r\n            LoadCurrentConfiguration();\r\n        }\r\n\r\n        private void Quit_Click(object sender, EventArgs e)\r\n        {\r\n            controller.Stop();\r\n            _notifyIcon.Visible = false;\r\n            Application.Exit();\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region System proxy\r\n\r\n        private void controller_EnableStatusChanged(object sender, EventArgs e)\r\n        {\r\n            disableItem.Checked = !controller.GetCurrentConfiguration().enabled;\r\n        }\r\n\r\n        private void EnableItem_Click(object sender, EventArgs e)\r\n        {\r\n            controller.ToggleEnable(false);\r\n            Configuration config = controller.GetCurrentConfiguration();\r\n            UpdateSystemProxyItemsEnabledStatus(config);\r\n        }\r\n\r\n        void controller_EnableGlobalChanged(object sender, EventArgs e)\r\n        {\r\n            globalModeItem.Checked = controller.GetCurrentConfiguration().global;\r\n            PACModeItem.Checked = !globalModeItem.Checked;\r\n        }\r\n\r\n        private void UpdateSystemProxyItemsEnabledStatus(Configuration config)\r\n        {\r\n            disableItem.Checked = !config.enabled;\r\n            if (!config.enabled)\r\n            {\r\n                globalModeItem.Checked = false;\r\n                PACModeItem.Checked = false;\r\n            }\r\n            else\r\n            {\r\n                globalModeItem.Checked = config.global;\r\n                PACModeItem.Checked = !config.global;\r\n            }\r\n        }\r\n\r\n        private void GlobalModeItem_Click(object sender, EventArgs e)\r\n        {\r\n            controller.ToggleEnable(true);\r\n            controller.ToggleGlobal(true);\r\n            Configuration config = controller.GetCurrentConfiguration();\r\n            UpdateSystemProxyItemsEnabledStatus(config);\r\n        }\r\n\r\n        private void PACModeItem_Click(object sender, EventArgs e)\r\n        {\r\n            controller.ToggleEnable(true);\r\n            controller.ToggleGlobal(false);\r\n            Configuration config = controller.GetCurrentConfiguration();\r\n            UpdateSystemProxyItemsEnabledStatus(config);\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Server\r\n\r\n        private void UpdateServersMenu()\r\n        {\r\n            var items = ServersItem.MenuItems;\r\n            while (items[0] != SeperatorItem)\r\n            {\r\n                items.RemoveAt(0);\r\n            }\r\n            int strategyCount = 0;\r\n            foreach (var strategy in controller.GetStrategies())\r\n            {\r\n                MenuItem item = new MenuItem(strategy.Name);\r\n                item.Tag = strategy.ID;\r\n                item.Click += AStrategyItem_Click;\r\n                items.Add(strategyCount, item);\r\n                strategyCount++;\r\n            }\r\n\r\n            // user wants a seperator item between strategy and servers menugroup\r\n            items.Add(strategyCount++, new MenuItem(\"-\"));\r\n\r\n            int maxCount = 20;\r\n            int serverCount = 0;\r\n            bool overflow = false;\r\n            bool needAdd = true;\r\n            \r\n            Configuration configuration = controller.GetCurrentConfiguration();\r\n            for (int i = 0; i < configuration.configs.Count; i++)\r\n            {\r\n                try\r\n                {\r\n                    if (overflow)\r\n                    {\r\n                        needAdd = configuration.index >= i;\r\n                        if (needAdd)\r\n                        {\r\n                            i = configuration.index;\r\n                        }\r\n                    }\r\n\r\n                    if (needAdd)\r\n                    {\r\n                        var server = configuration.configs[i];\r\n                        Configuration.CheckServer(server);\r\n                        var item = new MenuItem(server.ToString());\r\n                        item.Tag = i;\r\n                        item.Click += AServerItem_Click;\r\n                        items.Add(strategyCount + serverCount, item);\r\n                        serverCount++;\r\n                    }\r\n                    \r\n                    if (overflow)\r\n                    {\r\n                        items.Add(strategyCount + serverCount, new MenuItem($\"... more than {maxCount} (total {configuration.configs.Count})\", Config_Click));\r\n                        break;\r\n                    }\r\n\r\n                    overflow = serverCount > maxCount;\r\n                }\r\n                catch\r\n                {\r\n                }\r\n            }\r\n\r\n            foreach (MenuItem item in items)\r\n            {\r\n                if (item.Tag != null && (item.Tag.ToString() == configuration.index.ToString() || item.Tag.ToString() == configuration.strategy))\r\n                {\r\n                    item.Checked = true;\r\n                }\r\n            }\r\n        }\r\n\r\n        private void AServerItem_Click(object sender, EventArgs e)\r\n        {\r\n            MenuItem item = (MenuItem)sender;\r\n            controller.SelectServerIndex((int)item.Tag);\r\n        }\r\n\r\n        private void AStrategyItem_Click(object sender, EventArgs e)\r\n        {\r\n            MenuItem item = (MenuItem)sender;\r\n            controller.SelectStrategy((string)item.Tag);\r\n        }\r\n\r\n        private void Config_Click(object sender, EventArgs e)\r\n        {\r\n            ShowConfigForm();\r\n        }\r\n\r\n        void openURLFromQRCode()\r\n        {\r\n            Process.Start(_urlToOpen);\r\n        }\r\n\r\n        private void QRCodeItem_Click(object sender, EventArgs e)\r\n        {\r\n            if (serverSharingWindow == null)\r\n            {\r\n                serverSharingWindow = new System.Windows.Window()\r\n                {\r\n                    Title = LocalizationProvider.GetLocalizedValue<string>(\"ServerSharing\"),\r\n                    Height = 400,\r\n                    Width = 660,\r\n                    MinHeight = 400,\r\n                    MinWidth = 660,\r\n                    Content = new ServerSharingView()\r\n                };\r\n                serverSharingWindow.Closed += ServerSharingWindow_Closed;\r\n                ElementHost.EnableModelessKeyboardInterop(serverSharingWindow);\r\n                serverSharingWindow.Show();\r\n            }\r\n            serverSharingWindow.Activate();\r\n        }\r\n\r\n        private void ServerSharingWindow_Closed(object sender, EventArgs e)\r\n        {\r\n            serverSharingWindow = null;\r\n        }\r\n\r\n        private void ScanQRCodeItem_Click(object sender, EventArgs e)\r\n        {\r\n            var result = Utils.ScanQRCodeFromScreen();\r\n            if (result != null)\r\n            {\r\n                if (result.ToLowerInvariant().StartsWith(\"http://\") || result.ToLowerInvariant().StartsWith(\"https://\"))\r\n                {\r\n                    _urlToOpen = result;\r\n                    openURLFromQRCode();\r\n                }\r\n                else if (controller.AddServerBySSURL(result))\r\n                {\r\n                    ShowConfigForm();\r\n                }\r\n                else\r\n                {\r\n                    MessageBox.Show(I18N.GetString(\"Invalid QR Code content: {0}\", result));\r\n                }\r\n                return;\r\n            }\r\n            else\r\n                MessageBox.Show(I18N.GetString(\"No QRCode found. Try to zoom in or move it to the center of the screen.\"));\r\n        }\r\n\r\n        private void ImportURLItem_Click(object sender, EventArgs e)\r\n        {\r\n            if (controller.AskAddServerBySSURL(Clipboard.GetText(TextDataFormat.Text)))\r\n            {\r\n                ShowConfigForm();\r\n            }\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region PAC\r\n\r\n        private void LocalPACItem_Click(object sender, EventArgs e)\r\n        {\r\n            if (!localPACItem.Checked)\r\n            {\r\n                localPACItem.Checked = true;\r\n                onlinePACItem.Checked = false;\r\n                controller.UseOnlinePAC(false);\r\n                UpdatePACItemsEnabledStatus();\r\n            }\r\n        }\r\n\r\n        private void OnlinePACItem_Click(object sender, EventArgs e)\r\n        {\r\n            if (!onlinePACItem.Checked)\r\n            {\r\n                if (string.IsNullOrEmpty(controller.GetCurrentConfiguration().pacUrl))\r\n                {\r\n                    UpdateOnlinePACURLItem_Click(sender, e);\r\n                }\r\n                if (!string.IsNullOrEmpty(controller.GetCurrentConfiguration().pacUrl))\r\n                {\r\n                    localPACItem.Checked = false;\r\n                    onlinePACItem.Checked = true;\r\n                    controller.UseOnlinePAC(true);\r\n                }\r\n                UpdatePACItemsEnabledStatus();\r\n            }\r\n        }\r\n\r\n        private void UpdateOnlinePACURLItem_Click(object sender, EventArgs e)\r\n        {\r\n            string origPacUrl = controller.GetCurrentConfiguration().pacUrl;\r\n            string pacUrl = Microsoft.VisualBasic.Interaction.InputBox(\r\n                I18N.GetString(\"Please input PAC Url\"),\r\n                I18N.GetString(\"Edit Online PAC URL\"),\r\n                origPacUrl, -1, -1);\r\n            if (!string.IsNullOrEmpty(pacUrl) && pacUrl != origPacUrl)\r\n            {\r\n                controller.SavePACUrl(pacUrl);\r\n            }\r\n        }\r\n\r\n        private void SecureLocalPacUrlToggleItem_Click(object sender, EventArgs e)\r\n        {\r\n            Configuration configuration = controller.GetCurrentConfiguration();\r\n            controller.ToggleSecureLocalPac(!configuration.secureLocalPac);\r\n        }\r\n\r\n        private void RegenerateLocalPacOnUpdateItem_Click(object sender, EventArgs e)\r\n        {\r\n            var config = controller.GetCurrentConfiguration();\r\n            controller.ToggleRegeneratePacOnUpdate(!config.regeneratePacOnUpdate);\r\n        }\r\n\r\n        private void CopyLocalPacUrlItem_Click(object sender, EventArgs e)\r\n        {\r\n            controller.CopyPacUrl();\r\n        }\r\n\r\n        private void UpdatePACItemsEnabledStatus()\r\n        {\r\n            if (this.localPACItem.Checked)\r\n            {\r\n                this.editLocalPACItem.Enabled = true;\r\n                this.updateFromGeositeItem.Enabled = true;\r\n                this.editGFWUserRuleItem.Enabled = true;\r\n                this.editOnlinePACItem.Enabled = false;\r\n            }\r\n            else\r\n            {\r\n                this.editLocalPACItem.Enabled = false;\r\n                this.updateFromGeositeItem.Enabled = false;\r\n                this.editGFWUserRuleItem.Enabled = false;\r\n                this.editOnlinePACItem.Enabled = true;\r\n            }\r\n        }\r\n\r\n        private void EditPACFileItem_Click(object sender, EventArgs e)\r\n        {\r\n            controller.TouchPACFile();\r\n        }\r\n\r\n        private async void UpdatePACFromGeositeItem_Click(object sender, EventArgs e)\r\n        {\r\n            await GeositeUpdater.UpdatePACFromGeosite();\r\n        }\r\n\r\n        private void EditUserRuleFileForGeositeItem_Click(object sender, EventArgs e)\r\n        {\r\n            controller.TouchUserRuleFile();\r\n        }\r\n\r\n        void controller_FileReadyToOpen(object sender, ShadowsocksController.PathEventArgs e)\r\n        {\r\n            string argument = @\"/select, \" + e.Path;\r\n\r\n            Process.Start(\"explorer.exe\", argument);\r\n        }\r\n\r\n        void controller_UpdatePACFromGeositeError(object sender, System.IO.ErrorEventArgs e)\r\n        {\r\n            ShowBalloonTip(I18N.GetString(\"Failed to update PAC file\"), e.GetException().Message, ToolTipIcon.Error, 5000);\r\n            logger.LogUsefulException(e.GetException());\r\n        }\r\n\r\n        void controller_UpdatePACFromGeositeCompleted(object sender, GeositeResultEventArgs e)\r\n        {\r\n            string result = e.Success\r\n                ? I18N.GetString(\"PAC updated\")\r\n                : I18N.GetString(\"No updates found. Please report to Geosite if you have problems with it.\");\r\n            ShowBalloonTip(I18N.GetString(\"Shadowsocks\"), result, ToolTipIcon.Info, 1000);\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Help\r\n\r\n        void controller_VerboseLoggingStatusChanged(object sender, EventArgs e)\r\n        {\r\n            VerboseLoggingToggleItem.Checked = controller.GetCurrentConfiguration().isVerboseLogging;\r\n        }\r\n\r\n        void controller_ShowPluginOutputChanged(object sender, EventArgs e)\r\n        {\r\n            ShowPluginOutputToggleItem.Checked = controller.GetCurrentConfiguration().showPluginOutput;\r\n        }\r\n\r\n        private void VerboseLoggingToggleItem_Click(object sender, EventArgs e)\r\n        {\r\n            VerboseLoggingToggleItem.Checked = !VerboseLoggingToggleItem.Checked;\r\n            controller.ToggleVerboseLogging(VerboseLoggingToggleItem.Checked);\r\n        }\r\n\r\n        private void ShowLogItem_Click(object sender, EventArgs e)\r\n        {\r\n            ShowLogForm();\r\n        }\r\n\r\n        private void ShowPluginOutputToggleItem_Click(object sender, EventArgs e)\r\n        {\r\n            ShowPluginOutputToggleItem.Checked = !ShowPluginOutputToggleItem.Checked;\r\n            controller.ToggleShowPluginOutput(ShowPluginOutputToggleItem.Checked);\r\n        }\r\n\r\n        private void WriteI18NFileItem_Click(object sender, EventArgs e)\r\n        {\r\n            File.WriteAllText(I18N.I18N_FILE, Resources.i18n_csv, Encoding.UTF8);\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Update\r\n\r\n        void updateChecker_CheckUpdateCompleted(object sender, EventArgs e)\r\n        {\r\n            if (!_isStartupCheck && updateChecker.NewReleaseZipFilename == null)\r\n            {\r\n                ShowBalloonTip(I18N.GetString(\"Shadowsocks\"), I18N.GetString(\"No update is available\"), ToolTipIcon.Info, 5000);\r\n            }\r\n            _isStartupCheck = false;\r\n        }\r\n\r\n        private void UpdateUpdateMenu()\r\n        {\r\n            Configuration configuration = controller.GetCurrentConfiguration();\r\n            autoCheckUpdatesToggleItem.Checked = configuration.autoCheckUpdate;\r\n            checkPreReleaseToggleItem.Checked = configuration.checkPreRelease;\r\n        }\r\n\r\n        private void autoCheckUpdatesToggleItem_Click(object sender, EventArgs e)\r\n        {\r\n            Configuration configuration = controller.GetCurrentConfiguration();\r\n            controller.ToggleCheckingUpdate(!configuration.autoCheckUpdate);\r\n            UpdateUpdateMenu();\r\n        }\r\n\r\n        private void checkPreReleaseToggleItem_Click(object sender, EventArgs e)\r\n        {\r\n            Configuration configuration = controller.GetCurrentConfiguration();\r\n            controller.ToggleCheckingPreRelease(!configuration.checkPreRelease);\r\n            UpdateUpdateMenu();\r\n        }\r\n\r\n        private async void checkUpdatesItem_Click(object sender, EventArgs e)\r\n        {\r\n            await updateChecker.CheckForVersionUpdate();\r\n        }\r\n\r\n        private void AboutItem_Click(object sender, EventArgs e)\r\n        {\r\n            Process.Start(\"https://github.com/shadowsocks/shadowsocks-windows\");\r\n        }\r\n\r\n        #endregion\r\n    }\r\n}\r\n"
  },
  {
    "path": "shadowsocks-csharp/ViewModels/ForwardProxyViewModel.cs",
    "content": "﻿using ReactiveUI;\nusing ReactiveUI.Fody.Helpers;\nusing ReactiveUI.Validation.Extensions;\nusing ReactiveUI.Validation.Helpers;\nusing Shadowsocks.Controller;\nusing Shadowsocks.Model;\nusing Shadowsocks.View;\nusing System.Linq;\nusing System.Reactive;\nusing System.Reactive.Linq;\n\nnamespace Shadowsocks.ViewModels\n{\n    public class ForwardProxyViewModel : ReactiveValidationObject\n    {\n        public ForwardProxyViewModel()\n        {\n            _config = Program.MainController.GetCurrentConfiguration();\n            _controller = Program.MainController;\n            _menuViewController = Program.MenuController;\n\n            if (!_config.proxy.useProxy)\n                NoProxy = true;\n            else if (_config.proxy.proxyType == 0)\n                UseSocks5Proxy = true;\n            else\n                UseHttpProxy = true;\n\n            Address = _config.proxy.proxyServer;\n            Port = _config.proxy.proxyPort;\n            Timeout = _config.proxy.proxyTimeout;\n\n            Username = _config.proxy.authUser;\n            Password = _config.proxy.authPwd;\n\n            this.WhenAnyValue(x => x.NoProxy, x => !x)\n                .ToPropertyEx(this, x => x.CanModifyDetails);\n\n            AddressRule = this.ValidationRule(\n                viewModel => viewModel.Address,\n                address => !string.IsNullOrWhiteSpace(address),\n                \"Address can't be empty or whitespaces.\");\n            PortRule = this.ValidationRule(\n                viewModel => viewModel.Port,\n                port => port > 0 && port <= 65535,\n                port => $\"{port} is out of range (0, 65535].\");\n            TimeoutRule = this.ValidationRule(\n                viewModel => viewModel.Timeout,\n                timeout => timeout > 0 && timeout <= 10,\n                timeout => $\"{timeout} is out of range (0, 10].\");\n\n            var authValid = this\n                .WhenAnyValue(x => x.Username, x => x.Password, (username, password) => new { Username = username, Password = password })\n                .Select(x => string.IsNullOrWhiteSpace(x.Username) == string.IsNullOrWhiteSpace(x.Password));\n            AuthRule = this.ValidationRule(authValid, \"You must provide both username and password.\");\n\n            var canSave = this.IsValid();\n\n            Save = ReactiveCommand.Create(() =>\n            {\n                _controller.SaveProxy(GetForwardProxyConfig());\n                _menuViewController.CloseForwardProxyWindow();\n            }, canSave);\n            Cancel = ReactiveCommand.Create(_menuViewController.CloseForwardProxyWindow);\n        }\n\n        private readonly Configuration _config;\n        private readonly ShadowsocksController _controller;\n        private readonly MenuViewController _menuViewController;\n\n        public ValidationHelper AddressRule { get; }\n        public ValidationHelper PortRule { get; }\n        public ValidationHelper TimeoutRule { get; }\n        public ValidationHelper AuthRule { get; }\n\n        public ReactiveCommand<Unit, Unit> Save { get; }\n        public ReactiveCommand<Unit, Unit> Cancel { get; }\n\n        [ObservableAsProperty]\n        public bool CanModifyDetails { get; }\n\n        [Reactive]\n        public bool NoProxy { get; set; }\n\n        [Reactive]\n        public bool UseSocks5Proxy { get; set; }\n\n        [Reactive]\n        public bool UseHttpProxy { get; set; }\n\n        [Reactive]\n        public string Address { get; set; }\n\n        [Reactive]\n        public int Port { get; set; }\n\n        [Reactive]\n        public int Timeout { get; set; }\n\n        [Reactive]\n        public string Username { get; set; }\n\n        [Reactive]\n        public string Password { get; set; }\n\n        private ForwardProxyConfig GetForwardProxyConfig()\n        {\n            var forwardProxyConfig = new ForwardProxyConfig()\n            {\n                proxyServer = Address,\n                proxyPort = Port,\n                proxyTimeout = Timeout,\n                authUser = Username,\n                authPwd = Password\n            };\n            if (NoProxy)\n                forwardProxyConfig.useProxy = false;\n            else if (UseSocks5Proxy)\n            {\n                forwardProxyConfig.useProxy = true;\n                forwardProxyConfig.proxyType = 0;\n            }\n            else\n            {\n                forwardProxyConfig.useProxy = true;\n                forwardProxyConfig.proxyType = 1;\n            }\n            return forwardProxyConfig;\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/ViewModels/HotkeysViewModel.cs",
    "content": "﻿using ReactiveUI;\nusing ReactiveUI.Fody.Helpers;\nusing Shadowsocks.Controller;\nusing Shadowsocks.Model;\nusing Shadowsocks.View;\nusing System.Reactive;\nusing System.Text;\nusing System.Windows.Input;\n\nnamespace Shadowsocks.ViewModels\n{\n    public class HotkeysViewModel : ReactiveObject\n    {\n        public HotkeysViewModel()\n        {\n            _config = Program.MainController.GetCurrentConfiguration();\n            _controller = Program.MainController;\n            _menuViewController = Program.MenuController;\n            \n            HotkeySystemProxy = _config.hotkey.SwitchSystemProxy;\n            HotkeyProxyMode = _config.hotkey.SwitchSystemProxyMode;\n            HotkeyAllowLan = _config.hotkey.SwitchAllowLan;\n            HotkeyOpenLogs = _config.hotkey.ShowLogs;\n            HotkeySwitchPrev = _config.hotkey.ServerMoveUp;\n            HotkeySwitchNext = _config.hotkey.ServerMoveDown;\n            RegisterAtStartup = _config.hotkey.RegHotkeysAtStartup;\n\n            HotkeySystemProxyStatus = \"✔\";\n            HotkeyProxyModeStatus = \"✔\";\n            HotkeyAllowLanStatus = \"✔\";\n            HotkeyOpenLogsStatus = \"✔\";\n            HotkeySwitchPrevStatus = \"✔\";\n            HotkeySwitchNextStatus = \"✔\";\n\n            RegisterAll = ReactiveCommand.Create(() => RegisterAllAndUpdateStatus());\n            Save = ReactiveCommand.Create(() => RegisterAllAndUpdateStatus(true));\n            Cancel = ReactiveCommand.Create(_menuViewController.CloseHotkeysWindow);\n        }\n\n        private readonly Configuration _config;\n        private readonly ShadowsocksController _controller;\n        private readonly MenuViewController _menuViewController;\n\n        public ReactiveCommand<Unit, Unit> RegisterAll { get; }\n        public ReactiveCommand<Unit, Unit> Save { get; }\n        public ReactiveCommand<Unit, Unit> Cancel { get; }\n\n        [Reactive]\n        public string HotkeySystemProxy { get; set; }\n\n        [Reactive]\n        public string HotkeyProxyMode { get; set; }\n\n        [Reactive]\n        public string HotkeyAllowLan { get; set; }\n\n        [Reactive]\n        public string HotkeyOpenLogs { get; set; }\n\n        [Reactive]\n        public string HotkeySwitchPrev { get; set; }\n\n        [Reactive]\n        public string HotkeySwitchNext { get; set; }\n\n        [Reactive]\n        public bool RegisterAtStartup { get; set; }\n\n        [Reactive]\n        public string HotkeySystemProxyStatus { get; set; }\n\n        [Reactive]\n        public string HotkeyProxyModeStatus { get; set; }\n\n        [Reactive]\n        public string HotkeyAllowLanStatus { get; set; }\n\n        [Reactive]\n        public string HotkeyOpenLogsStatus { get; set; }\n\n        [Reactive]\n        public string HotkeySwitchPrevStatus { get; set; }\n\n        [Reactive]\n        public string HotkeySwitchNextStatus { get; set; }\n\n        public void RecordKeyDown(int hotkeyIndex, KeyEventArgs keyEventArgs)\n        {\n            var recordedKeyStringBuilder = new StringBuilder();\n\n            // record modifiers\n            if ((Keyboard.Modifiers & ModifierKeys.Control) > 0)\n                recordedKeyStringBuilder.Append(\"Ctrl+\");\n            if ((Keyboard.Modifiers & ModifierKeys.Alt) > 0)\n                recordedKeyStringBuilder.Append(\"Alt+\");\n            if ((Keyboard.Modifiers & ModifierKeys.Shift) > 0)\n                recordedKeyStringBuilder.Append(\"Shift+\");\n\n            // record other keys when at least one modifier is pressed\n            if (recordedKeyStringBuilder.Length > 0 && (keyEventArgs.Key < Key.LeftShift || keyEventArgs.Key > Key.RightAlt))\n                recordedKeyStringBuilder.Append(keyEventArgs.Key);\n\n            switch (hotkeyIndex)\n            {\n                case 0:\n                    HotkeySystemProxy = recordedKeyStringBuilder.ToString();\n                    break;\n                case 1:\n                    HotkeyProxyMode = recordedKeyStringBuilder.ToString();\n                    break;\n                case 2:\n                    HotkeyAllowLan = recordedKeyStringBuilder.ToString();\n                    break;\n                case 3:\n                    HotkeyOpenLogs = recordedKeyStringBuilder.ToString();\n                    break;\n                case 4:\n                    HotkeySwitchPrev = recordedKeyStringBuilder.ToString();\n                    break;\n                case 5:\n                    HotkeySwitchNext = recordedKeyStringBuilder.ToString();\n                    break;\n            }\n        }\n\n        public void FinishOnKeyUp(int hotkeyIndex, KeyEventArgs keyEventArgs)\n        {\n            switch (hotkeyIndex)\n            {\n                case 0:\n                    if (HotkeySystemProxy.EndsWith(\"+\"))\n                        HotkeySystemProxy = \"\";\n                    break;\n                case 1:\n                    if (HotkeyProxyMode.EndsWith(\"+\"))\n                        HotkeyProxyMode = \"\";\n                    break;\n                case 2:\n                    if (HotkeyAllowLan.EndsWith(\"+\"))\n                        HotkeyAllowLan = \"\";\n                    break;\n                case 3:\n                    if (HotkeyOpenLogs.EndsWith(\"+\"))\n                        HotkeyOpenLogs = \"\";\n                    break;\n                case 4:\n                    if (HotkeySwitchPrev.EndsWith(\"+\"))\n                        HotkeySwitchPrev = \"\";\n                    break;\n                case 5:\n                    if (HotkeySwitchNext.EndsWith(\"+\"))\n                        HotkeySwitchNext = \"\";\n                    break;\n            }\n        }\n\n        private void RegisterAllAndUpdateStatus(bool save = false)\n        {\n            HotkeySystemProxyStatus = HotkeyReg.RegHotkeyFromString(HotkeySystemProxy, \"SwitchSystemProxyCallback\") ? \"✔\" : \"❌\";\n            HotkeyProxyModeStatus = HotkeyReg.RegHotkeyFromString(HotkeyProxyMode, \"SwitchSystemProxyModeCallback\") ? \"✔\" : \"❌\";\n            HotkeyAllowLanStatus = HotkeyReg.RegHotkeyFromString(HotkeyAllowLan, \"SwitchAllowLanCallback\") ? \"✔\" : \"❌\";\n            HotkeyOpenLogsStatus = HotkeyReg.RegHotkeyFromString(HotkeyOpenLogs, \"ShowLogsCallback\") ? \"✔\" : \"❌\";\n            HotkeySwitchPrevStatus = HotkeyReg.RegHotkeyFromString(HotkeySwitchPrev, \"ServerMoveUpCallback\") ? \"✔\" : \"❌\";\n            HotkeySwitchNextStatus = HotkeyReg.RegHotkeyFromString(HotkeySwitchNext, \"ServerMoveDownCallback\") ? \"✔\" : \"❌\";\n\n            if (HotkeySystemProxyStatus == \"✔\" &&\n                HotkeyProxyModeStatus == \"✔\" &&\n                HotkeyAllowLanStatus == \"✔\" &&\n                HotkeyOpenLogsStatus == \"✔\" &&\n                HotkeySwitchPrevStatus == \"✔\" &&\n                HotkeySwitchNextStatus == \"✔\" && save)\n            {\n                _controller.SaveHotkeyConfig(GetHotkeyConfig);\n                _menuViewController.CloseHotkeysWindow();\n            }\n        }\n\n        private HotkeyConfig GetHotkeyConfig => new HotkeyConfig()\n        {\n            SwitchSystemProxy = HotkeySystemProxy,\n            SwitchSystemProxyMode = HotkeyProxyMode,\n            SwitchAllowLan = HotkeyAllowLan,\n            ShowLogs = HotkeyOpenLogs,\n            ServerMoveUp = HotkeySwitchPrev,\n            ServerMoveDown = HotkeySwitchNext,\n            RegHotkeysAtStartup = RegisterAtStartup\n        };\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/ViewModels/OnlineConfigViewModel.cs",
    "content": "﻿using ReactiveUI;\nusing ReactiveUI.Fody.Helpers;\nusing ReactiveUI.Validation.Extensions;\nusing ReactiveUI.Validation.Helpers;\nusing Shadowsocks.Controller;\nusing Shadowsocks.Localization;\nusing Shadowsocks.Model;\nusing Shadowsocks.View;\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Reactive;\nusing System.Reactive.Linq;\nusing System.Text;\nusing System.Windows;\n\nnamespace Shadowsocks.ViewModels\n{\n    public class OnlineConfigViewModel : ReactiveValidationObject\n    {\n        public OnlineConfigViewModel()\n        {\n            _config = Program.MainController.GetCurrentConfiguration();\n            _controller = Program.MainController;\n            _menuViewController = Program.MenuController;\n\n            Sources = new ObservableCollection<string>(_config.onlineConfigSource);\n            SelectedSource = \"\";\n            Address = \"\";\n\n            // TODO in v5: if http:// show warning as materialDesign:HintAssist.HelperText\n            AddressRule = this.ValidationRule(\n                viewModel => viewModel.Address,\n                address => address.StartsWith(\"http://\"),\n                \"Warning: getting online configuration from plain HTTP sources is NOT secure!\");\n\n            var canUpdateCopyRemove = this.WhenAnyValue(\n                x => x.SelectedSource,\n                selectedSource => !string.IsNullOrWhiteSpace(selectedSource));\n            var canUpdateAll = this.WhenAnyValue(\n                x => x.Sources.Count,\n                count => count > 0);\n            var canAdd = this.WhenAnyValue(\n                x => x.Address,\n                address => Uri.IsWellFormedUriString(address, UriKind.Absolute) &&\n                (address.StartsWith(\"https://\") || address.StartsWith(\"http://\")));\n\n            Update = ReactiveCommand.CreateFromTask(() => _controller.UpdateOnlineConfig(SelectedSource), canUpdateCopyRemove);\n            UpdateAll = ReactiveCommand.CreateFromTask(_controller.UpdateAllOnlineConfig, canUpdateAll);\n            CopyLink = ReactiveCommand.Create(() => Clipboard.SetText(SelectedSource), canUpdateCopyRemove);\n            Remove = ReactiveCommand.Create(() =>\n            {\n                bool result;\n                var urlToRemove = SelectedSource; // save it here because SelectedSource is lost once we remove the selection\n                do\n                {\n                    result = Sources.Remove(urlToRemove);\n                } while (result);\n                _controller.RemoveOnlineConfig(urlToRemove);\n            }, canUpdateCopyRemove);\n            Add = ReactiveCommand.Create(() =>\n            {\n                Sources.Add(Address);\n                SelectedSource = Address;\n                _controller.SaveOnlineConfigSource(Sources.ToList());\n                Address = \"\";\n            }, canAdd);\n\n            // TODO in v5: use MaterialDesignThemes snackbar messages\n            this.WhenAnyObservable(x => x.Update)\n                .Subscribe(x =>\n                {\n                    if (x)\n                        MessageBox.Show(LocalizationProvider.GetLocalizedValue<string>(\"sip008UpdateSuccess\"));\n                    else\n                        MessageBox.Show(LocalizationProvider.GetLocalizedValue<string>(\"sip008UpdateFailure\"));\n                });\n            this.WhenAnyObservable(x => x.UpdateAll)\n                .Subscribe(x =>\n                {\n                    if (x.Count == 0)\n                        MessageBox.Show(LocalizationProvider.GetLocalizedValue<string>(\"sip008UpdateAllSuccess\"));\n                    else\n                    {\n                        var stringBuilder = new StringBuilder(LocalizationProvider.GetLocalizedValue<string>(\"sip008UpdateAllFailure\"));\n                        foreach (var url in x)\n                            stringBuilder.AppendLine(url);\n                        MessageBox.Show(stringBuilder.ToString());\n                    }\n                });\n        }\n\n        private readonly Configuration _config;\n        private readonly ShadowsocksController _controller;\n        private readonly MenuViewController _menuViewController;\n\n        public ValidationHelper AddressRule { get; }\n\n        public ReactiveCommand<Unit, bool> Update { get; }\n        public ReactiveCommand<Unit, List<string>> UpdateAll { get; }\n        public ReactiveCommand<Unit, Unit> CopyLink { get; }\n        public ReactiveCommand<Unit, Unit> Remove { get; }\n        public ReactiveCommand<Unit, Unit> Add { get; }\n\n        [Reactive]\n        public ObservableCollection<string> Sources { get; private set; }\n\n        [Reactive]\n        public string SelectedSource { get; set; }\n\n        [Reactive]\n        public string Address { get; set; }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/ViewModels/ServerSharingViewModel.cs",
    "content": "﻿using ReactiveUI;\nusing ReactiveUI.Fody.Helpers;\nusing Shadowsocks.Model;\nusing System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.IO;\nusing System.Linq;\nusing System.Reactive;\nusing System.Windows;\nusing System.Windows.Media.Imaging;\n\nnamespace Shadowsocks.ViewModels\n{\n    public class ServerSharingViewModel : ReactiveObject\n    {\n        /// <summary>\n        /// The view model class for the server sharing user control.\n        /// </summary>\n        public ServerSharingViewModel()\n        {\n            _config = Program.MainController.GetCurrentConfiguration();\n            Servers = _config.configs;\n            SelectedServer = Servers[0];\n\n            this.WhenAnyValue(x => x.SelectedServer)\n                .Subscribe(_ => UpdateUrlAndImage());\n\n            CopyLink = ReactiveCommand.Create(() => Clipboard.SetText(SelectedServerUrl));\n        }\n\n        private readonly Configuration _config;\n\n        public ReactiveCommand<Unit, Unit> CopyLink { get; }\n\n        [Reactive]\n        public List<Server> Servers { get; private set; }\n\n        [Reactive]\n        public Server SelectedServer { get; set; }\n\n        [Reactive]\n        public string SelectedServerUrl { get; private set; }\n\n        [Reactive]\n        public BitmapImage SelectedServerUrlImage { get; private set; }\n\n        /// <summary>\n        /// Called when SelectedServer changed\n        /// to update SelectedServerUrl and SelectedServerUrlImage\n        /// </summary>\n        private void UpdateUrlAndImage()\n        {\n            // update SelectedServerUrl\n            SelectedServerUrl = SelectedServer.GetURL(_config.generateLegacyUrl);\n\n            // generate QR code\n            var qrCode = ZXing.QrCode.Internal.Encoder.encode(SelectedServerUrl, ZXing.QrCode.Internal.ErrorCorrectionLevel.L);\n            var byteMatrix = qrCode.Matrix;\n\n            // paint bitmap\n            int blockSize = Math.Max(1024 / byteMatrix.Height, 1);\n            Bitmap drawArea = new Bitmap((byteMatrix.Width * blockSize), (byteMatrix.Height * blockSize));\n            using (var graphics = Graphics.FromImage(drawArea))\n            {\n                graphics.Clear(Color.White);\n                using (var solidBrush = new SolidBrush(Color.Black))\n                {\n                    for (int row = 0; row < byteMatrix.Width; row++)\n                    {\n                        for (int column = 0; column < byteMatrix.Height; column++)\n                        {\n                            if (byteMatrix[row, column] != 0)\n                            {\n                                graphics.FillRectangle(solidBrush, blockSize * row, blockSize * column, blockSize, blockSize);\n                            }\n                        }\n                    }\n                }\n            }\n\n            // transform to BitmapImage for binding\n            BitmapImage bitmapImage = new BitmapImage();\n            using (MemoryStream memoryStream = new MemoryStream())\n            {\n                drawArea.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);\n                memoryStream.Position = 0;\n                bitmapImage.BeginInit();\n                bitmapImage.StreamSource = memoryStream;\n                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;\n                bitmapImage.EndInit();\n            }\n            SelectedServerUrlImage = bitmapImage;\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/ViewModels/VersionUpdatePromptViewModel.cs",
    "content": "﻿using Newtonsoft.Json.Linq;\nusing ReactiveUI;\nusing Shadowsocks.Controller;\nusing System.Reactive;\n\nnamespace Shadowsocks.ViewModels\n{\n    public class VersionUpdatePromptViewModel : ReactiveObject\n    {\n        public VersionUpdatePromptViewModel(JToken releaseObject)\n        {\n            _updateChecker = Program.MenuController.updateChecker;\n            _releaseObject = releaseObject;\n            ReleaseNotes = string.Concat(\n                $\"# {((bool)_releaseObject[\"prerelease\"] ? \"⚠ Pre-release\" : \"ℹ Release\")} {(string)_releaseObject[\"tag_name\"] ?? \"Failed to get tag name\"}\\r\\n\",\n                (string)_releaseObject[\"body\"] ?? \"Failed to get release notes\");\n\n            Update = ReactiveCommand.CreateFromTask(_updateChecker.DoUpdate);\n            SkipVersion = ReactiveCommand.Create(_updateChecker.SkipUpdate);\n            NotNow = ReactiveCommand.Create(_updateChecker.CloseVersionUpdatePromptWindow);\n        }\n\n        private readonly UpdateChecker _updateChecker;\n        private readonly JToken _releaseObject;\n\n        public string ReleaseNotes { get; }\n\n        public ReactiveCommand<Unit, Unit> Update { get; }\n\n        public ReactiveCommand<Unit, Unit> SkipVersion { get; }\n\n        public ReactiveCommand<Unit, Unit> NotNow { get; }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Views/ForwardProxyView.xaml",
    "content": "﻿<reactiveui:ReactiveUserControl\n    x:Class=\"Shadowsocks.Views.ForwardProxyView\"\n    x:TypeArguments=\"vms:ForwardProxyViewModel\"\n    xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n    xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n    xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n    xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\" \n    xmlns:local=\"clr-namespace:Shadowsocks.Views\"\n    xmlns:vms=\"clr-namespace:Shadowsocks.ViewModels\"\n    xmlns:reactiveui=\"http://reactiveui.net\"\n    xmlns:lex=\"http://wpflocalizeextension.codeplex.com\"\n    lex:LocalizeDictionary.DesignCulture=\"en\"\n    lex:ResxLocalizationProvider.DefaultAssembly=\"Shadowsocks\"\n    lex:ResxLocalizationProvider.DefaultDictionary=\"Strings\"\n    mc:Ignorable=\"d\" \n    d:DesignHeight=\"380\" d:DesignWidth=\"280\">\n    <Grid Margin=\"8\">\n        <Grid.RowDefinitions>\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"*\" />\n        </Grid.RowDefinitions>\n        <Grid.ColumnDefinitions>\n            <ColumnDefinition Width=\"Auto\" />\n            <ColumnDefinition Width=\"*\" />\n        </Grid.ColumnDefinitions>\n\n        <TextBlock Grid.Row=\"0\" Grid.Column=\"0\" Grid.ColumnSpan=\"2\"\n                   Margin=\"4 8 4 8\"\n                   FontSize=\"16\"\n                   Text=\"{lex:Loc Type}\"/>\n        <RadioButton x:Name=\"noProxyRadioButton\" Grid.Row=\"1\" Grid.Column=\"0\"\n                     Margin=\"4\"\n                     GroupName=\"ProxyType\"\n                     Content=\"{lex:Loc NoProxy}\"/>\n        <RadioButton x:Name=\"socks5RadioButton\" Grid.Row=\"2\" Grid.Column=\"0\"\n                     Margin=\"4\"\n                     GroupName=\"ProxyType\"\n                     Content=\"{lex:Loc SOCKS5}\"/>\n        <RadioButton x:Name=\"httpRadioButton\" Grid.Row=\"3\" Grid.Column=\"0\"\n                     Margin=\"4\"\n                     GroupName=\"ProxyType\"\n                     Content=\"{lex:Loc HTTP}\"/>\n\n        <TextBlock Grid.Row=\"4\" Grid.Column=\"0\" Grid.ColumnSpan=\"2\"\n                   Margin=\"4 8 4 8\"\n                   FontSize=\"16\"\n                   Text=\"{lex:Loc Details}\"/>\n        <TextBlock Grid.Row=\"5\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc Address}\"/>\n        <TextBox x:Name=\"addressTextBox\" Grid.Row=\"5\" Grid.Column=\"1\"\n                 Margin=\"4\"/>\n        <TextBlock Grid.Row=\"6\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc Port}\"/>\n        <TextBox x:Name=\"portTextBox\" Grid.Row=\"6\" Grid.Column=\"1\"\n                 Margin=\"4\"\n                 HorizontalContentAlignment=\"Right\"/>\n        <TextBlock Grid.Row=\"7\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc Timeout}\"/>\n        <TextBox x:Name=\"timeoutTextBox\" Grid.Row=\"7\" Grid.Column=\"1\"\n                 Margin=\"4\"\n                 HorizontalContentAlignment=\"Right\"/>\n\n        <TextBlock Grid.Row=\"8\" Grid.Column=\"0\" Grid.ColumnSpan=\"2\"\n                   Margin=\"4 8 4 8\"\n                   FontSize=\"16\"\n                   Text=\"{lex:Loc CredentialsOptional}\"/>\n\n        <TextBlock Grid.Row=\"9\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc Username}\"/>\n        <TextBox x:Name=\"usernameTextBox\" Grid.Row=\"9\" Grid.Column=\"1\"\n                 Margin=\"4\"/>\n        <TextBlock Grid.Row=\"10\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc Password}\"/>\n        <TextBox x:Name=\"passwordTextBox\" Grid.Row=\"10\" Grid.Column=\"1\"\n                 Margin=\"4\"/>\n\n        <StackPanel Grid.Row=\"11\" Grid.Column=\"0\" Grid.ColumnSpan=\"2\"\n                    Orientation=\"Horizontal\"\n                    HorizontalAlignment=\"Right\"\n                    VerticalAlignment=\"Bottom\">\n            <Button x:Name=\"saveButton\" Margin=\"4\" MinWidth=\"75\" Content=\"{lex:Loc}\"/>\n            <Button x:Name=\"cancelButton\" Margin=\"4\" MinWidth=\"75\" Content=\"{lex:Loc}\"/>\n        </StackPanel>\n    </Grid>\n</reactiveui:ReactiveUserControl>\n"
  },
  {
    "path": "shadowsocks-csharp/Views/ForwardProxyView.xaml.cs",
    "content": "﻿using ReactiveUI;\nusing Shadowsocks.ViewModels;\nusing System.Reactive.Disposables;\n\nnamespace Shadowsocks.Views\n{\n    /// <summary>\n    /// Interaction logic for ForwardProxyView.xaml\n    /// </summary>\n    public partial class ForwardProxyView : ReactiveUserControl<ForwardProxyViewModel>\n    {\n        public ForwardProxyView()\n        {\n            InitializeComponent();\n            ViewModel = new ForwardProxyViewModel();\n            this.WhenActivated(disposables =>\n            {\n                this.Bind(ViewModel,\n                    viewModel => viewModel.NoProxy,\n                    view => view.noProxyRadioButton.IsChecked)\n                    .DisposeWith(disposables);\n                this.Bind(ViewModel,\n                    viewModel => viewModel.UseSocks5Proxy,\n                    view => view.socks5RadioButton.IsChecked)\n                    .DisposeWith(disposables);\n                this.Bind(ViewModel,\n                    viewModel => viewModel.UseHttpProxy,\n                    view => view.httpRadioButton.IsChecked)\n                    .DisposeWith(disposables);\n\n                this.Bind(ViewModel,\n                    viewModel => viewModel.Address,\n                    view => view.addressTextBox.Text)\n                    .DisposeWith(disposables);\n                this.Bind(ViewModel,\n                    viewModel => viewModel.Port,\n                    view => view.portTextBox.Text)\n                    .DisposeWith(disposables);\n                this.Bind(ViewModel,\n                    viewModel => viewModel.Timeout,\n                    view => view.timeoutTextBox.Text)\n                    .DisposeWith(disposables);\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.CanModifyDetails,\n                    view => view.addressTextBox.IsEnabled)\n                    .DisposeWith(disposables);\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.CanModifyDetails,\n                    view => view.portTextBox.IsEnabled)\n                    .DisposeWith(disposables);\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.CanModifyDetails,\n                    view => view.timeoutTextBox.IsEnabled)\n                    .DisposeWith(disposables);\n\n                this.Bind(ViewModel,\n                    viewModel => viewModel.Username,\n                    view => view.usernameTextBox.Text)\n                    .DisposeWith(disposables);\n                this.Bind(ViewModel,\n                    viewModel => viewModel.Password,\n                    view => view.passwordTextBox.Text)\n                    .DisposeWith(disposables);\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.UseHttpProxy,\n                    view => view.usernameTextBox.IsEnabled)\n                    .DisposeWith(disposables);\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.UseHttpProxy,\n                    view => view.passwordTextBox.IsEnabled)\n                    .DisposeWith(disposables);\n\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.Save,\n                    view => view.saveButton)\n                    .DisposeWith(disposables);\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.Cancel,\n                    view => view.cancelButton)\n                    .DisposeWith(disposables);\n            });\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Views/HotkeysView.xaml",
    "content": "﻿<reactiveui:ReactiveUserControl\n    x:Class=\"Shadowsocks.Views.HotkeysView\"\n    x:TypeArguments=\"vms:HotkeysViewModel\"\n    xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n    xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n    xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n    xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\" \n    xmlns:local=\"clr-namespace:Shadowsocks.Views\"\n    xmlns:vms=\"clr-namespace:Shadowsocks.ViewModels\"\n    xmlns:reactiveui=\"http://reactiveui.net\"\n    xmlns:lex=\"http://wpflocalizeextension.codeplex.com\"\n    lex:LocalizeDictionary.DesignCulture=\"en\"\n    lex:ResxLocalizationProvider.DefaultAssembly=\"Shadowsocks\"\n    lex:ResxLocalizationProvider.DefaultDictionary=\"Strings\"\n    mc:Ignorable=\"d\" \n    d:DesignHeight=\"240\" d:DesignWidth=\"280\">\n    <Grid Margin=\"8\">\n        <Grid.RowDefinitions>\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"*\" />\n        </Grid.RowDefinitions>\n        <Grid.ColumnDefinitions>\n            <ColumnDefinition Width=\"Auto\" />\n            <ColumnDefinition Width=\"*\" />\n            <ColumnDefinition Width=\"Auto\" />\n        </Grid.ColumnDefinitions>\n\n        <TextBlock Grid.Row=\"0\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc ToggleSystemProxy}\"/>\n        <TextBox x:Name=\"systemProxyTextBox\"\n                 Grid.Row=\"0\" Grid.Column=\"1\"\n                 Margin=\"4\" IsReadOnly=\"True\" />\n        <TextBlock x:Name=\"systemProxyStatusTextBlock\"\n                 Grid.Row=\"0\" Grid.Column=\"2\"\n                 Margin=\"4\" />\n\n        <TextBlock Grid.Row=\"1\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc ToggleProxyMode}\"/>\n        <TextBox x:Name=\"proxyModeTextBox\"\n                 Grid.Row=\"1\" Grid.Column=\"1\"\n                 Margin=\"4\" IsReadOnly=\"True\" />\n        <TextBlock x:Name=\"proxyModeStatusTextBlock\"\n                 Grid.Row=\"1\" Grid.Column=\"2\"\n                 Margin=\"4\" />\n\n        <TextBlock Grid.Row=\"2\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc AllowClientsFromLAN}\"/>\n        <TextBox x:Name=\"allowLanTextBox\"\n                 Grid.Row=\"2\" Grid.Column=\"1\"\n                 Margin=\"4\" IsReadOnly=\"True\" />\n        <TextBlock x:Name=\"allowLanStatusTextBlock\"\n                 Grid.Row=\"2\" Grid.Column=\"2\"\n                 Margin=\"4\" />\n\n        <TextBlock Grid.Row=\"3\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc OpenLogsWindow}\"/>\n        <TextBox x:Name=\"openLogsTextBox\"\n                 Grid.Row=\"3\" Grid.Column=\"1\"\n                 Margin=\"4\" IsReadOnly=\"True\" />\n        <TextBlock x:Name=\"openLogsStatusTextBlock\"\n                 Grid.Row=\"3\" Grid.Column=\"2\"\n                 Margin=\"4\" />\n\n        <TextBlock Grid.Row=\"4\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc SwitchToPreviousServer}\"/>\n        <TextBox x:Name=\"switchPrevTextBox\"\n                 Grid.Row=\"4\" Grid.Column=\"1\"\n                 Margin=\"4\" IsReadOnly=\"True\" />\n        <TextBlock x:Name=\"switchPrevStatusTextBlock\"\n                 Grid.Row=\"4\" Grid.Column=\"2\"\n                 Margin=\"4\" />\n\n        <TextBlock Grid.Row=\"5\" Grid.Column=\"0\"\n                   Margin=\"4\"\n                   Text=\"{lex:Loc SwitchToNextServer}\"/>\n        <TextBox x:Name=\"switchNextTextBox\"\n                 Grid.Row=\"5\" Grid.Column=\"1\"\n                 Margin=\"4\" IsReadOnly=\"True\" />\n        <TextBlock x:Name=\"switchNextStatusTextBlock\"\n                 Grid.Row=\"5\" Grid.Column=\"2\"\n                 Margin=\"4\" />\n\n        <StackPanel Grid.Row=\"6\" Grid.ColumnSpan=\"2\" Orientation=\"Horizontal\">\n            <CheckBox x:Name=\"registerAtStartupCheckBox\" Margin=\"4\" VerticalAlignment=\"Center\"/>\n            <TextBlock Margin=\"4\" Text=\"{lex:Loc RegisterHotkeysAtStartup}\"/>\n        </StackPanel>\n\n        <StackPanel Grid.Row=\"7\"\n                    Grid.ColumnSpan=\"3\"\n                    Orientation=\"Horizontal\"\n                    HorizontalAlignment=\"Left\"\n                    VerticalAlignment=\"Bottom\">\n            <Button x:Name=\"registerAllButton\" Margin=\"4\" MinWidth=\"75\" Content=\"{lex:Loc}\"/>\n        </StackPanel>\n        <StackPanel Grid.Row=\"7\"\n                    Grid.ColumnSpan=\"3\"\n                    Orientation=\"Horizontal\"\n                    HorizontalAlignment=\"Right\"\n                    VerticalAlignment=\"Bottom\">\n            <Button x:Name=\"saveButton\" Margin=\"4\" MinWidth=\"75\" Content=\"{lex:Loc}\"/>\n            <Button x:Name=\"cancelButton\" Margin=\"4\" MinWidth=\"75\" Content=\"{lex:Loc}\"/>\n        </StackPanel>\n    </Grid>\n</reactiveui:ReactiveUserControl>\n"
  },
  {
    "path": "shadowsocks-csharp/Views/HotkeysView.xaml.cs",
    "content": "﻿using ReactiveUI;\nusing Shadowsocks.ViewModels;\nusing System;\nusing System.Reactive.Disposables;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Navigation;\n\nnamespace Shadowsocks.Views\n{\n    /// <summary>\n    /// Interaction logic for HotkeysView.xaml\n    /// </summary>\n    public partial class HotkeysView : ReactiveUserControl<HotkeysViewModel>\n    {\n        public HotkeysView()\n        {\n            InitializeComponent();\n            ViewModel = new HotkeysViewModel();\n            this.WhenActivated(disposables =>\n            {\n                systemProxyTextBox\n                    .Events().KeyDown\n                    .Subscribe(keyEventArgs => ViewModel.RecordKeyDown(0, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                systemProxyTextBox\n                    .Events().KeyUp\n                    .Subscribe(keyEventArgs => ViewModel.FinishOnKeyUp(0, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                proxyModeTextBox\n                    .Events().KeyDown\n                    .Subscribe(keyEventArgs => ViewModel.RecordKeyDown(1, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                proxyModeTextBox\n                    .Events().KeyUp\n                    .Subscribe(keyEventArgs => ViewModel.FinishOnKeyUp(1, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                allowLanTextBox\n                    .Events().KeyDown\n                    .Subscribe(keyEventArgs => ViewModel.RecordKeyDown(2, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                allowLanTextBox\n                    .Events().KeyUp\n                    .Subscribe(keyEventArgs => ViewModel.FinishOnKeyUp(2, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                openLogsTextBox\n                    .Events().KeyDown\n                    .Subscribe(keyEventArgs => ViewModel.RecordKeyDown(3, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                openLogsTextBox\n                    .Events().KeyUp\n                    .Subscribe(keyEventArgs => ViewModel.FinishOnKeyUp(3, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                switchPrevTextBox\n                    .Events().KeyDown\n                    .Subscribe(keyEventArgs => ViewModel.RecordKeyDown(4, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                switchPrevTextBox\n                    .Events().KeyUp\n                    .Subscribe(keyEventArgs => ViewModel.FinishOnKeyUp(4, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                switchNextTextBox\n                    .Events().KeyDown\n                    .Subscribe(keyEventArgs => ViewModel.RecordKeyDown(5, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                switchNextTextBox\n                    .Events().KeyUp\n                    .Subscribe(keyEventArgs => ViewModel.FinishOnKeyUp(5, keyEventArgs))\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeySystemProxy,\n                    view => view.systemProxyTextBox.Text)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeyProxyMode,\n                    view => view.proxyModeTextBox.Text)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeyAllowLan,\n                    view => view.allowLanTextBox.Text)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeyOpenLogs,\n                    view => view.openLogsTextBox.Text)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeySwitchPrev,\n                    view => view.switchPrevTextBox.Text)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeySwitchNext,\n                    view => view.switchNextTextBox.Text)\n                    .DisposeWith(disposables);\n\n                this.Bind(ViewModel,\n                    viewModel => viewModel.RegisterAtStartup,\n                    view => view.registerAtStartupCheckBox.IsChecked)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeySystemProxyStatus,\n                    view => view.systemProxyStatusTextBlock.Text)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeyProxyModeStatus,\n                    view => view.proxyModeStatusTextBlock.Text)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeyAllowLanStatus,\n                    view => view.allowLanStatusTextBlock.Text)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeyOpenLogsStatus,\n                    view => view.openLogsStatusTextBlock.Text)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeySwitchPrevStatus,\n                    view => view.switchPrevStatusTextBlock.Text)\n                    .DisposeWith(disposables);\n\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.HotkeySwitchNextStatus,\n                    view => view.switchNextStatusTextBlock.Text)\n                    .DisposeWith(disposables);\n\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.RegisterAll,\n                    view => view.registerAllButton)\n                    .DisposeWith(disposables);\n\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.Save,\n                    view => view.saveButton)\n                    .DisposeWith(disposables);\n\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.Cancel,\n                    view => view.cancelButton)\n                    .DisposeWith(disposables);\n            });\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Views/OnlineConfigView.xaml",
    "content": "﻿<reactiveui:ReactiveUserControl\n    x:Class=\"Shadowsocks.Views.OnlineConfigView\"\n    x:TypeArguments=\"vms:OnlineConfigViewModel\"\n    xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n    xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n    xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n    xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\" \n    xmlns:local=\"clr-namespace:Shadowsocks.Views\"\n    xmlns:vms=\"clr-namespace:Shadowsocks.ViewModels\"\n    xmlns:reactiveui=\"http://reactiveui.net\"\n    xmlns:lex=\"http://wpflocalizeextension.codeplex.com\"\n    lex:LocalizeDictionary.DesignCulture=\"en\"\n    lex:ResxLocalizationProvider.DefaultAssembly=\"Shadowsocks\"\n    lex:ResxLocalizationProvider.DefaultDictionary=\"Strings\"\n    mc:Ignorable=\"d\" \n    d:DesignHeight=\"500\" d:DesignWidth=\"480\">\n    <Grid Margin=\"8\">\n        <Grid.RowDefinitions>\n            <RowDefinition Height=\"*\" />\n            <RowDefinition Height=\"Auto\" />\n        </Grid.RowDefinitions>\n        <Grid.ColumnDefinitions>\n            <ColumnDefinition Width=\"Auto\" />\n            <ColumnDefinition Width=\"*\" />\n            <ColumnDefinition Width=\"Auto\" />\n        </Grid.ColumnDefinitions>\n\n        <ListBox x:Name=\"sourcesListBox\" Margin=\"8 8 4 4\"\n                 Grid.Row=\"0\"\n                 Grid.Column=\"0\"\n                 Grid.ColumnSpan=\"2\">\n            <ListBox.ItemTemplate>\n                <DataTemplate>\n                    <TextBlock Text=\"{Binding}\"/>\n                </DataTemplate>\n            </ListBox.ItemTemplate>\n        </ListBox>\n        <StackPanel Grid.Row=\"0\" Grid.Column=\"2\">\n            <Button x:Name=\"updateButton\" Margin=\"4 8 8 4\"\n                    MinWidth=\"75\" Content=\"{lex:Loc}\"/>\n            <Button x:Name=\"updateAllButton\" Margin=\"4 4 8 4\"\n                    MinWidth=\"75\" Content=\"{lex:Loc}\"/>\n            <Button x:Name=\"copyLinkButton\" Margin=\"4 4 8 8\"\n                    MinWidth=\"75\" Content=\"{lex:Loc}\"/>\n            <Button x:Name=\"removeButton\" Margin=\"4 8 8 8\"\n                    MinWidth=\"75\" Content=\"{lex:Loc}\"/>\n        </StackPanel>\n        \n        <TextBlock Margin=\"8 4 4 8\"\n                   Grid.Row=\"1\"\n                   Grid.Column=\"0\">URL</TextBlock>\n        <TextBox x:Name=\"urlTextBox\" Margin=\"4 4 4 8\"\n                 Grid.Row=\"1\"\n                 Grid.Column=\"1\"/>\n        <Button x:Name=\"addButton\" Margin=\"4 4 8 8\"\n                Grid.Row=\"1\"\n                Grid.Column=\"2\"\n                MinWidth=\"75\"\n                Content=\"{lex:Loc}\"/>\n    </Grid>\n</reactiveui:ReactiveUserControl>\n"
  },
  {
    "path": "shadowsocks-csharp/Views/OnlineConfigView.xaml.cs",
    "content": "﻿using ReactiveUI;\nusing Shadowsocks.ViewModels;\nusing System.Reactive.Disposables;\n\nnamespace Shadowsocks.Views\n{\n    /// <summary>\n    /// Interaction logic for OnlineConfigView.xaml\n    /// </summary>\n    public partial class OnlineConfigView : ReactiveUserControl<OnlineConfigViewModel>\n    {\n        public OnlineConfigView()\n        {\n            InitializeComponent();\n            ViewModel = new OnlineConfigViewModel();\n            this.WhenActivated(disposables =>\n            {\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.Sources,\n                    view => view.sourcesListBox.ItemsSource)\n                    .DisposeWith(disposables);\n                this.Bind(ViewModel,\n                    viewModel => viewModel.SelectedSource,\n                    view => view.sourcesListBox.SelectedItem)\n                    .DisposeWith(disposables);\n                this.Bind(ViewModel,\n                    viewModel => viewModel.Address,\n                    view => view.urlTextBox.Text)\n                    .DisposeWith(disposables);\n\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.Update,\n                    view => view.updateButton)\n                    .DisposeWith(disposables);\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.UpdateAll,\n                    view => view.updateAllButton)\n                    .DisposeWith(disposables);\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.CopyLink,\n                    view => view.copyLinkButton)\n                    .DisposeWith(disposables);\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.Remove,\n                    view => view.removeButton)\n                    .DisposeWith(disposables);\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.Add,\n                    view => view.addButton)\n                    .DisposeWith(disposables);\n            });\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Views/ServerSharingView.xaml",
    "content": "﻿<reactiveui:ReactiveUserControl\n    x:Class=\"Shadowsocks.Views.ServerSharingView\"\n    x:TypeArguments=\"vms:ServerSharingViewModel\"\n    xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n    xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n    xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n    xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n    xmlns:local=\"clr-namespace:Shadowsocks.Views\"\n    xmlns:vms=\"clr-namespace:Shadowsocks.ViewModels\"\n    xmlns:reactiveui=\"http://reactiveui.net\"\n    xmlns:lex=\"http://wpflocalizeextension.codeplex.com\"\n    lex:LocalizeDictionary.DesignCulture=\"en\"\n    lex:ResxLocalizationProvider.DefaultAssembly=\"Shadowsocks\"\n    lex:ResxLocalizationProvider.DefaultDictionary=\"Strings\"\n    mc:Ignorable=\"d\"\n    d:DesignHeight=\"400\" d:DesignWidth=\"660\">\n    <Grid Margin=\"8\">\n        <Grid.RowDefinitions>\n            <RowDefinition Height=\"*\" />\n            <RowDefinition Height=\"Auto\" />\n        </Grid.RowDefinitions>\n        <Grid.ColumnDefinitions>\n            <ColumnDefinition Width=\"*\" />\n            <ColumnDefinition Width=\"*\" />\n        </Grid.ColumnDefinitions>\n        <Image x:Name=\"qrCodeImage\" Grid.Row=\"0\"\n               Grid.Column=\"0\"\n               Margin=\"8\"/>\n        <ListBox x:Name=\"serversListBox\" Grid.Row=\"0\"\n                 Grid.Column=\"1\"\n                 Margin=\"8\">\n            <ListBox.ItemTemplate>\n                <DataTemplate>\n                    <TextBlock Text=\"{Binding}\"/>\n                </DataTemplate>\n            </ListBox.ItemTemplate>\n        </ListBox>\n        <Grid Grid.Row=\"1\"\n              Grid.Column=\"0\"\n              Grid.ColumnSpan=\"2\">\n            <Grid.ColumnDefinitions>\n                <ColumnDefinition Width=\"*\" />\n                <ColumnDefinition Width=\"Auto\" />\n            </Grid.ColumnDefinitions>\n            <TextBox x:Name=\"urlTextBox\"\n                 Grid.Column=\"0\"\n                 Margin=\"8 8 4 8\"\n                 IsReadOnly=\"True\"\n                 PreviewMouseDoubleClick=\"urlTextBox_PreviewMouseDoubleClick\"/>\n            <Button x:Name=\"copyLinkButton\" Grid.Column=\"1\" Margin=\"4 8 8 8\" MinWidth=\"36\" Content=\"{lex:Loc Copy}\"/>\n        </Grid>\n    </Grid>\n</reactiveui:ReactiveUserControl>\n"
  },
  {
    "path": "shadowsocks-csharp/Views/ServerSharingView.xaml.cs",
    "content": "﻿using ReactiveUI;\nusing Shadowsocks.ViewModels;\nusing System.Reactive.Disposables;\nusing System.Windows.Input;\n\nnamespace Shadowsocks.Views\n{\n    /// <summary>\n    /// Interaction logic for ServerSharingView.xaml\n    /// </summary>\n    public partial class ServerSharingView : ReactiveUserControl<ServerSharingViewModel>\n    {\n        public ServerSharingView()\n        {\n            InitializeComponent();\n            ViewModel = new ServerSharingViewModel();\n            this.WhenActivated(disposables =>\n            {\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.SelectedServerUrlImage,\n                    view => view.qrCodeImage.Source)\n                    .DisposeWith(disposables);\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.Servers,\n                    view => view.serversListBox.ItemsSource)\n                    .DisposeWith(disposables);\n                this.Bind(ViewModel,\n                    viewModel => viewModel.SelectedServer,\n                    view => view.serversListBox.SelectedItem)\n                    .DisposeWith(disposables);\n                this.OneWayBind(ViewModel,\n                    viewModel => viewModel.SelectedServerUrl,\n                    view => view.urlTextBox.Text)\n                    .DisposeWith(disposables);\n\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.CopyLink,\n                    view => view.copyLinkButton)\n                    .DisposeWith(disposables);\n            });\n        }\n\n        private void urlTextBox_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)\n        {\n            urlTextBox.SelectAll();\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/Views/VersionUpdatePromptView.xaml",
    "content": "﻿<reactiveui:ReactiveUserControl\n    x:Class=\"Shadowsocks.Views.VersionUpdatePromptView\"\n    x:TypeArguments=\"vms:VersionUpdatePromptViewModel\"\n    xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n    xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n    xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n    xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\" \n    xmlns:local=\"clr-namespace:Shadowsocks.Views\"\n    xmlns:vms=\"clr-namespace:Shadowsocks.ViewModels\"\n    xmlns:reactiveui=\"http://reactiveui.net\"\n    xmlns:mdxam=\"clr-namespace:MdXaml;assembly=MdXaml\"\n    xmlns:lex=\"http://wpflocalizeextension.codeplex.com\"\n    lex:LocalizeDictionary.DesignCulture=\"en\"\n    lex:ResxLocalizationProvider.DefaultAssembly=\"Shadowsocks\"\n    lex:ResxLocalizationProvider.DefaultDictionary=\"Strings\"\n    mc:Ignorable=\"d\" \n    d:DesignHeight=\"480\" d:DesignWidth=\"640\">\n    <Grid Margin=\"8\">\n        <Grid.RowDefinitions>\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"Auto\" />\n            <RowDefinition Height=\"*\" />\n            <RowDefinition Height=\"Auto\" />\n        </Grid.RowDefinitions>\n        <TextBlock Margin=\"8 8 8 4\" Grid.Row=\"0\"\n                   FontSize=\"16\"\n                   Text=\"{lex:Loc updatePromptTitle}\" />\n        <TextBlock Margin=\"8 4 8 8\" Grid.Row=\"1\"\n                   Text=\"{lex:Loc updatePromptBody}\" />\n        <mdxam:MarkdownScrollViewer x:Name=\"releaseNotesMarkdownScrollViewer\"\n                                    Margin=\"8\"\n                                    Grid.Row=\"2\"\n                                    Markdown=\"{Binding ReleaseNotes}\"\n                                    MarkdownStyle=\"{x:Static mdxam:MarkdownStyle.GithubLike}\"/>\n        <StackPanel Orientation=\"Horizontal\" Grid.Row=\"3\">\n            <Button x:Name=\"updateButton\" Margin=\"8 8 4 4\" Width=\"75\" Height=\"23\" Content=\"{lex:Loc}\"/>\n        </StackPanel>\n        <StackPanel Orientation=\"Horizontal\" Grid.Row=\"3\" HorizontalAlignment=\"Right\">\n            <Button x:Name=\"skipVersionButton\" Margin=\"4 8 4 4\" Width=\"75\" Height=\"23\" Content=\"{lex:Loc}\"/>\n            <Button x:Name=\"notNowButton\" Margin=\"4 8 8 4\" Width=\"75\" Height=\"23\" Content=\"{lex:Loc}\"/>\n        </StackPanel>\n    </Grid>\n</reactiveui:ReactiveUserControl>\n"
  },
  {
    "path": "shadowsocks-csharp/Views/VersionUpdatePromptView.xaml.cs",
    "content": "﻿using Newtonsoft.Json.Linq;\nusing ReactiveUI;\nusing Shadowsocks.ViewModels;\nusing System.Reactive.Disposables;\n\nnamespace Shadowsocks.Views\n{\n    /// <summary>\n    /// Interaction logic for VersionUpdatePromptView.xaml\n    /// </summary>\n    public partial class VersionUpdatePromptView : ReactiveUserControl<VersionUpdatePromptViewModel>\n    {\n        public VersionUpdatePromptView(JToken releaseObject)\n        {\n            InitializeComponent();\n            ViewModel = new VersionUpdatePromptViewModel(releaseObject);\n            DataContext = ViewModel; // for compatibility with MdXaml\n            this.WhenActivated(disposables =>\n            {\n                /*this.OneWayBind(ViewModel,\n                    viewModel => viewModel.ReleaseNotes,\n                    view => releaseNotesMarkdownScrollViewer.Markdown)\n                    .DisposeWith(disposables);*/\n\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.Update,\n                    view => view.updateButton)\n                    .DisposeWith(disposables);\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.SkipVersion,\n                    view => view.skipVersionButton)\n                    .DisposeWith(disposables);\n                this.BindCommand(ViewModel,\n                    viewModel => viewModel.NotNow,\n                    view => view.notNowButton)\n                    .DisposeWith(disposables);\n            });\n        }\n    }\n}\n"
  },
  {
    "path": "shadowsocks-csharp/app.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n<configSections>\r\n    <sectionGroup name=\"userSettings\" type=\"System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\r\n        <section name=\"Shadowsocks.Properties.Settings\" type=\"System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" allowExeDefinition=\"MachineToLocalUser\" requirePermission=\"false\" />\r\n    </sectionGroup>\r\n</configSections>\r\n<startup>\r\n  <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.8\" />\r\n</startup>\r\n  <runtime>\r\n    <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\r\n      <dependentAssembly>\r\n        <assemblyIdentity name=\"System.Runtime\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\" />\r\n        <bindingRedirect oldVersion=\"0.0.0.0-2.6.10.0\" newVersion=\"2.6.10.0\" />\r\n      </dependentAssembly>\r\n      <dependentAssembly>\r\n        <assemblyIdentity name=\"System.Threading.Tasks\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\" />\r\n        <bindingRedirect oldVersion=\"0.0.0.0-2.6.10.0\" newVersion=\"2.6.10.0\" />\r\n      </dependentAssembly>\r\n      <dependentAssembly>\r\n        <assemblyIdentity name=\"System.Runtime.CompilerServices.Unsafe\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\" />\r\n        <bindingRedirect oldVersion=\"0.0.0.0-5.0.0.0\" newVersion=\"5.0.0.0\" />\r\n      </dependentAssembly>\r\n      <dependentAssembly>\r\n        <assemblyIdentity name=\"System.Memory\" publicKeyToken=\"cc7b13ffcd2ddd51\" culture=\"neutral\" />\r\n        <bindingRedirect oldVersion=\"0.0.0.0-4.0.1.1\" newVersion=\"4.0.1.1\" />\r\n      </dependentAssembly>\r\n      <dependentAssembly>\r\n        <assemblyIdentity name=\"ICSharpCode.AvalonEdit\" publicKeyToken=\"9cc39be672370310\" culture=\"neutral\" />\r\n        <bindingRedirect oldVersion=\"0.0.0.0-6.0.1.278\" newVersion=\"6.0.1.278\" />\r\n      </dependentAssembly>\r\n      <dependentAssembly>\r\n        <assemblyIdentity name=\"System.Reactive\" publicKeyToken=\"94bc3704cddfc263\" culture=\"neutral\" />\r\n        <bindingRedirect oldVersion=\"0.0.0.0-5.0.0.0\" newVersion=\"5.0.0.0\" />\r\n      </dependentAssembly>\r\n    </assemblyBinding>\r\n  </runtime>\r\n  <userSettings>\r\n    <Shadowsocks.Properties.Settings>\r\n      <setting name=\"LogViewerWidth\" serializeAs=\"String\">\r\n        <value>600</value>\r\n      </setting>\r\n      <setting name=\"LogViewerHeight\" serializeAs=\"String\">\r\n        <value>400</value>\r\n      </setting>\r\n      <setting name=\"LogViewerMaximized\" serializeAs=\"String\">\r\n        <value>True</value>\r\n      </setting>\r\n      <setting name=\"LogViewerTop\" serializeAs=\"String\">\r\n        <value>0</value>\r\n      </setting>\r\n      <setting name=\"LogViewerLeft\" serializeAs=\"String\">\r\n        <value>0</value>\r\n      </setting>\r\n    </Shadowsocks.Properties.Settings>\r\n  </userSettings>\r\n  <!-- Uncomment to dump network tracing info\r\n    <system.diagnostics>\r\n    <sources>\r\n      <source name=\"System.Net\" tracemode=\"includehex\" maxdatasize=\"1024\">\r\n        <listeners>\r\n          <add name=\"System.Net\"/>\r\n        </listeners>\r\n      </source>\r\n      <source name=\"System.Net.Cache\">\r\n        <listeners>\r\n          <add name=\"System.Net\"/>\r\n        </listeners>\r\n      </source>\r\n      <source name=\"System.Net.Http\">\r\n        <listeners>\r\n          <add name=\"System.Net\"/>\r\n        </listeners>\r\n      </source>\r\n      <source name=\"System.Net.Sockets\">\r\n        <listeners>\r\n          <add name=\"System.Net\"/>\r\n        </listeners>\r\n      </source>\r\n      <source name=\"System.Net.WebSockets\">\r\n        <listeners>\r\n          <add name=\"System.Net\"/>\r\n        </listeners>\r\n      </source>\r\n    </sources>\r\n    <switches>\r\n      <add name=\"System.Net\" value=\"Verbose\"/>\r\n      <add name=\"System.Net.Cache\" value=\"Verbose\"/>\r\n      <add name=\"System.Net.Http\" value=\"Verbose\"/>\r\n      <add name=\"System.Net.Sockets\" value=\"Verbose\"/>\r\n      <add name=\"System.Net.WebSockets\" value=\"Verbose\"/>\r\n    </switches>\r\n    <sharedListeners>\r\n      <add name=\"System.Net\"\r\n        type=\"System.Diagnostics.TextWriterTraceListener\"\r\n        initializeData=\"network-tracing.log\"\r\n      />\r\n    </sharedListeners>\r\n    <trace autoflush=\"true\"/>\r\n  </system.diagnostics>\r\n  -->\r\n</configuration>\r\n"
  },
  {
    "path": "shadowsocks-csharp/app.manifest",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\" xmlns:asmv3=\"urn:schemas-microsoft-com:asm.v3\" >\r\n  <assemblyIdentity version=\"1.0.0.0\" name=\"MyApplication.app\"/>\r\n  <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v2\">\r\n    <security>\r\n      <requestedPrivileges xmlns=\"urn:schemas-microsoft-com:asm.v3\">\r\n        <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\" />\r\n      </requestedPrivileges>\r\n    </security>\r\n  </trustInfo>\r\n  <asmv3:application>\r\n    <asmv3:windowsSettings xmlns=\"http://schemas.microsoft.com/SMI/2005/WindowsSettings\">\r\n      <dpiAware>true</dpiAware>\r\n    </asmv3:windowsSettings>\r\n  </asmv3:application>\r\n\r\n  <compatibility xmlns=\"urn:schemas-microsoft-com:compatibility.v1\">\r\n    <!-- We specify these, in addition to the UAC above, so we avoid Program Compatibility Assistant in Vista and Win7 -->\r\n    <!-- We try to avoid PCA so we can use Windows Job Objects -->\r\n    <!-- See http://stackoverflow.com/questions/3342941/kill-child-process-when-parent-process-is-killed -->\r\n\r\n    <application>\r\n      <!--The ID below indicates application support for Windows Vista -->\r\n      <supportedOS Id=\"{e2011457-1546-43c5-a5fe-008deee3d3f0}\"/>\r\n      <!--The ID below indicates application support for Windows 7 -->\r\n      <supportedOS Id=\"{35138b9a-5d96-4fbd-8e2d-a2440225f93a}\"/>\r\n    </application>\r\n  </compatibility>\r\n</assembly>"
  },
  {
    "path": "shadowsocks-csharp/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"AvalonEdit\" version=\"6.0.1\" targetFramework=\"net472\" />\r\n  <package id=\"Caseless.Fody\" version=\"1.9.0\" targetFramework=\"net472\" />\r\n  <package id=\"CommandLineParser\" version=\"2.8.0\" targetFramework=\"net472\" />\r\n  <package id=\"Costura.Fody\" version=\"4.1.0\" targetFramework=\"net472\" />\r\n  <package id=\"DynamicData\" version=\"7.1.1\" targetFramework=\"net48\" />\r\n  <package id=\"Fody\" version=\"6.3.0\" targetFramework=\"net472\" developmentDependency=\"true\" />\r\n  <package id=\"GlobalHotKey\" version=\"1.1.0\" targetFramework=\"net472\" />\r\n  <package id=\"Google.Protobuf\" version=\"3.27.2\" targetFramework=\"net48\" />\r\n  <package id=\"MdXaml\" version=\"1.6.0\" targetFramework=\"net472\" />\r\n  <package id=\"Newtonsoft.Json\" version=\"13.0.3\" targetFramework=\"net48\" />\r\n  <package id=\"NLog\" version=\"4.7.6\" targetFramework=\"net48\" />\r\n  <package id=\"Pharmacist.Common\" version=\"2.0.5\" targetFramework=\"net48\" />\r\n  <package id=\"ReactiveUI\" version=\"12.1.5\" targetFramework=\"net48\" />\r\n  <package id=\"ReactiveUI.Events.WPF\" version=\"12.1.5\" targetFramework=\"net48\" />\r\n  <package id=\"ReactiveUI.Fody\" version=\"12.1.5\" targetFramework=\"net48\" />\r\n  <package id=\"ReactiveUI.Validation\" version=\"1.8.6\" targetFramework=\"net48\" />\r\n  <package id=\"ReactiveUI.WPF\" version=\"12.1.5\" targetFramework=\"net48\" />\r\n  <package id=\"Splat\" version=\"9.8.1\" targetFramework=\"net48\" />\r\n  <package id=\"System.Buffers\" version=\"4.5.1\" targetFramework=\"net472\" />\r\n  <package id=\"System.IO\" version=\"4.3.0\" targetFramework=\"net472\" />\r\n  <package id=\"System.Memory\" version=\"4.5.4\" targetFramework=\"net472\" />\r\n  <package id=\"System.Net.Http\" version=\"4.3.4\" targetFramework=\"net472\" />\r\n  <package id=\"System.Numerics.Vectors\" version=\"4.5.0\" targetFramework=\"net472\" />\r\n  <package id=\"System.Reactive\" version=\"5.0.0\" targetFramework=\"net48\" />\r\n  <package id=\"System.Runtime\" version=\"4.3.1\" targetFramework=\"net472\" />\r\n  <package id=\"System.Runtime.CompilerServices.Unsafe\" version=\"5.0.0\" targetFramework=\"net48\" />\r\n  <package id=\"System.Security.Cryptography.Algorithms\" version=\"4.3.1\" targetFramework=\"net472\" />\r\n  <package id=\"System.Security.Cryptography.Encoding\" version=\"4.3.0\" targetFramework=\"net472\" />\r\n  <package id=\"System.Security.Cryptography.Primitives\" version=\"4.3.0\" targetFramework=\"net472\" />\r\n  <package id=\"System.Security.Cryptography.X509Certificates\" version=\"4.3.2\" targetFramework=\"net472\" />\r\n  <package id=\"System.Threading.Tasks.Extensions\" version=\"4.5.4\" targetFramework=\"net472\" />\r\n  <package id=\"System.ValueTuple\" version=\"4.5.0\" targetFramework=\"net472\" />\r\n  <package id=\"WPFLocalizeExtension\" version=\"3.8.0\" targetFramework=\"net472\" />\r\n  <package id=\"XAMLMarkupExtensions\" version=\"2.0.0\" targetFramework=\"net472\" />\r\n  <package id=\"ZXing.Net\" version=\"0.16.6\" targetFramework=\"net472\" />\r\n</packages>"
  },
  {
    "path": "shadowsocks-csharp/shadowsocks-csharp.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"12.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"..\\packages\\ReactiveUI.Fody.12.1.5\\build\\ReactiveUI.Fody.props\" Condition=\"Exists('..\\packages\\ReactiveUI.Fody.12.1.5\\build\\ReactiveUI.Fody.props')\" />\r\n  <Import Project=\"..\\packages\\Costura.Fody.4.1.0\\build\\Costura.Fody.props\" Condition=\"Exists('..\\packages\\Costura.Fody.4.1.0\\build\\Costura.Fody.props')\" />\r\n  <Import Project=\"..\\packages\\Caseless.Fody.1.9.0\\build\\Caseless.Fody.props\" Condition=\"Exists('..\\packages\\Caseless.Fody.1.9.0\\build\\Caseless.Fody.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <ProductVersion>9.0.21022</ProductVersion>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}</ProjectGuid>\r\n    <OutputType>WinExe</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Shadowsocks</RootNamespace>\r\n    <AssemblyName>Shadowsocks</AssemblyName>\r\n    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>\r\n    <FileAlignment>512</FileAlignment>\r\n    <StartupObject>\r\n    </StartupObject>\r\n    <ApplicationIcon>shadowsocks.ico</ApplicationIcon>\r\n    <IsWebBootstrapper>false</IsWebBootstrapper>\r\n    <FileUpgradeFlags>\r\n    </FileUpgradeFlags>\r\n    <UpgradeBackupLocation>\r\n    </UpgradeBackupLocation>\r\n    <OldToolsVersion>3.5</OldToolsVersion>\r\n    <TargetFrameworkProfile>\r\n    </TargetFrameworkProfile>\r\n    <NuGetPackageImportStamp>\r\n    </NuGetPackageImportStamp>\r\n    <PublishUrl>publish\\</PublishUrl>\r\n    <Install>true</Install>\r\n    <InstallFrom>Disk</InstallFrom>\r\n    <UpdateEnabled>false</UpdateEnabled>\r\n    <UpdateMode>Foreground</UpdateMode>\r\n    <UpdateInterval>7</UpdateInterval>\r\n    <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r\n    <UpdatePeriodically>false</UpdatePeriodically>\r\n    <UpdateRequired>false</UpdateRequired>\r\n    <MapFileExtensions>true</MapFileExtensions>\r\n    <ApplicationRevision>1</ApplicationRevision>\r\n    <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r\n    <UseApplicationTrust>false</UseApplicationTrust>\r\n    <BootstrapperEnabled>true</BootstrapperEnabled>\r\n    <ProjectTypeGuids>{60DC8134-EBA5-43B8-BCC9-BB4BC16C2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'Debug|x86'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\x86\\Debug\\</OutputPath>\r\n    <DefineConstants>TRACE;DEBUG</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>x86</PlatformTarget>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>ManagedMinimumRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n    <Optimize>false</Optimize>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'Release|x86'\">\r\n    <OutputPath>bin\\x86\\Release\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>x86</PlatformTarget>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>ManagedMinimumRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n    <DebugSymbols>true</DebugSymbols>\r\n  </PropertyGroup>\r\n  <PropertyGroup>\r\n    <ApplicationManifest>app.manifest</ApplicationManifest>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Caseless, Version=1.9.0.0, Culture=neutral, PublicKeyToken=409b3227471b0f0d, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\Caseless.Fody.1.9.0\\lib\\net452\\Caseless.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"CommandLine, Version=2.8.0.0, Culture=neutral, PublicKeyToken=5a870481e358d379, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\CommandLineParser.2.8.0\\lib\\net461\\CommandLine.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"Costura, Version=4.1.0.0, Culture=neutral, PublicKeyToken=9919ef960d84173d, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\Costura.Fody.4.1.0\\lib\\net40\\Costura.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"DynamicData, Version=7.1.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\DynamicData.7.1.1\\lib\\net461\\DynamicData.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"GlobalHotKey, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\GlobalHotKey.1.1.0\\lib\\GlobalHotKey.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"Google.Protobuf, Version=3.27.2.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\Google.Protobuf.3.27.2\\lib\\net45\\Google.Protobuf.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"ICSharpCode.AvalonEdit, Version=6.0.1.278, Culture=neutral, PublicKeyToken=9cc39be672370310, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\AvalonEdit.6.0.1\\lib\\net45\\ICSharpCode.AvalonEdit.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"MdXaml, Version=1.6.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\MdXaml.1.6.0\\lib\\net45\\MdXaml.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"Microsoft.VisualBasic\" />\r\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\Newtonsoft.Json.13.0.3\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\NLog.4.7.6\\lib\\net45\\NLog.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"Pharmacist.Common, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\Pharmacist.Common.2.0.5\\lib\\net472\\Pharmacist.Common.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"PresentationCore\" />\r\n    <Reference Include=\"PresentationFramework\" />\r\n    <Reference Include=\"PresentationFramework.Aero\" />\r\n    <Reference Include=\"ReactiveUI, Version=12.1.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\ReactiveUI.12.1.5\\lib\\net461\\ReactiveUI.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"ReactiveUI.Events.WPF, Version=12.1.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\ReactiveUI.Events.WPF.12.1.5\\lib\\net472\\ReactiveUI.Events.WPF.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"ReactiveUI.Fody.Helpers, Version=12.1.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\ReactiveUI.Fody.12.1.5\\lib\\net461\\ReactiveUI.Fody.Helpers.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"ReactiveUI.Validation, Version=1.8.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\ReactiveUI.Validation.1.8.6\\lib\\net461\\ReactiveUI.Validation.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"ReactiveUI.Wpf, Version=12.1.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\ReactiveUI.WPF.12.1.5\\lib\\net472\\ReactiveUI.Wpf.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"Splat, Version=9.8.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\Splat.9.8.1\\lib\\net461\\Splat.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Buffers.4.5.1\\lib\\net461\\System.Buffers.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"System.ComponentModel.Composition\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Data.DataSetExtensions\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.IO, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.IO.4.3.0\\lib\\net462\\System.IO.dll</HintPath>\r\n      <Private>True</Private>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"System.IO.Compression\" />\r\n    <Reference Include=\"System.Management\" />\r\n    <Reference Include=\"System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Memory.4.5.4\\lib\\net461\\System.Memory.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"System.Net\" />\r\n    <Reference Include=\"System.Net.Http, Version=4.1.1.3, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Net.Http.4.3.4\\lib\\net46\\System.Net.Http.dll</HintPath>\r\n      <Private>True</Private>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"System.Numerics\" />\r\n    <Reference Include=\"System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Numerics.Vectors.4.5.0\\lib\\net46\\System.Numerics.Vectors.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"System.Reactive, Version=5.0.0.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Reactive.5.0.0\\lib\\net472\\System.Reactive.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"System.Runtime, Version=4.1.1.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Runtime.4.3.1\\lib\\net462\\System.Runtime.dll</HintPath>\r\n      <Private>True</Private>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"System.Runtime.CompilerServices.Unsafe, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Runtime.CompilerServices.Unsafe.5.0.0\\lib\\net45\\System.Runtime.CompilerServices.Unsafe.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"System.Runtime.Serialization\" />\r\n    <Reference Include=\"System.Security.Cryptography.Algorithms, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Security.Cryptography.Algorithms.4.3.1\\lib\\net463\\System.Security.Cryptography.Algorithms.dll</HintPath>\r\n      <Private>True</Private>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"System.Security.Cryptography.Encoding, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Security.Cryptography.Encoding.4.3.0\\lib\\net46\\System.Security.Cryptography.Encoding.dll</HintPath>\r\n      <Private>True</Private>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"System.Security.Cryptography.Primitives, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Security.Cryptography.Primitives.4.3.0\\lib\\net46\\System.Security.Cryptography.Primitives.dll</HintPath>\r\n      <Private>True</Private>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"System.Security.Cryptography.X509Certificates, Version=4.1.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Security.Cryptography.X509Certificates.4.3.2\\lib\\net461\\System.Security.Cryptography.X509Certificates.dll</HintPath>\r\n      <Private>True</Private>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"System.ServiceModel\" />\r\n    <Reference Include=\"System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.Threading.Tasks.Extensions.4.5.4\\lib\\net461\\System.Threading.Tasks.Extensions.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"System.Transactions\" />\r\n    <Reference Include=\"System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\System.ValueTuple.4.5.0\\lib\\net47\\System.ValueTuple.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Windows\" />\r\n    <Reference Include=\"System.Windows.Forms\" />\r\n    <Reference Include=\"System.Windows.Forms.DataVisualization\" />\r\n    <Reference Include=\"System.Xaml\" />\r\n    <Reference Include=\"System.XML\" />\r\n    <Reference Include=\"UIAutomationProvider\" />\r\n    <Reference Include=\"WindowsBase\" />\r\n    <Reference Include=\"WindowsFormsIntegration\" />\r\n    <Reference Include=\"WPFLocalizeExtension, Version=3.8.0.0, Culture=neutral, PublicKeyToken=c726e0262981a1eb, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\WPFLocalizeExtension.3.8.0\\lib\\net452\\WPFLocalizeExtension.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"XAMLMarkupExtensions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=c726e0262981a1eb, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\XAMLMarkupExtensions.2.0.0\\lib\\net472\\XAMLMarkupExtensions.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"zxing, Version=0.16.6.0, Culture=neutral, PublicKeyToken=4e88037ac681fe60, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\ZXing.Net.0.16.6\\lib\\net47\\zxing.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"zxing.presentation, Version=0.16.6.0, Culture=neutral, PublicKeyToken=4e88037ac681fe60, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\ZXing.Net.0.16.6\\lib\\net47\\zxing.presentation.dll</HintPath>\r\n    </Reference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"CommandLineOption.cs\" />\r\n    <Compile Include=\"Controller\\HotkeyReg.cs\" />\r\n    <Compile Include=\"Controller\\LoggerExtension.cs\" />\r\n    <Compile Include=\"Controller\\Service\\GeositeUpdater.cs\" />\r\n    <Compile Include=\"Controller\\Service\\OnlineConfigResolver.cs\" />\r\n    <Compile Include=\"Controller\\Service\\PACDaemon.cs\" />\r\n    <Compile Include=\"Controller\\Service\\IPCService.cs\" />\r\n    <Compile Include=\"Controller\\System\\ProtocolHandler.cs\" />\r\n    <Compile Include=\"Controller\\System\\Hotkeys\\HotkeyCallbacks.cs\" />\r\n    <Compile Include=\"Encryption\\AEAD\\AEADEncryptor.cs\" />\r\n    <Compile Include=\"Encryption\\AEAD\\AEADMbedTLSEncryptor.cs\" />\r\n    <Compile Include=\"Encryption\\AEAD\\AEADOpenSSLEncryptor.cs\" />\r\n    <Compile Include=\"Encryption\\AEAD\\AEADSodiumEncryptor.cs\" />\r\n    <Compile Include=\"Encryption\\CircularBuffer\\ByteCircularBuffer.cs\" />\r\n    <Compile Include=\"Encryption\\EncryptorBase.cs\" />\r\n    <Compile Include=\"Encryption\\EncryptorFactory.cs\" />\r\n    <Compile Include=\"Encryption\\Exception\\CryptoException.cs\" />\r\n    <Compile Include=\"Encryption\\IEncryptor.cs\" />\r\n    <Compile Include=\"Encryption\\MbedTLS.cs\" />\r\n    <Compile Include=\"Encryption\\OpenSSL.cs\" />\r\n    <Compile Include=\"Encryption\\RNG.cs\" />\r\n    <Compile Include=\"Encryption\\Sodium.cs\" />\r\n    <Compile Include=\"Encryption\\Stream\\PlainEncryptor.cs\" />\r\n    <Compile Include=\"Localization\\LocalizationProvider.cs\" />\r\n    <Compile Include=\"Localization\\Strings.Designer.cs\">\r\n      <AutoGen>True</AutoGen>\r\n      <DesignTime>True</DesignTime>\r\n      <DependentUpon>Strings.resx</DependentUpon>\r\n    </Compile>\r\n    <Compile Include=\"Model\\Geosite\\Geosite.cs\" />\r\n    <Compile Include=\"Model\\HotKeyConfig.cs\" />\r\n    <Compile Include=\"Model\\NLogConfig.cs\" />\r\n    <Compile Include=\"Model\\ForwardProxyConfig.cs\" />\r\n    <Compile Include=\"Model\\SysproxyConfig.cs\" />\r\n    <Compile Include=\"Properties\\Resources.Designer.cs\">\r\n      <AutoGen>True</AutoGen>\r\n      <DesignTime>True</DesignTime>\r\n      <DependentUpon>Resources.resx</DependentUpon>\r\n    </Compile>\r\n    <Compile Include=\"Properties\\Settings.Designer.cs\">\r\n      <AutoGen>True</AutoGen>\r\n      <DesignTimeSharedInput>True</DesignTimeSharedInput>\r\n      <DependentUpon>Settings.settings</DependentUpon>\r\n    </Compile>\r\n    <Compile Include=\"Proxy\\DirectConnect.cs\" />\r\n    <Compile Include=\"Proxy\\HttpProxy.cs\" />\r\n    <Compile Include=\"Proxy\\IProxy.cs\" />\r\n    <Compile Include=\"Controller\\Strategy\\HighAvailabilityStrategy.cs\" />\r\n    <Compile Include=\"Controller\\System\\AutoStartup.cs\" />\r\n    <Compile Include=\"Controller\\FileManager.cs\" />\r\n    <Compile Include=\"Controller\\I18N.cs\" />\r\n    <Compile Include=\"Controller\\Service\\Listener.cs\" />\r\n    <Compile Include=\"Controller\\Service\\PortForwarder.cs\" />\r\n    <Compile Include=\"Controller\\Service\\UDPRelay.cs\" />\r\n    <Compile Include=\"Controller\\Service\\UpdateChecker.cs\" />\r\n    <Compile Include=\"Controller\\Service\\PACServer.cs\" />\r\n    <Compile Include=\"Model\\LogViewerConfig.cs\" />\r\n    <Compile Include=\"Model\\Server.cs\" />\r\n    <Compile Include=\"Model\\Configuration.cs\" />\r\n    <Compile Include=\"Controller\\Strategy\\BalancingStrategy.cs\" />\r\n    <Compile Include=\"Controller\\Strategy\\StrategyManager.cs\" />\r\n    <Compile Include=\"Controller\\Strategy\\IStrategy.cs\" />\r\n    <Compile Include=\"Controller\\Service\\Sip003Plugin.cs\" />\r\n    <Compile Include=\"Proxy\\Socks5Proxy.cs\" />\r\n    <Compile Include=\"Settings.cs\" />\r\n    <Compile Include=\"Controller\\System\\Hotkeys\\Hotkeys.cs\" />\r\n    <Compile Include=\"Util\\ProcessManagement\\Job.cs\" />\r\n    <Compile Include=\"Util\\ProcessManagement\\ThreadUtil.cs\" />\r\n    <Compile Include=\"Util\\Sockets\\LineReader.cs\" />\r\n    <Compile Include=\"Util\\Sockets\\SocketUtil.cs\" />\r\n    <Compile Include=\"Util\\Sockets\\WrappedSocket.cs\" />\r\n    <Compile Include=\"Util\\SystemProxy\\ProxyException.cs\" />\r\n    <Compile Include=\"Util\\SystemProxy\\Sysproxy.cs\" />\r\n    <Compile Include=\"Util\\Util.cs\" />\r\n    <Compile Include=\"Util\\ViewUtils.cs\" />\r\n    <Compile Include=\"ViewModels\\ForwardProxyViewModel.cs\" />\r\n    <Compile Include=\"ViewModels\\HotkeysViewModel.cs\" />\r\n    <Compile Include=\"ViewModels\\OnlineConfigViewModel.cs\" />\r\n    <Compile Include=\"ViewModels\\ServerSharingViewModel.cs\" />\r\n    <Compile Include=\"ViewModels\\VersionUpdatePromptViewModel.cs\" />\r\n    <Compile Include=\"Views\\ForwardProxyView.xaml.cs\">\r\n      <DependentUpon>ForwardProxyView.xaml</DependentUpon>\r\n    </Compile>\r\n    <Compile Include=\"Views\\HotkeysView.xaml.cs\">\r\n      <DependentUpon>HotkeysView.xaml</DependentUpon>\r\n    </Compile>\r\n    <Compile Include=\"Views\\OnlineConfigView.xaml.cs\">\r\n      <DependentUpon>OnlineConfigView.xaml</DependentUpon>\r\n    </Compile>\r\n    <Compile Include=\"Views\\VersionUpdatePromptView.xaml.cs\">\r\n      <DependentUpon>VersionUpdatePromptView.xaml</DependentUpon>\r\n    </Compile>\r\n    <Compile Include=\"View\\ConfigForm.cs\">\r\n      <SubType>Form</SubType>\r\n    </Compile>\r\n    <Compile Include=\"View\\ConfigForm.Designer.cs\">\r\n      <DependentUpon>ConfigForm.cs</DependentUpon>\r\n    </Compile>\r\n    <Compile Include=\"Controller\\Service\\TCPRelay.cs\" />\r\n    <Compile Include=\"Controller\\Service\\PrivoxyRunner.cs\" />\r\n    <Compile Include=\"Program.cs\" />\r\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\r\n    <Compile Include=\"Controller\\ShadowsocksController.cs\" />\r\n    <Compile Include=\"Controller\\System\\SystemProxy.cs\" />\r\n    <Compile Include=\"View\\LogForm.cs\">\r\n      <SubType>Form</SubType>\r\n    </Compile>\r\n    <Compile Include=\"View\\LogForm.Designer.cs\">\r\n      <DependentUpon>LogForm.cs</DependentUpon>\r\n    </Compile>\r\n    <Compile Include=\"View\\MenuViewController.cs\" />\r\n    <Compile Include=\"Views\\ServerSharingView.xaml.cs\">\r\n      <DependentUpon>ServerSharingView.xaml</DependentUpon>\r\n    </Compile>\r\n    <EmbeddedResource Include=\"Localization\\Strings.fr.resx\" />\r\n    <EmbeddedResource Include=\"Localization\\Strings.ja.resx\" />\r\n    <EmbeddedResource Include=\"Localization\\Strings.ko.resx\" />\r\n    <EmbeddedResource Include=\"Localization\\Strings.resx\">\r\n      <Generator>ResXFileCodeGenerator</Generator>\r\n      <LastGenOutput>Strings.Designer.cs</LastGenOutput>\r\n    </EmbeddedResource>\r\n    <EmbeddedResource Include=\"Localization\\Strings.ru.resx\" />\r\n    <EmbeddedResource Include=\"Localization\\Strings.zh-Hans.resx\" />\r\n    <EmbeddedResource Include=\"Localization\\Strings.zh-Hant.resx\" />\r\n    <EmbeddedResource Include=\"View\\ConfigForm.resx\">\r\n      <DependentUpon>ConfigForm.cs</DependentUpon>\r\n      <SubType>Designer</SubType>\r\n    </EmbeddedResource>\r\n    <EmbeddedResource Include=\"Properties\\Resources.resx\">\r\n      <Generator>PublicResXFileCodeGenerator</Generator>\r\n      <SubType>Designer</SubType>\r\n      <LastGenOutput>Resources.Designer.cs</LastGenOutput>\r\n    </EmbeddedResource>\r\n    <EmbeddedResource Include=\"View\\LogForm.resx\">\r\n      <DependentUpon>LogForm.cs</DependentUpon>\r\n    </EmbeddedResource>\r\n    <None Include=\"app.config\" />\r\n    <None Include=\"app.manifest\">\r\n      <SubType>Designer</SubType>\r\n    </None>\r\n    <None Include=\"Data\\dlc.dat\" />\r\n    <None Include=\"Data\\i18n.csv\" />\r\n    <None Include=\"Data\\libsscrypto.dll.gz\" />\r\n    <None Include=\"Data\\NLog.config\" />\r\n    <None Include=\"Data\\privoxy.exe.gz\" />\r\n    <None Include=\"Model\\Geosite\\geosite.proto\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"Data\\sysproxy.exe.gz\" />\r\n    <None Include=\"Data\\sysproxy64.exe.gz\" />\r\n    <None Include=\"packages.config\" />\r\n    <None Include=\"Properties\\Settings.settings\">\r\n      <Generator>SettingsSingleFileGenerator</Generator>\r\n      <LastGenOutput>Settings.Designer.cs</LastGenOutput>\r\n    </None>\r\n    <None Include=\"Resources\\ssw128.png\" />\r\n    <Content Include=\"Data\\abp.js\" />\r\n    <Content Include=\"Data\\privoxy_conf.txt\" />\r\n    <Content Include=\"Data\\user-rule.txt\" />\r\n    <None Include=\"FodyWeavers.xml\">\r\n      <SubType>Designer</SubType>\r\n    </None>\r\n    <Content Include=\"Resources\\ss32Fill.png\" />\r\n    <Content Include=\"Resources\\ss32In.png\" />\r\n    <Content Include=\"Resources\\ss32Out.png\" />\r\n    <Content Include=\"Resources\\ss32Outline.png\" />\r\n    <Content Include=\"shadowsocks.ico\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <BootstrapperPackage Include=\"Microsoft.Net.Client.3.5\">\r\n      <Visible>False</Visible>\r\n      <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>\r\n      <Install>false</Install>\r\n    </BootstrapperPackage>\r\n    <BootstrapperPackage Include=\"Microsoft.Net.Framework.3.0\">\r\n      <Visible>False</Visible>\r\n      <ProductName>.NET Framework 3.0 %28x86%29</ProductName>\r\n      <Install>false</Install>\r\n    </BootstrapperPackage>\r\n    <BootstrapperPackage Include=\"Microsoft.Net.Framework.3.5\">\r\n      <Visible>False</Visible>\r\n      <ProductName>.NET Framework 3.5</ProductName>\r\n      <Install>true</Install>\r\n    </BootstrapperPackage>\r\n    <BootstrapperPackage Include=\"Microsoft.Net.Framework.3.5.SP1\">\r\n      <Visible>False</Visible>\r\n      <ProductName>.NET Framework 3.5 SP1</ProductName>\r\n      <Install>false</Install>\r\n    </BootstrapperPackage>\r\n    <BootstrapperPackage Include=\"Microsoft.Windows.Installer.3.1\">\r\n      <Visible>False</Visible>\r\n      <ProductName>Windows Installer 3.1</ProductName>\r\n      <Install>true</Install>\r\n    </BootstrapperPackage>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Page Include=\"Views\\ForwardProxyView.xaml\">\r\n      <SubType>Designer</SubType>\r\n      <Generator>MSBuild:Compile</Generator>\r\n    </Page>\r\n    <Page Include=\"Views\\HotkeysView.xaml\">\r\n      <SubType>Designer</SubType>\r\n      <Generator>MSBuild:Compile</Generator>\r\n    </Page>\r\n    <Page Include=\"Views\\OnlineConfigView.xaml\">\r\n      <SubType>Designer</SubType>\r\n      <Generator>MSBuild:Compile</Generator>\r\n    </Page>\r\n    <Page Include=\"Views\\ServerSharingView.xaml\">\r\n      <SubType>Designer</SubType>\r\n      <Generator>MSBuild:Compile</Generator>\r\n    </Page>\r\n    <Page Include=\"Views\\VersionUpdatePromptView.xaml\">\r\n      <SubType>Designer</SubType>\r\n      <Generator>MSBuild:Compile</Generator>\r\n    </Page>\r\n  </ItemGroup>\r\n  <ItemGroup />\r\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\r\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\r\n    <PropertyGroup>\r\n      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>\r\n    </PropertyGroup>\r\n    <Error Condition=\"!Exists('..\\packages\\Caseless.Fody.1.9.0\\build\\Caseless.Fody.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\packages\\Caseless.Fody.1.9.0\\build\\Caseless.Fody.props'))\" />\r\n    <Error Condition=\"!Exists('..\\packages\\Costura.Fody.4.1.0\\build\\Costura.Fody.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\packages\\Costura.Fody.4.1.0\\build\\Costura.Fody.props'))\" />\r\n    <Error Condition=\"!Exists('..\\packages\\Fody.6.3.0\\build\\Fody.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\packages\\Fody.6.3.0\\build\\Fody.targets'))\" />\r\n    <Error Condition=\"!Exists('..\\packages\\ReactiveUI.Fody.12.1.5\\build\\ReactiveUI.Fody.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\packages\\ReactiveUI.Fody.12.1.5\\build\\ReactiveUI.Fody.props'))\" />\r\n  </Target>\r\n  <Import Project=\"..\\packages\\Fody.6.3.0\\build\\Fody.targets\" Condition=\"Exists('..\\packages\\Fody.6.3.0\\build\\Fody.targets')\" />\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "shadowsocks-windows.sln",
    "content": "﻿\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio Version 16\r\nVisualStudioVersion = 16.0.29709.97\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"shadowsocks-csharp\", \"shadowsocks-csharp\\shadowsocks-csharp.csproj\", \"{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"ShadowsocksTest\", \"test\\ShadowsocksTest.csproj\", \"{45913187-0685-4903-B250-DCEF0479CD86}\"\r\n\tProjectSection(ProjectDependencies) = postProject\r\n\t\t{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062} = {8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}\r\n\tEndProjectSection\r\nEndProject\r\nGlobal\r\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n\t\tDebug|Any CPU = Debug|Any CPU\r\n\t\tDebug|x86 = Debug|x86\r\n\t\tRelease|Any CPU = Release|Any CPU\r\n\t\tRelease|x86 = Release|x86\r\n\tEndGlobalSection\r\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n\t\t{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Debug|Any CPU.ActiveCfg = Debug|x86\r\n\t\t{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Debug|x86.ActiveCfg = Debug|x86\r\n\t\t{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Debug|x86.Build.0 = Debug|x86\r\n\t\t{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Debug|x86.Deploy.0 = Debug|x86\r\n\t\t{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Release|Any CPU.ActiveCfg = Release|x86\r\n\t\t{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Release|x86.ActiveCfg = Release|x86\r\n\t\t{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Release|x86.Build.0 = Release|x86\r\n\t\t{45913187-0685-4903-B250-DCEF0479CD86}.Debug|Any CPU.ActiveCfg = Debug|x86\r\n\t\t{45913187-0685-4903-B250-DCEF0479CD86}.Debug|x86.ActiveCfg = Debug|x86\r\n\t\t{45913187-0685-4903-B250-DCEF0479CD86}.Debug|x86.Build.0 = Debug|x86\r\n\t\t{45913187-0685-4903-B250-DCEF0479CD86}.Release|Any CPU.ActiveCfg = Release|x86\r\n\t\t{45913187-0685-4903-B250-DCEF0479CD86}.Release|x86.ActiveCfg = Release|x86\r\n\t\t{45913187-0685-4903-B250-DCEF0479CD86}.Release|x86.Build.0 = Release|x86\r\n\tEndGlobalSection\r\n\tGlobalSection(SolutionProperties) = preSolution\r\n\t\tHideSolutionNode = FALSE\r\n\tEndGlobalSection\r\n\tGlobalSection(ExtensibilityGlobals) = postSolution\r\n\t\tSolutionGuid = {F7E7D35B-4FDA-4385-95CF-09DADED042EA}\r\n\tEndGlobalSection\r\nEndGlobal\r\n"
  },
  {
    "path": "test/ProcessEnvironment.cs",
    "content": "﻿/* ***************************************************************************\n\nThe component allows to read the environment variables of another process\nrunning in a Windows system.\n\nHistory:\n\n - v1.2.ss Add GetCommandLine for convenience.\n \n - v1.2: Added support for inspection of 64 bit processes from 32 bit host\n - v1.1: Fixed issue with environment block size detection\n - v1.0: Initial\n\n\n******************************************************************************\n\nThe MIT License (MIT)\n\nCopyright (c) 2011-2014 Oleksiy Gapotchenko\nCopyright (c) 2018 Shadowsocks Project\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n*************************************************************************** */\n\nusing System;\nusing System.Collections.Specialized;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Management;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace Shadowsocks.Test\n{\n    static class ProcessEnvironment\n    {\n        public static StringDictionary ReadEnvironmentVariables(this Process process)\n        {\n            return _GetEnvironmentVariablesCore(process.Handle);\n        }\n\n        public static StringDictionary TryReadEnvironmentVariables(this Process process)\n        {\n            try\n            {\n                return ReadEnvironmentVariables(process);\n            }\n            catch\n            {\n                return null;\n            }\n        }\n\n        public static string GetCommandLine(this Process process)\n        {\n            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(\"SELECT CommandLine FROM Win32_Process WHERE ProcessId = \" + process.Id))\n            using (ManagementObjectCollection objects = searcher.Get())\n            {\n                return objects.Cast<ManagementBaseObject>().SingleOrDefault()?[\"CommandLine\"]?.ToString();\n            }\n\n        }\n\n        /// <summary>\n        /// Universal pointer.\n        /// </summary>\n        struct UniPtr\n        {\n            public UniPtr(IntPtr p)\n            {\n                Value = p.ToInt64();\n                Size = IntPtr.Size;\n            }\n\n            public UniPtr(long p)\n            {\n                Value = p;\n                Size = sizeof(long);\n            }\n\n            public long Value;\n            public int Size;\n\n            public static implicit operator IntPtr(UniPtr p)\n            {\n                return new IntPtr(p.Value);\n            }\n\n            public static implicit operator UniPtr(IntPtr p)\n            {\n                return new UniPtr(p);\n            }\n\n            public override string ToString()\n            {\n                return Value.ToString();\n            }\n\n            public bool FitsInNativePointer\n            {\n                get\n                {\n                    return Size <= IntPtr.Size;\n                }\n            }\n\n            public bool CanBeRepresentedByNativePointer\n            {\n                get\n                {\n                    int actualSize = Size;\n\n                    if (actualSize == 8)\n                    {\n                        if (Value >> 32 == 0)\n                            actualSize = 4;\n                    }\n\n                    return actualSize <= IntPtr.Size;\n                }\n            }\n\n            public long ToInt64()\n            {\n                return Value;\n            }\n        }\n\n        static StringDictionary _GetEnvironmentVariablesCore(IntPtr hProcess)\n        {\n            var penv = _GetPenv(hProcess);\n\n            const int maxEnvSize = 32767;\n            byte[] envData;\n\n            if (penv.CanBeRepresentedByNativePointer)\n            {\n                int dataSize;\n                if (!_HasReadAccess(hProcess, penv, out dataSize))\n                    throw new Exception(\"Unable to read environment block.\");\n\n                if (dataSize > maxEnvSize)\n                    dataSize = maxEnvSize;\n\n                envData = new byte[dataSize];\n                var res_len = IntPtr.Zero;\n                bool b = WindowsApi.ReadProcessMemory(\n                    hProcess,\n                    penv,\n                    envData,\n                    new IntPtr(dataSize),\n                    ref res_len);\n\n                if (!b || (int)res_len != dataSize)\n                    throw new Exception(\"Unable to read environment block data.\");\n            }\n            else if (penv.Size == 8 && IntPtr.Size == 4)\n            {\n                // Accessing 64 bit process under 32 bit host.\n\n                int dataSize;\n                if (!_HasReadAccessWow64(hProcess, penv.ToInt64(), out dataSize))\n                    throw new Exception(\"Unable to read environment block with WOW64 API.\");\n\n                if (dataSize > maxEnvSize)\n                    dataSize = maxEnvSize;\n\n                envData = new byte[dataSize];\n                long res_len = 0;\n                int result = WindowsApi.NtWow64ReadVirtualMemory64(\n                    hProcess,\n                    penv.ToInt64(),\n                    envData,\n                    dataSize,\n                    ref res_len);\n\n                if (result != WindowsApi.STATUS_SUCCESS || res_len != dataSize)\n                    throw new Exception(\"Unable to read environment block data with WOW64 API.\");\n            }\n            else\n            {\n                throw new Exception(\"Unable to access process memory due to unsupported bitness cardinality.\");\n            }\n\n            return _EnvToDictionary(envData);\n        }\n\n        static StringDictionary _EnvToDictionary(byte[] env)\n        {\n            var result = new StringDictionary();\n\n            int len = env.Length;\n            if (len < 4)\n                return result;\n\n            int n = len - 3;\n            for (int i = 0; i < n; ++i)\n            {\n                byte c1 = env[i];\n                byte c2 = env[i + 1];\n                byte c3 = env[i + 2];\n                byte c4 = env[i + 3];\n\n                if (c1 == 0 && c2 == 0 && c3 == 0 && c4 == 0)\n                {\n                    len = i + 3;\n                    break;\n                }\n            }\n\n            char[] environmentCharArray = Encoding.Unicode.GetChars(env, 0, len);\n\n            for (int i = 0; i < environmentCharArray.Length; i++)\n            {\n                int startIndex = i;\n                while ((environmentCharArray[i] != '=') && (environmentCharArray[i] != '\\0'))\n                {\n                    i++;\n                }\n                if (environmentCharArray[i] != '\\0')\n                {\n                    if ((i - startIndex) == 0)\n                    {\n                        while (environmentCharArray[i] != '\\0')\n                        {\n                            i++;\n                        }\n                    }\n                    else\n                    {\n                        string str = new string(environmentCharArray, startIndex, i - startIndex);\n                        i++;\n                        int num3 = i;\n                        while (environmentCharArray[i] != '\\0')\n                        {\n                            i++;\n                        }\n                        string str2 = new string(environmentCharArray, num3, i - num3);\n                        result[str] = str2;\n                    }\n                }\n            }\n\n            return result;\n        }\n\n        static bool _TryReadIntPtr32(IntPtr hProcess, IntPtr ptr, out IntPtr readPtr)\n        {\n            bool result;\n            RuntimeHelpers.PrepareConstrainedRegions();\n            try\n            {\n            }\n            finally\n            {\n                int dataSize = sizeof(Int32);\n                var data = Marshal.AllocHGlobal(dataSize);\n                IntPtr res_len = IntPtr.Zero;\n                bool b = WindowsApi.ReadProcessMemory(\n                    hProcess,\n                    ptr,\n                    data,\n                    new IntPtr(dataSize),\n                    ref res_len);\n                readPtr = new IntPtr(Marshal.ReadInt32(data));\n                Marshal.FreeHGlobal(data);\n                if (!b || (int)res_len != dataSize)\n                    result = false;\n                else\n                    result = true;\n            }\n            return result;\n        }\n\n        static bool _TryReadIntPtr(IntPtr hProcess, IntPtr ptr, out IntPtr readPtr)\n        {\n            bool result;\n            RuntimeHelpers.PrepareConstrainedRegions();\n            try\n            {\n            }\n            finally\n            {\n                int dataSize = IntPtr.Size;\n                var data = Marshal.AllocHGlobal(dataSize);\n                IntPtr res_len = IntPtr.Zero;\n                bool b = WindowsApi.ReadProcessMemory(\n                    hProcess,\n                    ptr,\n                    data,\n                    new IntPtr(dataSize),\n                    ref res_len);\n                readPtr = Marshal.ReadIntPtr(data);\n                Marshal.FreeHGlobal(data);\n                if (!b || (int)res_len != dataSize)\n                    result = false;\n                else\n                    result = true;\n            }\n            return result;\n        }\n\n        static bool _TryReadIntPtrWow64(IntPtr hProcess, long ptr, out long readPtr)\n        {\n            bool result;\n            RuntimeHelpers.PrepareConstrainedRegions();\n            try\n            {\n            }\n            finally\n            {\n                int dataSize = sizeof(long);\n                var data = Marshal.AllocHGlobal(dataSize);\n                long res_len = 0;\n                int status = WindowsApi.NtWow64ReadVirtualMemory64(\n                    hProcess,\n                    ptr,\n                    data,\n                    dataSize,\n                    ref res_len);\n                readPtr = Marshal.ReadInt64(data);\n                Marshal.FreeHGlobal(data);\n                if (status != WindowsApi.STATUS_SUCCESS || res_len != dataSize)\n                    result = false;\n                else\n                    result = true;\n            }\n            return result;\n        }\n\n        static UniPtr _GetPenv(IntPtr hProcess)\n        {\n            int processBitness = _GetProcessBitness(hProcess);\n\n            if (processBitness == 64)\n            {\n                if (Environment.Is64BitProcess)\n                {\n                    // Accessing 64 bit process under 64 bit host.\n\n                    IntPtr pPeb = _GetPeb64(hProcess);\n\n                    IntPtr ptr;\n                    if (!_TryReadIntPtr(hProcess, pPeb + 0x20, out ptr))\n                        throw new Exception(\"Unable to read PEB.\");\n\n                    IntPtr penv;\n                    if (!_TryReadIntPtr(hProcess, ptr + 0x80, out penv))\n                        throw new Exception(\"Unable to read RTL_USER_PROCESS_PARAMETERS.\");\n\n                    return penv;\n                }\n                else\n                {\n                    // Accessing 64 bit process under 32 bit host.\n\n                    var pPeb = _GetPeb64(hProcess);\n\n                    long ptr;\n                    if (!_TryReadIntPtrWow64(hProcess, pPeb.ToInt64() + 0x20, out ptr))\n                        throw new Exception(\"Unable to read PEB.\");\n\n                    long penv;\n                    if (!_TryReadIntPtrWow64(hProcess, ptr + 0x80, out penv))\n                        throw new Exception(\"Unable to read RTL_USER_PROCESS_PARAMETERS.\");\n\n                    return new UniPtr(penv);\n                }\n            }\n            else\n            {\n                // Accessing 32 bit process under 32 bit host.\n\n                IntPtr pPeb = _GetPeb32(hProcess);\n\n                IntPtr ptr;\n                if (!_TryReadIntPtr32(hProcess, pPeb + 0x10, out ptr))\n                    throw new Exception(\"Unable to read PEB.\");\n\n                IntPtr penv;\n                if (!_TryReadIntPtr32(hProcess, ptr + 0x48, out penv))\n                    throw new Exception(\"Unable to read RTL_USER_PROCESS_PARAMETERS.\");\n\n                return penv;\n            }\n        }\n\n        static int _GetProcessBitness(IntPtr hProcess)\n        {\n            if (Environment.Is64BitOperatingSystem)\n            {\n                bool wow64;\n                if (!WindowsApi.IsWow64Process(hProcess, out wow64))\n                    return 32;\n                if (wow64)\n                    return 32;\n                return 64;\n            }\n            else\n            {\n                return 32;\n            }\n        }\n\n        static IntPtr _GetPeb32(IntPtr hProcess)\n        {\n            if (Environment.Is64BitProcess)\n            {\n                var ptr = IntPtr.Zero;\n                int res_len = 0;\n                int pbiSize = IntPtr.Size;\n                int status = WindowsApi.NtQueryInformationProcess(\n                    hProcess,\n                    WindowsApi.ProcessWow64Information,\n                    ref ptr,\n                    pbiSize,\n                    ref res_len);\n                if (res_len != pbiSize)\n                    throw new Exception(\"Unable to query process information.\");\n                return ptr;\n            }\n            else\n            {\n                return _GetPebNative(hProcess);\n            }\n        }\n\n        static IntPtr _GetPebNative(IntPtr hProcess)\n        {\n            var pbi = new WindowsApi.PROCESS_BASIC_INFORMATION();\n            int res_len = 0;\n            int pbiSize = Marshal.SizeOf(pbi);\n            int status = WindowsApi.NtQueryInformationProcess(\n                hProcess,\n                WindowsApi.ProcessBasicInformation,\n                ref pbi,\n                pbiSize,\n                ref res_len);\n            if (res_len != pbiSize)\n                throw new Exception(\"Unable to query process information.\");\n            return pbi.PebBaseAddress;\n        }\n\n        static UniPtr _GetPeb64(IntPtr hProcess)\n        {\n            if (Environment.Is64BitProcess)\n            {\n                return _GetPebNative(hProcess);\n            }\n            else\n            {\n                // Get PEB via WOW64 API.\n                var pbi = new WindowsApi.PROCESS_BASIC_INFORMATION_WOW64();\n                int res_len = 0;\n                int pbiSize = Marshal.SizeOf(pbi);\n                int status = WindowsApi.NtWow64QueryInformationProcess64(\n                    hProcess,\n                    WindowsApi.ProcessBasicInformation,\n                    ref pbi,\n                    pbiSize,\n                    ref res_len);\n                if (res_len != pbiSize)\n                    throw new Exception(\"Unable to query process information.\");\n                return new UniPtr(pbi.PebBaseAddress);\n            }\n        }\n\n        static bool _HasReadAccess(IntPtr hProcess, IntPtr address, out int size)\n        {\n            size = 0;\n\n            var memInfo = new WindowsApi.MEMORY_BASIC_INFORMATION();\n            int result = WindowsApi.VirtualQueryEx(\n                hProcess,\n                address,\n                ref memInfo,\n                Marshal.SizeOf(memInfo));\n\n            if (result == 0)\n                return false;\n\n            if (memInfo.Protect == WindowsApi.PAGE_NOACCESS || memInfo.Protect == WindowsApi.PAGE_EXECUTE)\n                return false;\n\n            try\n            {\n                size = Convert.ToInt32(memInfo.RegionSize.ToInt64() - (address.ToInt64() - memInfo.BaseAddress.ToInt64()));\n            }\n            catch (OverflowException)\n            {\n                return false;\n            }\n\n            if (size <= 0)\n                return false;\n\n            return true;\n        }\n\n        static bool _HasReadAccessWow64(IntPtr hProcess, long address, out int size)\n        {\n            size = 0;\n\n            WindowsApi.MEMORY_BASIC_INFORMATION_WOW64 memInfo;\n            var memInfoType = typeof(WindowsApi.MEMORY_BASIC_INFORMATION_WOW64);\n            int memInfoLength = Marshal.SizeOf(memInfoType);\n            const int memInfoAlign = 8;\n\n            long resultLength = 0;\n            int result;\n\n            IntPtr hMemInfo = Marshal.AllocHGlobal(memInfoLength + memInfoAlign * 2);\n            try\n            {\n                // Align to 64 bits.\n                IntPtr hMemInfoAligned = new IntPtr(hMemInfo.ToInt64() & ~(memInfoAlign - 1L));\n\n                result = WindowsApi.NtWow64QueryVirtualMemory64(\n                    hProcess,\n                    address,\n                    WindowsApi.MEMORY_INFORMATION_CLASS.MemoryBasicInformation,\n                    hMemInfoAligned,\n                    memInfoLength,\n                    ref resultLength);\n\n                memInfo = (WindowsApi.MEMORY_BASIC_INFORMATION_WOW64)Marshal.PtrToStructure(hMemInfoAligned, memInfoType);\n            }\n            finally\n            {\n                Marshal.FreeHGlobal(hMemInfo);\n            }\n\n            if (result != WindowsApi.STATUS_SUCCESS)\n                return false;\n\n            if (memInfo.Protect == WindowsApi.PAGE_NOACCESS || memInfo.Protect == WindowsApi.PAGE_EXECUTE)\n                return false;\n\n            try\n            {\n                size = Convert.ToInt32(memInfo.RegionSize - (address - memInfo.BaseAddress));\n            }\n            catch (OverflowException)\n            {\n                return false;\n            }\n\n            if (size <= 0)\n                return false;\n\n            return true;\n        }\n\n        static class WindowsApi\n        {\n            [StructLayout(LayoutKind.Sequential, Pack = 1)]\n            public struct PROCESS_BASIC_INFORMATION\n            {\n                public IntPtr Reserved1;\n                public IntPtr PebBaseAddress;\n                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]\n                public IntPtr[] Reserved2;\n                public IntPtr UniqueProcessId;\n                public IntPtr Reserved3;\n            }\n\n            public const int ProcessBasicInformation = 0;\n            public const int ProcessWow64Information = 26;\n\n            [DllImport(\"ntdll.dll\", SetLastError = true)]\n            public static extern int NtQueryInformationProcess(\n                IntPtr hProcess,\n                int pic,\n                ref PROCESS_BASIC_INFORMATION pbi,\n                int cb,\n                ref int pSize);\n\n            [DllImport(\"ntdll.dll\", SetLastError = true)]\n            public static extern int NtQueryInformationProcess(\n                IntPtr hProcess,\n                int pic,\n                ref IntPtr pi,\n                int cb,\n                ref int pSize);\n\n            [DllImport(\"ntdll.dll\", SetLastError = true)]\n            public static extern int NtQueryInformationProcess(\n                IntPtr hProcess,\n                int pic,\n                ref long pi,\n                int cb,\n                ref int pSize);\n\n            [StructLayout(LayoutKind.Sequential, Pack = 1)]\n            public struct PROCESS_BASIC_INFORMATION_WOW64\n            {\n                public long Reserved1;\n                public long PebBaseAddress;\n                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]\n                public long[] Reserved2;\n                public long UniqueProcessId;\n                public long Reserved3;\n            }\n\n            [DllImport(\"ntdll.dll\", SetLastError = true)]\n            public static extern int NtWow64QueryInformationProcess64(\n                IntPtr hProcess,\n                int pic,\n                ref PROCESS_BASIC_INFORMATION_WOW64 pbi,\n                int cb,\n                ref int pSize);\n\n            [DllImport(\"kernel32.dll\", SetLastError = true)]\n            public static extern bool ReadProcessMemory(\n              IntPtr hProcess,\n              IntPtr lpBaseAddress,\n              [Out] byte[] lpBuffer,\n              IntPtr dwSize,\n              ref IntPtr lpNumberOfBytesRead);\n\n            [DllImport(\"kernel32.dll\", SetLastError = true)]\n            public static extern bool ReadProcessMemory(\n              IntPtr hProcess,\n              IntPtr lpBaseAddress,\n              IntPtr lpBuffer,\n              IntPtr dwSize,\n              ref IntPtr lpNumberOfBytesRead);\n\n            [DllImport(\"ntdll.dll\", SetLastError = true)]\n            public static extern int NtWow64ReadVirtualMemory64(\n              IntPtr hProcess,\n              long lpBaseAddress,\n              IntPtr lpBuffer,\n              long dwSize,\n              ref long lpNumberOfBytesRead);\n\n            [DllImport(\"ntdll.dll\", SetLastError = true)]\n            public static extern int NtWow64ReadVirtualMemory64(\n              IntPtr hProcess,\n              long lpBaseAddress,\n              [Out] byte[] lpBuffer,\n              long dwSize,\n              ref long lpNumberOfBytesRead);\n\n            public const int STATUS_SUCCESS = 0;\n\n            public const int PAGE_NOACCESS = 0x01;\n            public const int PAGE_EXECUTE = 0x10;\n\n            [StructLayout(LayoutKind.Sequential)]\n            public struct MEMORY_BASIC_INFORMATION\n            {\n                public IntPtr BaseAddress;\n                public IntPtr AllocationBase;\n                public int AllocationProtect;\n                public IntPtr RegionSize;\n                public int State;\n                public int Protect;\n                public int Type;\n            }\n\n            [DllImport(\"kernel32.dll\")]\n            public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);\n\n            [StructLayout(LayoutKind.Sequential)]\n            public struct MEMORY_BASIC_INFORMATION_WOW64\n            {\n                public long BaseAddress;\n                public long AllocationBase;\n                public int AllocationProtect;\n                public long RegionSize;\n                public int State;\n                public int Protect;\n                public int Type;\n            }\n\n            public enum MEMORY_INFORMATION_CLASS\n            {\n                MemoryBasicInformation\n            }\n\n            [DllImport(\"ntdll.dll\")]\n            public static extern int NtWow64QueryVirtualMemory64(\n                IntPtr hProcess,\n                long lpAddress,\n                MEMORY_INFORMATION_CLASS memoryInformationClass,\n                IntPtr lpBuffer, // MEMORY_BASIC_INFORMATION_WOW64, pointer must be 64-bit aligned\n                long memoryInformationLength,\n                ref long returnLength);\n\n            [DllImport(\"kernel32.dll\")]\n            public static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\n// General Information about an assembly is controlled through the following \r\n// set of attributes. Change these attribute values to modify the information\r\n// associated with an assembly.\r\n[assembly: AssemblyTitle(\"test\")]\r\n[assembly: AssemblyDescription(\"\")]\r\n[assembly: AssemblyConfiguration(\"\")]\r\n[assembly: AssemblyCompany(\"\")]\r\n[assembly: AssemblyProduct(\"test\")]\r\n[assembly: AssemblyCopyright(\"Copyright ©  2015\")]\r\n[assembly: AssemblyTrademark(\"\")]\r\n[assembly: AssemblyCulture(\"\")]\r\n\r\n// Setting ComVisible to false makes the types in this assembly not visible \r\n// to COM components.  If you need to access a type in this assembly from \r\n// COM, set the ComVisible attribute to true on that type.\r\n[assembly: ComVisible(false)]\r\n\r\n// The following GUID is for the ID of the typelib if this project is exposed to COM\r\n[assembly: Guid(\"f74e87ac-7e3a-444b-a1d9-8b91a674c60f\")]\r\n\r\n// Version information for an assembly consists of the following four values:\r\n//\r\n//      Major Version\r\n//      Minor Version \r\n//      Build Number\r\n//      Revision\r\n//\r\n// You can specify all the values or you can default the Build and Revision Numbers \r\n// by using the '*' as shown below:\r\n// [assembly: AssemblyVersion(\"1.0.*\")]\r\n[assembly: AssemblyVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\r\n"
  },
  {
    "path": "test/ShadowsocksTest.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"12.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <ProjectGuid>{45913187-0685-4903-B250-DCEF0479CD86}</ProjectGuid>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Shadowsocks.Test</RootNamespace>\r\n    <AssemblyName>Shadowsocks.Test</AssemblyName>\r\n    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>\r\n    <FileAlignment>512</FileAlignment>\r\n    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n    <ReferencePath>$(ProgramFiles)\\Common Files\\microsoft shared\\VSTT\\$(VisualStudioVersion)\\UITestExtensionPackages</ReferencePath>\r\n    <IsCodedUITest>False</IsCodedUITest>\r\n    <TestProjectType>UnitTest</TestProjectType>\r\n    <TargetFrameworkProfile />\r\n    <NuGetPackageImportStamp>\r\n    </NuGetPackageImportStamp>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'Debug|x86'\">\r\n    <OutputPath>bin\\x86\\Debug\\</OutputPath>\r\n    <PlatformTarget>x86</PlatformTarget>\r\n    <DefineConstants>TRACE;DEBUG</DefineConstants>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'Release|x86'\">\r\n    <OutputPath>bin\\x86\\Release\\</OutputPath>\r\n    <PlatformTarget>x86</PlatformTarget>\r\n    <Optimize>true</Optimize>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n  </PropertyGroup>\r\n  <PropertyGroup>\r\n    <StartupObject />\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"GlobalHotKey, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\packages\\GlobalHotKey.1.1.0\\lib\\GlobalHotKey.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Management\" />\r\n    <Reference Include=\"WindowsBase\" />\r\n  </ItemGroup>\r\n  <Choose>\r\n    <When Condition=\"('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'\">\r\n      <ItemGroup>\r\n        <Reference Include=\"Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\" />\r\n      </ItemGroup>\r\n    </When>\r\n    <Otherwise>\r\n      <ItemGroup>\r\n        <Reference Include=\"Microsoft.VisualStudio.QualityTools.UnitTestFramework\" />\r\n      </ItemGroup>\r\n    </Otherwise>\r\n  </Choose>\r\n  <ItemGroup>\r\n    <Compile Include=\"ProcessEnvironment.cs\" />\r\n    <Compile Include=\"Sip003PluginTest.cs\" />\r\n    <Compile Include=\"UrlTest.cs\" />\r\n    <Compile Include=\"UnitTest.cs\" />\r\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\shadowsocks-csharp\\shadowsocks-csharp.csproj\">\r\n      <Project>{8c02d2f7-7cdb-4d55-9f25-cd03ef4aa062}</Project>\r\n      <Name>shadowsocks-csharp</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"app.config\" />\r\n    <None Include=\"packages.config\" />\r\n  </ItemGroup>\r\n  <Choose>\r\n    <When Condition=\"'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'\">\r\n      <ItemGroup>\r\n        <Reference Include=\"Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n          <Private>False</Private>\r\n        </Reference>\r\n        <Reference Include=\"Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n          <Private>False</Private>\r\n        </Reference>\r\n        <Reference Include=\"Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n          <Private>False</Private>\r\n        </Reference>\r\n        <Reference Include=\"Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n          <Private>False</Private>\r\n        </Reference>\r\n      </ItemGroup>\r\n    </When>\r\n  </Choose>\r\n  <Import Project=\"$(VSToolsPath)\\TeamTest\\Microsoft.TestTools.targets\" Condition=\"Exists('$(VSToolsPath)\\TeamTest\\Microsoft.TestTools.targets')\" />\r\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>\r\n"
  },
  {
    "path": "test/Sip003PluginTest.cs",
    "content": "﻿using System;\r\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\r\nusing System.Threading;\r\nusing System.Collections.Generic;\r\nusing Shadowsocks.Model;\r\nusing Shadowsocks.Controller.Service;\r\nusing System.Diagnostics;\r\nusing System.Net;\r\n\r\nnamespace Shadowsocks.Test\r\n{\r\n    [TestClass]\r\n    public class Sip003PluginTest\r\n    {\r\n        string fake_plugin = \"ftp\";\r\n\r\n        [TestMethod]\r\n        public void TestSip003Plugin_NoPlugin()\r\n        {\r\n\r\n\r\n            var NoPlugin = Sip003Plugin.CreateIfConfigured(\r\n                new Server\r\n                {\r\n                    server = \"192.168.100.1\",\r\n                    server_port = 8888,\r\n                    password = \"test\",\r\n                    method = \"bf-cfb\"\r\n                },\r\n                false);\r\n\r\n            RunPluginSupportTest(\r\n                NoPlugin,\r\n                \"\",\r\n                \"\",\r\n                \"\",\r\n                \"192.168.100.1\",\r\n                8888);\r\n        }\r\n\r\n        [TestMethod]\r\n        public void TestSip003Plugin_Plugin()\r\n        {\r\n            var Plugin = Sip003Plugin.CreateIfConfigured(\r\n                new Server\r\n                {\r\n                    server = \"192.168.100.1\",\r\n                    server_port = 8888,\r\n                    password = \"test\",\r\n                    method = \"bf-cfb\",\r\n                    plugin = fake_plugin\r\n                },\r\n                false);\r\n\r\n            RunPluginSupportTest(\r\n                Plugin,\r\n                fake_plugin,\r\n                \"\",\r\n                \"\",\r\n                \"192.168.100.1\",\r\n                8888);\r\n        }\r\n\r\n        [TestMethod]\r\n        public void TestSip003Plugin_PluginWithOpts()\r\n        {\r\n            var PluginWithOpts = Sip003Plugin.CreateIfConfigured(\r\n                new Server\r\n                {\r\n                    server = \"192.168.100.1\",\r\n                    server_port = 8888,\r\n                    password = \"test\",\r\n                    method = \"bf-cfb\",\r\n                    plugin = fake_plugin,\r\n                    plugin_opts = \"_option\"\r\n                },\r\n                false);\r\n\r\n            RunPluginSupportTest(\r\n                PluginWithOpts,\r\n                fake_plugin,\r\n                \"_option\",\r\n                \"\",\r\n                \"192.168.100.1\",\r\n                8888);\r\n        }\r\n\r\n        [TestMethod]\r\n        public void TestSip003Plugin_PluginWithArgs()\r\n        {\r\n            var PluginWithArgs = Sip003Plugin.CreateIfConfigured(\r\n                new Server\r\n                {\r\n                    server = \"192.168.100.1\",\r\n                    server_port = 8888,\r\n                    password = \"test\",\r\n                    method = \"bf-cfb\",\r\n                    plugin = fake_plugin,\r\n                    plugin_args = \"_test\"\r\n                },\r\n                false);\r\n\r\n            RunPluginSupportTest(\r\n                PluginWithArgs,\r\n                fake_plugin,\r\n                \"\",\r\n                \"_test\",\r\n                \"192.168.100.1\",\r\n                8888);\r\n        }\r\n\r\n        [TestMethod]\r\n        public void TestSip003Plugin_PluginWithOptsAndArgs()\r\n        {\r\n            var PluginWithOptsAndArgs = Sip003Plugin.CreateIfConfigured(\r\n                new Server\r\n                {\r\n                    server = \"192.168.100.1\",\r\n                    server_port = 8888,\r\n                    password = \"test\",\r\n                    method = \"bf-cfb\",\r\n                    plugin = fake_plugin,\r\n                    plugin_opts = \"_option\",\r\n                    plugin_args = \"_test\"\r\n                },\r\n                false);\r\n\r\n            RunPluginSupportTest(\r\n                PluginWithOptsAndArgs,\r\n                fake_plugin,\r\n                \"_option\",\r\n                \"_test\",\r\n                \"192.168.100.1\",\r\n                8888);\r\n        }\r\n\r\n        [TestMethod]\r\n        public void TestSip003Plugin_PluginWithArgsReplaced()\r\n        {\r\n            var PluginWithArgsReplaced = Sip003Plugin.CreateIfConfigured(\r\n                new Server\r\n                {\r\n                    server = \"192.168.100.1\",\r\n                    server_port = 8888,\r\n                    password = \"test\",\r\n                    method = \"bf-cfb\",\r\n                    plugin = fake_plugin,\r\n                    plugin_args = \"_test,%SS_REMOTE_HOST%\"\r\n                },\r\n                false);\r\n\r\n            RunPluginSupportTest(\r\n                PluginWithArgsReplaced,\r\n                fake_plugin,\r\n                \"\",\r\n                \"_test,192.168.100.1\",\r\n                \"192.168.100.1\",\r\n                8888);\r\n        }\r\n\r\n        [TestMethod]\r\n        public void TestSip003Plugin_PluginWithOptsAndArgsReplaced()\r\n        {\r\n            var PluginWithOptsAndArgsReplaced = Sip003Plugin.CreateIfConfigured(\r\n                new Server\r\n                {\r\n                    server = \"192.168.100.1\",\r\n                    server_port = 8888,\r\n                    password = \"test\",\r\n                    method = \"bf-cfb\",\r\n                    plugin = fake_plugin,\r\n                    plugin_opts = \"_option\",\r\n                    plugin_args = \"_test,%SS_REMOTE_HOST%,%SS_PLUGIN_OPTIONS%\"\r\n                },\r\n                false);\r\n\r\n            RunPluginSupportTest(\r\n                PluginWithOptsAndArgsReplaced,\r\n                fake_plugin,\r\n                \"_option\",\r\n                \"_test,192.168.100.1,_option\",\r\n                \"192.168.100.1\",\r\n                8888);\r\n        }\r\n\r\n        private static void RunPluginSupportTest(Sip003Plugin plugin, string pluginName, string pluginOpts, string pluginArgs, string serverAddress, int serverPort)\r\n        {\r\n\r\n            if (string.IsNullOrWhiteSpace(pluginName)) return;\r\n\r\n            plugin.StartIfNeeded();\r\n\r\n            Process[] processes = Process.GetProcessesByName(pluginName);\r\n            Assert.AreEqual(processes.Length, 1);\r\n            Process p = processes[0];\r\n\r\n\r\n            var penv = ProcessEnvironment.ReadEnvironmentVariables(p);\r\n            var pcmd = ProcessEnvironment.GetCommandLine(p).Trim();\r\n            pcmd = pcmd.IndexOf(' ') >= 0 ? pcmd.Substring(pcmd.IndexOf(' ') + 1) : \"\";\r\n            \r\n            Assert.AreEqual(penv[\"SS_REMOTE_HOST\"], serverAddress);\r\n            Assert.AreEqual(penv[\"SS_REMOTE_PORT\"], serverPort.ToString());\r\n            Assert.AreEqual(penv[\"SS_LOCAL_HOST\"], IPAddress.Loopback.ToString());\r\n            \r\n            int _ignored;\r\n            Assert.IsTrue(int.TryParse(penv[\"SS_LOCAL_PORT\"], out _ignored));\r\n            \r\n            Assert.AreEqual(penv[\"SS_PLUGIN_OPTIONS\"], pluginOpts);\r\n            Assert.AreEqual(pcmd, pluginArgs);\r\n\r\n\r\n            plugin.Dispose();\r\n            for (int i = 0; i < 50; i++)\r\n            {\r\n                if (Process.GetProcessesByName(pluginName).Length == 0) return;\r\n                Thread.Sleep(50);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/UnitTest.cs",
    "content": "﻿using System;\r\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\r\nusing Shadowsocks.Controller;\r\nusing GlobalHotKey;\r\nusing System.Windows.Input;\r\nusing System.Threading;\r\nusing System.Collections.Generic;\r\nusing Shadowsocks.Controller.Hotkeys;\r\nusing System.Diagnostics;\r\n\r\n\r\nnamespace Shadowsocks.Test\r\n{\r\n    [TestClass]\r\n    public class UnitTest\r\n    {\r\n        [TestMethod]\r\n        public void TestHotKey2Str()\r\n        {\r\n            Assert.AreEqual(\"Ctrl+A\", HotKeys.HotKey2Str(Key.A, ModifierKeys.Control));\r\n            Assert.AreEqual(\"Ctrl+Alt+D2\", HotKeys.HotKey2Str(Key.D2, (ModifierKeys.Alt | ModifierKeys.Control)));\r\n            Assert.AreEqual(\"Ctrl+Alt+Shift+NumPad7\", HotKeys.HotKey2Str(Key.NumPad7, (ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift)));\r\n            Assert.AreEqual(\"Ctrl+Alt+Shift+F6\", HotKeys.HotKey2Str(Key.F6, (ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift)));\r\n            Assert.AreNotEqual(\"Ctrl+Shift+Alt+F6\", HotKeys.HotKey2Str(Key.F6, (ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift)));\r\n        }\r\n\r\n        [TestMethod]\r\n        public void TestStr2HotKey()\r\n        {\r\n            Assert.IsTrue(HotKeys.Str2HotKey(\"Ctrl+A\").Equals(new HotKey(Key.A, ModifierKeys.Control)));\r\n            Assert.IsTrue(HotKeys.Str2HotKey(\"Ctrl+Alt+A\").Equals(new HotKey(Key.A, (ModifierKeys.Control | ModifierKeys.Alt))));\r\n            Assert.IsTrue(HotKeys.Str2HotKey(\"Ctrl+Shift+A\").Equals(new HotKey(Key.A, (ModifierKeys.Control | ModifierKeys.Shift))));\r\n            Assert.IsTrue(HotKeys.Str2HotKey(\"Ctrl+Alt+Shift+A\").Equals(new HotKey(Key.A, (ModifierKeys.Control | ModifierKeys.Alt | ModifierKeys.Shift))));\r\n            HotKey testKey0 = HotKeys.Str2HotKey(\"Ctrl+Alt+Shift+A\");\r\n            Assert.IsTrue(testKey0 != null && testKey0.Equals(new HotKey(Key.A, (ModifierKeys.Control | ModifierKeys.Alt | ModifierKeys.Shift))));\r\n            HotKey testKey1 = HotKeys.Str2HotKey(\"Ctrl+Alt+Shift+F2\");\r\n            Assert.IsTrue(testKey1 != null && testKey1.Equals(new HotKey(Key.F2, (ModifierKeys.Control | ModifierKeys.Alt | ModifierKeys.Shift))));\r\n            HotKey testKey2 = HotKeys.Str2HotKey(\"Ctrl+Shift+Alt+D7\");\r\n            Assert.IsTrue(testKey2 != null && testKey2.Equals(new HotKey(Key.D7, (ModifierKeys.Control | ModifierKeys.Alt | ModifierKeys.Shift))));\r\n            HotKey testKey3 = HotKeys.Str2HotKey(\"Ctrl+Shift+Alt+NumPad7\");\r\n            Assert.IsTrue(testKey3 != null && testKey3.Equals(new HotKey(Key.NumPad7, (ModifierKeys.Control | ModifierKeys.Alt | ModifierKeys.Shift))));\r\n        }\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/UrlTest.cs",
    "content": "﻿using System;\r\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\r\nusing Shadowsocks.Controller;\r\nusing System.Threading;\r\nusing System.Collections.Generic;\r\nusing Shadowsocks.Model;\r\nusing System.Diagnostics;\r\n\r\nnamespace Shadowsocks.Test\r\n{\r\n    [TestClass]\r\n    public class UrlTest\r\n    {\r\n        Server server1, server1WithRemark, server1WithPlugin, server1WithPluginAndRemark;\r\n        string server1CanonUrl, server1WithRemarkCanonUrl, server1WithPluginCanonUrl, server1WithPluginAndRemarkCanonUrl;\r\n\r\n        Server server2, server2WithRemark, server2WithPlugin, server2WithPluginAndRemark;\r\n        string server2CanonUrl, server2WithRemarkCanonUrl, server2WithPluginCanonUrl, server2WithPluginAndRemarkCanonUrl;\r\n\r\n\r\n        [TestInitialize]\r\n        public void PrepareTestData()\r\n        {\r\n            server1 = new Server\r\n            {\r\n                server = \"192.168.100.1\",\r\n                server_port = 8888,\r\n                password = \"test\",\r\n                method = \"bf-cfb\"\r\n            };\r\n            server1CanonUrl = \"ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xMDAuMTo4ODg4\";\r\n\r\n            // server2 has base64 padding\r\n            server2 = new Server\r\n            {\r\n                server = \"192.168.1.1\",\r\n                server_port = 8388,\r\n                password = \"test\",\r\n                method = \"bf-cfb\"\r\n            };\r\n            server2CanonUrl = \"ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xLjE6ODM4OA==\";\r\n\r\n            server1WithRemark = new Server\r\n            {\r\n                server = server1.server,\r\n                server_port = server1.server_port,\r\n                password = server1.password,\r\n                method = server1.method,\r\n                remarks = \"example-server 1\"\r\n            };\r\n            server1WithRemarkCanonUrl = \"ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xMDAuMTo4ODg4#example-server+1\";\r\n\r\n            server2WithRemark = new Server\r\n            {\r\n                server = server2.server,\r\n                server_port = server2.server_port,\r\n                password = server2.password,\r\n                method = server2.method,\r\n                remarks = \"example-server 2\"\r\n            };\r\n\r\n            server2WithRemarkCanonUrl = \"ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xLjE6ODM4OA==#example-server+2\";\r\n\r\n            server1WithPlugin = new Server\r\n            {\r\n                server = server1.server,\r\n                server_port = server1.server_port,\r\n                password = server1.password,\r\n                method = server1.method,\r\n                plugin = \"obfs-local\",\r\n                plugin_opts = \"obfs=http;obfs-host=google.com\"\r\n            };\r\n            server1WithPluginCanonUrl =\r\n                \"ss://YmYtY2ZiOnRlc3Q@192.168.100.1:8888/?plugin=obfs-local%3bobfs%3dhttp%3bobfs-host%3dgoogle.com\";\r\n\r\n            server2WithPlugin = new Server\r\n            {\r\n                server = server2.server,\r\n                server_port = server2.server_port,\r\n                password = server2.password,\r\n                method = server2.method,\r\n                plugin = \"obfs-local\",\r\n                plugin_opts = \"obfs=http;obfs-host=google.com\"\r\n            };\r\n            server2WithPluginCanonUrl =\r\n                \"ss://YmYtY2ZiOnRlc3Q@192.168.1.1:8388/?plugin=obfs-local%3bobfs%3dhttp%3bobfs-host%3dgoogle.com\";\r\n\r\n            server1WithPluginAndRemark = new Server\r\n            {\r\n                server = server1.server,\r\n                server_port = server1.server_port,\r\n                password = server1.password,\r\n                method = server1.method,\r\n                plugin = server1WithPlugin.plugin,\r\n                plugin_opts = server1WithPlugin.plugin_opts,\r\n                remarks = server1WithRemark.remarks\r\n            };\r\n            server1WithPluginAndRemarkCanonUrl =\r\n                \"ss://YmYtY2ZiOnRlc3Q@192.168.100.1:8888/?plugin=obfs-local%3bobfs%3dhttp%3bobfs-host%3dgoogle.com#example-server+1\";\r\n\r\n            server2WithPluginAndRemark = new Server\r\n            {\r\n                server = server2.server,\r\n                server_port = server2.server_port,\r\n                password = server2.password,\r\n                method = server2.method,\r\n                plugin = server2WithPlugin.plugin,\r\n                plugin_opts = server2WithPlugin.plugin_opts,\r\n                remarks = server2WithRemark.remarks\r\n            };\r\n            server2WithPluginAndRemarkCanonUrl =\r\n                \"ss://YmYtY2ZiOnRlc3Q@192.168.1.1:8388/?plugin=obfs-local%3bobfs%3dhttp%3bobfs-host%3dgoogle.com#example-server+2\";\r\n        }\r\n\r\n        [TestMethod]\r\n        public void TestParseUrl_Server1()\r\n        {\r\n            RunParseShadowsocksUrlTest(\r\n                string.Join(\r\n                    \"\\r\\n\",\r\n                    server1CanonUrl,\r\n                    \"\\r\\n\",\r\n                    \"ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xMDAuMTo4ODg4/\",\r\n                    server1WithRemarkCanonUrl,\r\n                    \"ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xMDAuMTo4ODg4/#example-server+1\"),\r\n                new[]\r\n                {\r\n                    server1,\r\n                    server1,\r\n                    server1WithRemark,\r\n                    server1WithRemark\r\n                });\r\n\r\n            RunParseShadowsocksUrlTest(\r\n                string.Join(\r\n                    \"\\r\\n\",\r\n                    \"ss://YmYtY2ZiOnRlc3Q@192.168.100.1:8888\",\r\n                    \"\\r\\n\",\r\n                    \"ss://YmYtY2ZiOnRlc3Q@192.168.100.1:8888/\",\r\n                    \"ss://YmYtY2ZiOnRlc3Q@192.168.100.1:8888#example-server+1\",\r\n                    \"ss://YmYtY2ZiOnRlc3Q@192.168.100.1:8888/#example-server+1\",\r\n                    server1WithPluginCanonUrl,\r\n                    server1WithPluginAndRemarkCanonUrl,\r\n                    \"ss://YmYtY2ZiOnRlc3Q@192.168.100.1:8888/?plugin=obfs-local%3bobfs%3dhttp%3bobfs-host%3dgoogle.com&unsupported=1#example-server+1\"),\r\n                new[]\r\n                {\r\n                    server1,\r\n                    server1,\r\n                    server1WithRemark,\r\n                    server1WithRemark,\r\n                    server1WithPlugin,\r\n                    server1WithPluginAndRemark,\r\n                    server1WithPluginAndRemark\r\n                });\r\n        }\r\n\r\n\r\n\r\n        [TestMethod]\r\n        public void TestParseUrl_Server2()\r\n        {\r\n            RunParseShadowsocksUrlTest(\r\n                string.Join(\r\n                    \"\\r\\n\",\r\n                    server2CanonUrl,\r\n                    \"\\r\\n\",\r\n                    \"ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xLjE6ODM4OA==/\",\r\n                    server2WithRemarkCanonUrl,\r\n                    \"ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xLjE6ODM4OA==/#example-server+2\"),\r\n                new[]\r\n                {\r\n                    server2,\r\n                    server2,\r\n                    server2WithRemark,\r\n                    server2WithRemark\r\n                });\r\n\r\n            RunParseShadowsocksUrlTest(\r\n                string.Join(\r\n                    \"\\r\\n\",\r\n                    \"ss://YmYtY2ZiOnRlc3Q@192.168.1.1:8388\",\r\n                    \"\\r\\n\",\r\n                    \"ss://YmYtY2ZiOnRlc3Q@192.168.1.1:8388/\",\r\n                    \"ss://YmYtY2ZiOnRlc3Q@192.168.1.1:8388#example-server+2\",\r\n                    \"ss://YmYtY2ZiOnRlc3Q@192.168.1.1:8388/#example-server+2\",\r\n                    server2WithPluginCanonUrl,\r\n                    server2WithPluginAndRemarkCanonUrl,\r\n                    \"ss://YmYtY2ZiOnRlc3Q@192.168.1.1:8388/?plugin=obfs-local%3bobfs%3dhttp%3bobfs-host%3dgoogle.com&unsupported=1#example-server+2\"),\r\n                new[]\r\n                {\r\n                    server2,\r\n                    server2,\r\n                    server2WithRemark,\r\n                    server2WithRemark,\r\n                    server2WithPlugin,\r\n                    server2WithPluginAndRemark,\r\n                    server2WithPluginAndRemark\r\n                });\r\n        }\r\n\r\n\r\n        [TestMethod]\r\n        public void TestUrlGenerate()\r\n        { \r\n            var generateUrlCases = new Dictionary<string, Server>\r\n            {\r\n                [server1CanonUrl] = server1,\r\n                [server1WithRemarkCanonUrl] = server1WithRemark,\r\n                [server1WithPluginCanonUrl] = server1WithPlugin,\r\n                [server1WithPluginAndRemarkCanonUrl] = server1WithPluginAndRemark\r\n            };\r\n            RunGenerateShadowsocksUrlTest(generateUrlCases);\r\n        }\r\n\r\n        private static void RunParseShadowsocksUrlTest(string testCase, IReadOnlyList<Server> expected)\r\n        {\r\n            var actual = Server.GetServers(testCase);\r\n            if (actual.Count != expected.Count)\r\n            {\r\n                Assert.Fail(\"Wrong number of configs. Expected: {0}. Actual: {1}\", expected.Count, actual.Count);\r\n            }\r\n\r\n            for (int i = 0; i < expected.Count; i++)\r\n            {\r\n                var expectedServer = expected[i];\r\n                var actualServer = actual[i];\r\n\r\n                Assert.AreEqual(expectedServer.server, actualServer.server);\r\n                Assert.AreEqual(expectedServer.server_port, actualServer.server_port);\r\n                Assert.AreEqual(expectedServer.password, actualServer.password);\r\n                Assert.AreEqual(expectedServer.method, actualServer.method);\r\n                Assert.AreEqual(expectedServer.plugin, actualServer.plugin);\r\n                Assert.AreEqual(expectedServer.plugin_opts, actualServer.plugin_opts);\r\n                Assert.AreEqual(expectedServer.remarks, actualServer.remarks);\r\n                Assert.AreEqual(expectedServer.timeout, actualServer.timeout);\r\n            }\r\n        }\r\n\r\n        private static void RunGenerateShadowsocksUrlTest(IReadOnlyDictionary<string, Server> testCases)\r\n        {\r\n            foreach (var testCase in testCases)\r\n            {\r\n                string expected = testCase.Key;\r\n                Server config = testCase.Value;\r\n\r\n                var actual = config.GetURL(true);\r\n                Assert.AreEqual(expected, actual);\r\n            }\r\n        }\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/app.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n  <runtime>\n    <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n      <dependentAssembly>\n        <assemblyIdentity name=\"System.Runtime.CompilerServices.Unsafe\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\" />\n        <bindingRedirect oldVersion=\"0.0.0.0-5.0.0.0\" newVersion=\"5.0.0.0\" />\n      </dependentAssembly>\n      <dependentAssembly>\n        <assemblyIdentity name=\"System.Memory\" publicKeyToken=\"cc7b13ffcd2ddd51\" culture=\"neutral\" />\n        <bindingRedirect oldVersion=\"0.0.0.0-4.0.1.1\" newVersion=\"4.0.1.1\" />\n      </dependentAssembly>\n      <dependentAssembly>\n        <assemblyIdentity name=\"ICSharpCode.AvalonEdit\" publicKeyToken=\"9cc39be672370310\" culture=\"neutral\" />\n        <bindingRedirect oldVersion=\"0.0.0.0-6.0.1.278\" newVersion=\"6.0.1.278\" />\n      </dependentAssembly>\n    </assemblyBinding>\n  </runtime>\n<startup><supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.8\" /></startup></configuration>\n"
  },
  {
    "path": "test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"GlobalHotKey\" version=\"1.1.0\" targetFramework=\"net472\" />\r\n</packages>"
  }
]