diff --git a/shadowsocks-csharp/3rd/zxing/common/StringUtils.cs b/shadowsocks-csharp/3rd/zxing/common/StringUtils.cs index 55b5ec91..f15fd8e6 100755 --- a/shadowsocks-csharp/3rd/zxing/common/StringUtils.cs +++ b/shadowsocks-csharp/3rd/zxing/common/StringUtils.cs @@ -30,16 +30,16 @@ namespace ZXing.Common #if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || WINDOWS_PHONE80 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE) private const String PLATFORM_DEFAULT_ENCODING = "UTF-8"; #else - private static String PLATFORM_DEFAULT_ENCODING = Encoding.Default.WebName; + private static string PLATFORM_DEFAULT_ENCODING = Encoding.Default.WebName; #endif - public static String SHIFT_JIS = "SJIS"; - public static String GB2312 = "GB2312"; - private const String EUC_JP = "EUC-JP"; - private const String UTF8 = "UTF-8"; - private const String ISO88591 = "ISO-8859-1"; + public static string SHIFT_JIS = "SJIS"; + public static string GB2312 = "GB2312"; + private const string EUC_JP = "EUC-JP"; + private const string UTF8 = "UTF-8"; + private const string ISO88591 = "ISO-8859-1"; private static readonly bool ASSUME_SHIFT_JIS = - String.Compare(SHIFT_JIS, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0 || - String.Compare(EUC_JP, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0; + string.Equals(SHIFT_JIS, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) || + string.Equals(EUC_JP, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase); /// /// Guesses the encoding. diff --git a/shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGFPoly.cs b/shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGFPoly.cs index 427fe11d..96df3e69 100755 --- a/shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGFPoly.cs +++ b/shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGFPoly.cs @@ -145,7 +145,7 @@ namespace ZXing.Common.ReedSolomon internal GenericGFPoly addOrSubtract(GenericGFPoly other) { - if (!field.Equals(other.field)) + if (field != other.field) { throw new ArgumentException("GenericGFPolys do not have same GenericGF field"); } @@ -181,7 +181,7 @@ namespace ZXing.Common.ReedSolomon internal GenericGFPoly multiply(GenericGFPoly other) { - if (!field.Equals(other.field)) + if (field != other.field) { throw new ArgumentException("GenericGFPolys do not have same GenericGF field"); } @@ -246,7 +246,7 @@ namespace ZXing.Common.ReedSolomon internal GenericGFPoly[] divide(GenericGFPoly other) { - if (!field.Equals(other.field)) + if (field != other.field) { throw new ArgumentException("GenericGFPolys do not have same GenericGF field"); } diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/Encoder.cs b/shadowsocks-csharp/3rd/zxing/qrcode/encoder/Encoder.cs index 56c9a9a8..dbae7bf3 100755 --- a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/Encoder.cs +++ b/shadowsocks-csharp/3rd/zxing/qrcode/encoder/Encoder.cs @@ -86,7 +86,7 @@ namespace ZXing.QrCode.Internal { encoding = DEFAULT_BYTE_MODE_ENCODING; } - bool generateECI = !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding); + bool generateECI = !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding, StringComparison.OrdinalIgnoreCase); #else // Silverlight supports only UTF-8 and UTF-16 out-of-the-box const string encoding = "UTF-8"; @@ -514,7 +514,8 @@ namespace ZXing.QrCode.Internal BitArray bits, String encoding) { - if (mode.Equals(Mode.BYTE)) + // TODO: check the purpose of this .Equals(obj) + if (mode == Mode.BYTE) append8BitBytes(content, bits, encoding); else throw new WriterException("Invalid mode: " + mode); diff --git a/shadowsocks-csharp/Controller/FileManager.cs b/shadowsocks-csharp/Controller/FileManager.cs index f6edf147..60dc66e4 100755 --- a/shadowsocks-csharp/Controller/FileManager.cs +++ b/shadowsocks-csharp/Controller/FileManager.cs @@ -10,37 +10,35 @@ namespace Shadowsocks.Controller { try { - FileStream _FileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write); - _FileStream.Write(content, 0, content.Length); - _FileStream.Close(); + using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) + fs.Write(content, 0, content.Length); return true; } - catch (Exception _Exception) + catch (Exception ex) { Console.WriteLine("Exception caught in process: {0}", - _Exception.ToString()); + ex.ToString()); } return false; } public static void UncompressFile(string fileName, byte[] content) { - FileStream destinationFile = File.Create(fileName); - // Because the uncompressed size of the file is unknown, // we are using an arbitrary buffer size. byte[] buffer = new byte[4096]; int n; - using (GZipStream input = new GZipStream(new MemoryStream(content), + using(var fs = File.Create(fileName)) + using (var input = new GZipStream( + new MemoryStream(content), CompressionMode.Decompress, false)) { while ((n = input.Read(buffer, 0, buffer.Length)) > 0) { - destinationFile.Write(buffer, 0, n); + fs.Write(buffer, 0, n); } } - destinationFile.Close(); } } diff --git a/shadowsocks-csharp/Controller/I18N.cs b/shadowsocks-csharp/Controller/I18N.cs index c99d0f14..af49e36c 100755 --- a/shadowsocks-csharp/Controller/I18N.cs +++ b/shadowsocks-csharp/Controller/I18N.cs @@ -1,11 +1,12 @@ -using Shadowsocks.Properties; -using System; +using System; using System.Collections.Generic; -using System.Text; -using System.Text.RegularExpressions; +using System.Globalization; +using System.IO; namespace Shadowsocks.Controller { + using Shadowsocks.Properties; + public class I18N { protected static Dictionary Strings; @@ -13,19 +14,20 @@ namespace Shadowsocks.Controller { Strings = new Dictionary(); - if (System.Globalization.CultureInfo.CurrentCulture.IetfLanguageTag.ToLowerInvariant().StartsWith("zh")) + if (CultureInfo.CurrentCulture.IetfLanguageTag.StartsWith("zh", StringComparison.OrdinalIgnoreCase)) { - string[] lines = Regex.Split(Resources.cn, "\r\n|\r|\n"); - foreach (string line in lines) + using (var sr = new StringReader(Resources.cn)) { - if (line.StartsWith("#")) - { - continue; - } - string[] kv = Regex.Split(line, "="); - if (kv.Length == 2) + string line; + while ((line = sr.ReadLine()) != null) { - Strings[kv[0]] = kv[1]; + if (line[0] == '#') + continue; + + var pos = line.IndexOf('='); + if (pos < 1) + continue; + Strings[line.Substring(0, pos)] = line.Substring(pos + 1); } } } diff --git a/shadowsocks-csharp/Controller/Service/GfwListUpdater.cs b/shadowsocks-csharp/Controller/Service/GfwListUpdater.cs index 2497090d..42dc70ca 100644 --- a/shadowsocks-csharp/Controller/Service/GfwListUpdater.cs +++ b/shadowsocks-csharp/Controller/Service/GfwListUpdater.cs @@ -42,7 +42,7 @@ namespace Shadowsocks.Controller string[] rules = local.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string rule in rules) { - if (rule.StartsWith("!") || rule.StartsWith("[")) + if (rule[0] == '!' || rule[0] == '[') continue; lines.Add(rule); } @@ -97,7 +97,7 @@ namespace Shadowsocks.Controller List valid_lines = new List(lines.Length); foreach (string line in lines) { - if (line.StartsWith("!") || line.StartsWith("[")) + if (line[0] == '!' || line[0] == '[') continue; valid_lines.Add(line); } diff --git a/shadowsocks-csharp/Controller/ShadowsocksController.cs b/shadowsocks-csharp/Controller/ShadowsocksController.cs index f7d50bd3..0950c2d9 100755 --- a/shadowsocks-csharp/Controller/ShadowsocksController.cs +++ b/shadowsocks-csharp/Controller/ShadowsocksController.cs @@ -457,7 +457,7 @@ namespace Shadowsocks.Controller string[] rules = local.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string rule in rules) { - if (rule.StartsWith("!") || rule.StartsWith("[")) + if (rule[0] == '!' || rule[0] == '[') continue; lines.Add(rule); } diff --git a/shadowsocks-csharp/Controller/Strategy/StatisticsStrategy.cs b/shadowsocks-csharp/Controller/Strategy/StatisticsStrategy.cs index df34c994..70da0ac8 100644 --- a/shadowsocks-csharp/Controller/Strategy/StatisticsStrategy.cs +++ b/shadowsocks-csharp/Controller/Strategy/StatisticsStrategy.cs @@ -18,7 +18,7 @@ namespace Shadowsocks.Controller.Strategy private readonly Timer _timer; private Dictionary> _filteredStatistics; private int ChoiceKeptMilliseconds - => (int) TimeSpan.FromMinutes(_controller.StatisticsConfiguration.ChoiceKeptMinutes).TotalMilliseconds; + => (int)TimeSpan.FromMinutes(_controller.StatisticsConfiguration.ChoiceKeptMinutes).TotalMilliseconds; public StatisticsStrategy(ShadowsocksController controller) { @@ -49,11 +49,11 @@ namespace Shadowsocks.Controller.Strategy var config = _controller.StatisticsConfiguration; List dataList; if (_filteredStatistics == null || !_filteredStatistics.TryGetValue(serverName, out dataList)) return 0; - var successTimes = (float) dataList.Count(data => data.ICMPStatus.Equals(IPStatus.Success.ToString())); - var timedOutTimes = (float) dataList.Count(data => data.ICMPStatus.Equals(IPStatus.TimedOut.ToString())); + var successTimes = (float)dataList.Count(data => data.ICMPStatus == IPStatus.Success.ToString()); + var timedOutTimes = (float)dataList.Count(data => data.ICMPStatus == IPStatus.TimedOut.ToString()); var statisticsData = new AvailabilityStatistics.StatisticsData { - PackageLoss = timedOutTimes/(successTimes + timedOutTimes)*100, + PackageLoss = timedOutTimes / (successTimes + timedOutTimes) * 100, AverageResponse = Convert.ToInt32(dataList.Average(data => data.RoundtripTime)), MinResponse = dataList.Min(data => data.RoundtripTime), MaxResponse = dataList.Max(data => data.RoundtripTime) @@ -61,13 +61,13 @@ namespace Shadowsocks.Controller.Strategy float factor; float score = 0; if (!config.Calculations.TryGetValue("PackageLoss", out factor)) factor = 0; - score += statisticsData.PackageLoss*factor; + score += statisticsData.PackageLoss * factor; if (!config.Calculations.TryGetValue("AverageResponse", out factor)) factor = 0; - score += statisticsData.AverageResponse*factor; + score += statisticsData.AverageResponse * factor; if (!config.Calculations.TryGetValue("MinResponse", out factor)) factor = 0; - score += statisticsData.MinResponse*factor; + score += statisticsData.MinResponse * factor; if (!config.Calculations.TryGetValue("MaxResponse", out factor)) factor = 0; - score += statisticsData.MaxResponse*factor; + score += statisticsData.MaxResponse * factor; Logging.Debug($"{serverName} {JsonConvert.SerializeObject(statisticsData)}"); return score; } @@ -90,7 +90,7 @@ namespace Shadowsocks.Controller.Strategy } ).Aggregate((result1, result2) => result1.score > result2.score ? result1 : result2); - LogWhenEnabled($"Switch to server: {bestResult.server.FriendlyName()} by statistics: score {bestResult.score}"); + LogWhenEnabled($"Switch to server: {bestResult.server.FriendlyName()} by statistics: score {bestResult.score}"); _currentServer = bestResult.server; } catch (Exception e) diff --git a/shadowsocks-csharp/Controller/System/AutoStartup.cs b/shadowsocks-csharp/Controller/System/AutoStartup.cs index a2ad21c1..353056eb 100644 --- a/shadowsocks-csharp/Controller/System/AutoStartup.cs +++ b/shadowsocks-csharp/Controller/System/AutoStartup.cs @@ -1,5 +1,5 @@ -using System; -using System.Windows.Forms; +using System; +using System.Windows.Forms; using Microsoft.Win32; namespace Shadowsocks.Controller @@ -14,7 +14,7 @@ namespace Shadowsocks.Controller try { string path = Application.ExecutablePath; - runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); + runKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); if (enabled) { runKey.SetValue(Key, path); @@ -47,16 +47,16 @@ namespace Shadowsocks.Controller try { string path = Application.ExecutablePath; - runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); + runKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); string[] runList = runKey.GetValueNames(); foreach (string item in runList) { - if (item.Equals(Key)) + if (item.Equals(Key, StringComparison.OrdinalIgnoreCase)) return true; - else if (item.Equals("Shadowsocks")) // Compatibility with older versions + else if (item.Equals("Shadowsocks", StringComparison.OrdinalIgnoreCase)) // Compatibility with older versions { string value = Convert.ToString(runKey.GetValue(item)); - if (path.Equals(value, StringComparison.InvariantCultureIgnoreCase)) + if (path.Equals(value, StringComparison.OrdinalIgnoreCase)) { runKey.DeleteValue(item); runKey.SetValue(Key, path); @@ -76,10 +76,10 @@ namespace Shadowsocks.Controller if (runKey != null) { try { runKey.Close(); } - catch(Exception e) + catch (Exception e) { Logging.LogUsefulException(e); } } } } } -} +} diff --git a/shadowsocks-csharp/Controller/System/SystemProxy.cs b/shadowsocks-csharp/Controller/System/SystemProxy.cs index 74e4beb4..c13c2f10 100644 --- a/shadowsocks-csharp/Controller/System/SystemProxy.cs +++ b/shadowsocks-csharp/Controller/System/SystemProxy.cs @@ -9,7 +9,7 @@ using Shadowsocks.Model; namespace Shadowsocks.Controller { - public class SystemProxy + public static class SystemProxy { [DllImport("wininet.dll")] @@ -26,19 +26,29 @@ namespace Shadowsocks.Controller _refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0); } + private static readonly DateTime UnixEpoch + = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + public static long ToUnixEpochMilliseconds(this DateTime dt) + => (long)(dt - UnixEpoch).TotalMilliseconds; + private static string GetTimestamp(DateTime value) + { + return value.ToString("yyyyMMddHHmmssfff"); + } + public static void Update(Configuration config, bool forceDisable) { bool global = config.global; bool enabled = config.enabled; + if (forceDisable) { enabled = false; } + try { - RegistryKey registry = - Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", - true); + var registry = Registry.CurrentUser + .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); if (enabled) { if (global) @@ -53,7 +63,7 @@ namespace Shadowsocks.Controller if (config.useOnlinePac && !string.IsNullOrEmpty(config.pacUrl)) pacUrl = config.pacUrl; else - pacUrl = "http://127.0.0.1:" + config.localPort.ToString() + "/pac?t=" + GetTimestamp(DateTime.Now); + pacUrl = $"http://127.0.0.1:{config.localPort}/pac?t={GetTimestamp(DateTime.Now)}"; registry.SetValue("ProxyEnable", 0); var readProxyServer = registry.GetValue("ProxyServer"); registry.SetValue("ProxyServer", ""); @@ -66,9 +76,11 @@ namespace Shadowsocks.Controller registry.SetValue("ProxyServer", ""); registry.SetValue("AutoConfigURL", ""); } - //Set AutoDetectProxy Off - IEAutoDetectProxy(false); - SystemProxy.NotifyIE(); + + //Set AutoDetectProxy + IEAutoDetectProxy(!enabled); + + NotifyIE(); //Must Notify IE first, or the connections do not chanage CopyProxySettingFromLan(); } @@ -82,55 +94,66 @@ namespace Shadowsocks.Controller private static void CopyProxySettingFromLan() { - RegistryKey registry = - Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections", - true); + var registry = Registry.CurrentUser + .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections", true); var defaultValue = registry.GetValue("DefaultConnectionSettings"); try { var connections = registry.GetValueNames(); - foreach (String each in connections) + foreach (var each in connections) { - if (!(each.Equals("DefaultConnectionSettings") - || each.Equals("LAN Connection") - || each.Equals("SavedLegacySettings"))) + switch (each.ToUpperInvariant()) { - //set all the connections's proxy as the lan - registry.SetValue(each, defaultValue); + case "DEFAULTCONNECTIONSETTINGS": + case "LAN CONNECTION": + case "SAVEDLEGACYSETTINGS": + continue; + default: + //set all the connections's proxy as the lan + registry.SetValue(each, defaultValue); + continue; } } - SystemProxy.NotifyIE(); - } catch (IOException e) { + NotifyIE(); + } + catch (IOException e) + { Logging.LogUsefulException(e); } } - private static String GetTimestamp(DateTime value) - { - return value.ToString("yyyyMMddHHmmssffff"); - } - /// /// Checks or unchecks the IE Options Connection setting of "Automatically detect Proxy" /// /// Provide 'true' if you want to check the 'Automatically detect Proxy' check box. To uncheck, pass 'false' private static void IEAutoDetectProxy(bool set) { - RegistryKey registry = - Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections", - true); - byte[] defConnection = (byte[])registry.GetValue("DefaultConnectionSettings"); - byte[] savedLegacySetting = (byte[])registry.GetValue("SavedLegacySettings"); + var registry = Registry.CurrentUser + .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections", true); + var defConnection = (byte[])registry.GetValue("DefaultConnectionSettings"); + var savedLegacySetting = (byte[])registry.GetValue("SavedLegacySettings"); + + const int versionOffset = 4; + const int optionsOffset = 8; + if (set) { - defConnection[8] = Convert.ToByte(defConnection[8] & 8); - savedLegacySetting[8] = Convert.ToByte(savedLegacySetting[8] & 8); + defConnection[optionsOffset] = (byte)(defConnection[optionsOffset] | 8); + savedLegacySetting[optionsOffset] = (byte)(savedLegacySetting[optionsOffset] | 8); } else { - defConnection[8] = Convert.ToByte(defConnection[8] & ~8); - savedLegacySetting[8] = Convert.ToByte(savedLegacySetting[8] & ~8); + defConnection[optionsOffset] = (byte)(defConnection[optionsOffset] & ~8); + savedLegacySetting[optionsOffset] = (byte)(savedLegacySetting[optionsOffset] & ~8); } + + BitConverter.GetBytes( + unchecked(BitConverter.ToUInt32(defConnection, versionOffset) + 1)) + .CopyTo(defConnection, versionOffset); + BitConverter.GetBytes( + unchecked(BitConverter.ToUInt32(savedLegacySetting, versionOffset) + 1)) + .CopyTo(savedLegacySetting, versionOffset); + registry.SetValue("DefaultConnectionSettings", defConnection); registry.SetValue("SavedLegacySettings", savedLegacySetting); } diff --git a/shadowsocks-csharp/FodyWeavers.xml b/shadowsocks-csharp/FodyWeavers.xml index 2e6d4a7a..17e88514 100644 --- a/shadowsocks-csharp/FodyWeavers.xml +++ b/shadowsocks-csharp/FodyWeavers.xml @@ -1,5 +1,5 @@  - - + + \ No newline at end of file diff --git a/shadowsocks-csharp/View/StatisticsStrategyConfigurationForm.cs b/shadowsocks-csharp/View/StatisticsStrategyConfigurationForm.cs index aae33546..02b57cd4 100644 --- a/shadowsocks-csharp/View/StatisticsStrategyConfigurationForm.cs +++ b/shadowsocks-csharp/View/StatisticsStrategyConfigurationForm.cs @@ -108,7 +108,7 @@ namespace Shadowsocks.View Timestamp = dataGroup.First().Timestamp, Ping = (int)dataGroup.Average(data => data.RoundtripTime), PackageLoss = (int) - (dataGroup.Count(data => data.ICMPStatus.Equals(IPStatus.TimedOut.ToString())) + (dataGroup.Count(data => data.ICMPStatus == IPStatus.TimedOut.ToString()) / (float)dataGroup.Count() * 100) }; foreach (var data in finalData) diff --git a/shadowsocks-csharp/packages.config b/shadowsocks-csharp/packages.config index 2230519e..c0fab934 100644 --- a/shadowsocks-csharp/packages.config +++ b/shadowsocks-csharp/packages.config @@ -1,5 +1,6 @@  +