Browse Source

WIP: Migrate to NLog

tags/4.1.9.3
celeron533 5 years ago
parent
commit
84c55d116d
39 changed files with 676 additions and 622 deletions
  1. +6
    -3
      shadowsocks-csharp/Controller/FileManager.cs
  2. +3
    -2
      shadowsocks-csharp/Controller/HotkeyReg.cs
  3. +7
    -5
      shadowsocks-csharp/Controller/I18N.cs
  4. +110
    -0
      shadowsocks-csharp/Controller/LoggerExtension.cs
  5. +0
    -198
      shadowsocks-csharp/Controller/Logging.cs
  6. +23
    -18
      shadowsocks-csharp/Controller/Service/AvailabilityStatistics.cs
  7. +5
    -3
      shadowsocks-csharp/Controller/Service/GfwListUpdater.cs
  8. +9
    -7
      shadowsocks-csharp/Controller/Service/Listener.cs
  9. +6
    -3
      shadowsocks-csharp/Controller/Service/PACDaemon.cs
  10. +5
    -2
      shadowsocks-csharp/Controller/Service/PACServer.cs
  11. +13
    -10
      shadowsocks-csharp/Controller/Service/PortForwarder.cs
  12. +7
    -4
      shadowsocks-csharp/Controller/Service/PrivoxyRunner.cs
  13. +40
    -36
      shadowsocks-csharp/Controller/Service/TCPRelay.cs
  14. +6
    -3
      shadowsocks-csharp/Controller/Service/UDPRelay.cs
  15. +11
    -9
      shadowsocks-csharp/Controller/Service/UpdateChecker.cs
  16. +7
    -5
      shadowsocks-csharp/Controller/ShadowsocksController.cs
  17. +10
    -7
      shadowsocks-csharp/Controller/Strategy/HighAvailabilityStrategy.cs
  18. +7
    -5
      shadowsocks-csharp/Controller/Strategy/StatisticsStrategy.cs
  19. +11
    -8
      shadowsocks-csharp/Controller/System/AutoStartup.cs
  20. +4
    -1
      shadowsocks-csharp/Controller/System/SystemProxy.cs
  21. +10
    -0
      shadowsocks-csharp/Data/NLog.config
  22. +20
    -18
      shadowsocks-csharp/Encryption/AEAD/AEADEncryptor.cs
  23. +11
    -8
      shadowsocks-csharp/Encryption/AEAD/AEADSodiumEncryptor.cs
  24. +4
    -1
      shadowsocks-csharp/Encryption/MbedTLS.cs
  25. +4
    -1
      shadowsocks-csharp/Encryption/OpenSSL.cs
  26. +5
    -2
      shadowsocks-csharp/Encryption/Sodium.cs
  27. +6
    -2
      shadowsocks-csharp/Model/Configuration.cs
  28. +5
    -3
      shadowsocks-csharp/Model/StatisticsStrategyConfiguration.cs
  29. +22
    -11
      shadowsocks-csharp/Program.cs
  30. +252
    -231
      shadowsocks-csharp/Properties/Resources.Designer.cs
  31. +3
    -0
      shadowsocks-csharp/Properties/Resources.resx
  32. +4
    -1
      shadowsocks-csharp/Proxy/HttpProxy.cs
  33. +4
    -1
      shadowsocks-csharp/Util/ProcessManagement/Job.cs
  34. +5
    -2
      shadowsocks-csharp/Util/SystemProxy/Sysproxy.cs
  35. +7
    -4
      shadowsocks-csharp/Util/Util.cs
  36. +7
    -4
      shadowsocks-csharp/View/LogForm.cs
  37. +5
    -3
      shadowsocks-csharp/View/MenuViewController.cs
  38. +1
    -0
      shadowsocks-csharp/packages.config
  39. +11
    -1
      shadowsocks-csharp/shadowsocks-csharp.csproj

+ 6
- 3
shadowsocks-csharp/Controller/FileManager.cs View File

@@ -1,4 +1,5 @@
using System;
using NLog;
using System;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Text; using System.Text;
@@ -7,6 +8,8 @@ namespace Shadowsocks.Controller
{ {
public static class FileManager public static class FileManager
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
public static bool ByteArrayToFile(string fileName, byte[] content) public static bool ByteArrayToFile(string fileName, byte[] content)
{ {
try try
@@ -17,7 +20,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.Error(ex);
logger.Error(ex);
} }
return false; return false;
} }
@@ -57,7 +60,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.Error(ex);
logger.Error(ex);
throw ex; throw ex;
} }
} }


+ 3
- 2
shadowsocks-csharp/Controller/HotkeyReg.cs View File

@@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Windows.Forms; using System.Windows.Forms;
using NLog;
using Shadowsocks.Controller.Hotkeys; using Shadowsocks.Controller.Hotkeys;
using Shadowsocks.Model; using Shadowsocks.Model;


@@ -9,6 +9,7 @@ namespace Shadowsocks.Controller
{ {
static class HotkeyReg static class HotkeyReg
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
public static void RegAllHotkeys() public static void RegAllHotkeys()
{ {
var hotkeyConfig = Configuration.Load().hotkey; var hotkeyConfig = Configuration.Load().hotkey;
@@ -60,7 +61,7 @@ namespace Shadowsocks.Controller
var hotkey = HotKeys.Str2HotKey(hotkeyStr); var hotkey = HotKeys.Str2HotKey(hotkeyStr);
if (hotkey == null) if (hotkey == null)
{ {
Logging.Error($"Cannot parse hotkey: {hotkeyStr}");
logger.Error($"Cannot parse hotkey: {hotkeyStr}");
onComplete?.Invoke(RegResult.ParseError); onComplete?.Invoke(RegResult.ParseError);
return false; return false;
} }


+ 7
- 5
shadowsocks-csharp/Controller/I18N.cs View File

@@ -1,4 +1,5 @@
using Microsoft.VisualBasic.FileIO; using Microsoft.VisualBasic.FileIO;
using NLog;
using Shadowsocks.Properties; using Shadowsocks.Properties;
using Shadowsocks.Util; using Shadowsocks.Util;
using System.Collections.Generic; using System.Collections.Generic;
@@ -9,9 +10,10 @@ using System.Windows.Forms;
namespace Shadowsocks.Controller namespace Shadowsocks.Controller
{ {
public static class I18N public static class I18N
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
public const string I18N_FILE = "i18n.csv"; public const string I18N_FILE = "i18n.csv";
private static Dictionary<string, string> _strings = new Dictionary<string, string>(); private static Dictionary<string, string> _strings = new Dictionary<string, string>();
@@ -47,12 +49,12 @@ namespace Shadowsocks.Controller
} }
if (targetIndex != -1 && enIndex != targetIndex) if (targetIndex != -1 && enIndex != targetIndex)
{ {
Logging.Info($"Using {localeNames[targetIndex]} translation for {locale}");
logger.Info($"Using {localeNames[targetIndex]} translation for {locale}");
} }
else else
{ {
// Still not found, exit // Still not found, exit
Logging.Info($"Translation for {locale} not found");
logger.Info($"Translation for {locale} not found");
return; return;
} }
} }
@@ -85,10 +87,10 @@ namespace Shadowsocks.Controller
} }
else else
{ {
Logging.Info("Using external translation");
logger.Info("Using external translation");
i18n = File.ReadAllText(I18N_FILE, Encoding.UTF8); i18n = File.ReadAllText(I18N_FILE, Encoding.UTF8);
} }
Logging.Info("Current language is: " + locale);
logger.Info("Current language is: " + locale);
Init(i18n, locale); Init(i18n, locale);
} }


+ 110
- 0
shadowsocks-csharp/Controller/LoggerExtension.cs View File

@@ -0,0 +1,110 @@
using System;
using System.ComponentModel;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Text;
using Shadowsocks.Util.SystemProxy;
namespace NLog
{
public static class LoggerExtension
{
public static void Dump(this Logger logger, string tag, byte[] arr, int length)
{
var sb = new StringBuilder($"{Environment.NewLine}{tag}: ");
for (int i = 0; i < length - 1; i++)
{
sb.Append($"0x{arr[i]:X2}, ");
}
sb.Append($"0x{arr[length - 1]:X2}");
sb.Append(Environment.NewLine);
logger.Debug(sb.ToString());
}
public static void Debug(this Logger logger, EndPoint local, EndPoint remote, int len, string header = null, string tailer = null)
{
if (header == null && tailer == null)
logger.Debug($"{local} => {remote} (size={len})");
else if (header == null && tailer != null)
logger.Debug($"{local} => {remote} (size={len}), {tailer}");
else if (header != null && tailer == null)
logger.Debug($"{header}: {local} => {remote} (size={len})");
else
logger.Debug($"{header}: {local} => {remote} (size={len}), {tailer}");
}
public static void Debug(this Logger logger, Socket sock, int len, string header = null, string tailer = null)
{
logger.Debug(sock.LocalEndPoint, sock.RemoteEndPoint, len, header, tailer);
}
public static void LogUsefulException(this Logger logger, Exception e)
{
// just log useful exceptions, not all of them
if (e is SocketException)
{
SocketException se = (SocketException)e;
if (se.SocketErrorCode == SocketError.ConnectionAborted)
{
// closed by browser when sending
// normally happens when download is canceled or a tab is closed before page is loaded
}
else if (se.SocketErrorCode == SocketError.ConnectionReset)
{
// received rst
}
else if (se.SocketErrorCode == SocketError.NotConnected)
{
// The application tried to send or receive data, and the System.Net.Sockets.Socket is not connected.
}
else if (se.SocketErrorCode == SocketError.HostUnreachable)
{
// There is no network route to the specified host.
}
else if (se.SocketErrorCode == SocketError.TimedOut)
{
// The connection attempt timed out, or the connected host has failed to respond.
}
else
{
logger.Info(e);
}
}
else if (e is ObjectDisposedException)
{
}
else if (e is Win32Exception)
{
var ex = (Win32Exception)e;
// Win32Exception (0x80004005): A 32 bit processes cannot access modules of a 64 bit process.
if ((uint)ex.ErrorCode != 0x80004005)
{
logger.Info(e);
}
}
else if (e is ProxyException)
{
var ex = (ProxyException)e;
switch (ex.Type)
{
case ProxyExceptionType.FailToRun:
case ProxyExceptionType.QueryReturnMalformed:
case ProxyExceptionType.SysproxyExitError:
logger.Error($"sysproxy - {ex.Type.ToString()}:{ex.Message}");
break;
case ProxyExceptionType.QueryReturnEmpty:
case ProxyExceptionType.Unspecific:
logger.Error($"sysproxy - {ex.Type.ToString()}");
break;
}
}
else
{
logger.Info(e);
}
}
}
}

+ 0
- 198
shadowsocks-csharp/Controller/Logging.cs View File

@@ -1,198 +0,0 @@
using System;
using System.ComponentModel;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Text;
using Shadowsocks.Util;
using Shadowsocks.Util.SystemProxy;
namespace Shadowsocks.Controller
{
public class Logging
{
public static string LogFilePath;
private static FileStream _fs;
private static StreamWriterWithTimestamp _sw;
public static bool OpenLogFile()
{
try
{
LogFilePath = Utils.GetTempPath("shadowsocks.log");
_fs = new FileStream(LogFilePath, FileMode.Append);
_sw = new StreamWriterWithTimestamp(_fs);
_sw.AutoFlush = true;
Console.SetOut(_sw);
Console.SetError(_sw);
return true;
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
return false;
}
}
private static void WriteToLogFile(object o)
{
try {
Console.WriteLine(o);
} catch(ObjectDisposedException) {
}
}
public static void Error(object o)
{
WriteToLogFile("[E] " + o);
}
public static void Info(object o)
{
WriteToLogFile(o);
}
public static void Clear() {
_sw.Close();
_sw.Dispose();
_fs.Close();
_fs.Dispose();
File.Delete(LogFilePath);
OpenLogFile();
}
[Conditional("DEBUG")]
public static void Debug(object o)
{
WriteToLogFile("[D] " + o);
}
[Conditional("DEBUG")]
public static void Dump(string tag, byte[] arr, int length)
{
var sb = new StringBuilder($"{Environment.NewLine}{tag}: ");
for (int i = 0; i < length - 1; i++) {
sb.Append($"0x{arr[i]:X2}, ");
}
sb.Append($"0x{arr[length - 1]:X2}");
sb.Append(Environment.NewLine);
Debug(sb.ToString());
}
[Conditional("DEBUG")]
public static void Debug(EndPoint local, EndPoint remote, int len, string header = null, string tailer = null)
{
if (header == null && tailer == null)
Debug($"{local} => {remote} (size={len})");
else if (header == null && tailer != null)
Debug($"{local} => {remote} (size={len}), {tailer}");
else if (header != null && tailer == null)
Debug($"{header}: {local} => {remote} (size={len})");
else
Debug($"{header}: {local} => {remote} (size={len}), {tailer}");
}
[Conditional("DEBUG")]
public static void Debug(Socket sock, int len, string header = null, string tailer = null)
{
Debug(sock.LocalEndPoint, sock.RemoteEndPoint, len, header, tailer);
}
public static void LogUsefulException(Exception e)
{
// just log useful exceptions, not all of them
if (e is SocketException)
{
SocketException se = (SocketException)e;
if (se.SocketErrorCode == SocketError.ConnectionAborted)
{
// closed by browser when sending
// normally happens when download is canceled or a tab is closed before page is loaded
}
else if (se.SocketErrorCode == SocketError.ConnectionReset)
{
// received rst
}
else if (se.SocketErrorCode == SocketError.NotConnected)
{
// The application tried to send or receive data, and the System.Net.Sockets.Socket is not connected.
}
else if (se.SocketErrorCode == SocketError.HostUnreachable)
{
// There is no network route to the specified host.
}
else if (se.SocketErrorCode == SocketError.TimedOut)
{
// The connection attempt timed out, or the connected host has failed to respond.
}
else
{
Info(e);
}
}
else if (e is ObjectDisposedException)
{
}
else if (e is Win32Exception)
{
var ex = (Win32Exception) e;
// Win32Exception (0x80004005): A 32 bit processes cannot access modules of a 64 bit process.
if ((uint) ex.ErrorCode != 0x80004005)
{
Info(e);
}
}
else if (e is ProxyException)
{
var ex = (ProxyException)e;
switch (ex.Type)
{
case ProxyExceptionType.FailToRun:
case ProxyExceptionType.QueryReturnMalformed:
case ProxyExceptionType.SysproxyExitError:
Error($"sysproxy - {ex.Type.ToString()}:{ex.Message}");
break;
case ProxyExceptionType.QueryReturnEmpty:
case ProxyExceptionType.Unspecific:
Error($"sysproxy - {ex.Type.ToString()}");
break;
}
}
else
{
Info(e);
}
}
}
// Simply extended System.IO.StreamWriter for adding timestamp workaround
public class StreamWriterWithTimestamp : StreamWriter
{
public StreamWriterWithTimestamp(Stream stream) : base(stream)
{
}
private string GetTimestamp()
{
return "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] ";
}
public override void WriteLine(string value)
{
base.WriteLine(GetTimestamp() + value);
}
public override void Write(string value)
{
base.Write(GetTimestamp() + value);
}
}
}

+ 23
- 18
shadowsocks-csharp/Controller/Service/AvailabilityStatistics.cs View File

@@ -9,6 +9,7 @@ using System.Net.Sockets;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using NLog;
using Shadowsocks.Model; using Shadowsocks.Model;
using Shadowsocks.Util; using Shadowsocks.Util;


@@ -18,6 +19,8 @@ namespace Shadowsocks.Controller


public sealed class AvailabilityStatistics : IDisposable public sealed class AvailabilityStatistics : IDisposable
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();

public const string DateTimePattern = "yyyy-MM-dd HH:mm:ss"; public const string DateTimePattern = "yyyy-MM-dd HH:mm:ss";
private const string StatisticsFilesName = "shadowsocks.availability.json"; private const string StatisticsFilesName = "shadowsocks.availability.json";
public static string AvailabilityStatisticsFile; public static string AvailabilityStatisticsFile;
@@ -111,7 +114,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }


@@ -155,7 +158,7 @@ namespace Shadowsocks.Controller
inR.Add(inboundSpeed); inR.Add(inboundSpeed);
outR.Add(outboundSpeed); outR.Add(outboundSpeed);


Logging.Debug(
logger.Debug(
$"{id}: current/max inbound {inboundSpeed}/{inR.Max()} KiB/s, current/max outbound {outboundSpeed}/{outR.Max()} KiB/s"); $"{id}: current/max inbound {inboundSpeed}/{inR.Max()} KiB/s, current/max outbound {outboundSpeed}/{outR.Max()} KiB/s");
} }
} }
@@ -213,7 +216,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.Debug("config changed asynchrously, just ignore this server");
logger.Debug("config changed asynchrously, just ignore this server");
} }
} }


@@ -235,7 +238,7 @@ namespace Shadowsocks.Controller
{ {
AppendRecord(server.Identifier(), record); AppendRecord(server.Identifier(), record);
} }
Logging.Debug($"Ping {server.FriendlyName()} {e.RoundtripTime.Count} times, {(100 - record.PackageLoss * 100)}% packages loss, min {record.MinResponse} ms, max {record.MaxResponse} ms, avg {record.AverageResponse} ms");
logger.Debug($"Ping {server.FriendlyName()} {e.RoundtripTime.Count} times, {(100 - record.PackageLoss * 100)}% packages loss, min {record.MinResponse} ms, max {record.MaxResponse} ms, avg {record.AverageResponse} ms");
if (Interlocked.Decrement(ref state.counter) == 0) if (Interlocked.Decrement(ref state.counter) == 0)
{ {
Save(); Save();
@@ -260,13 +263,13 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }


private void Save() private void Save()
{ {
Logging.Debug($"save statistics to {AvailabilityStatisticsFile}");
logger.Debug($"save statistics to {AvailabilityStatisticsFile}");
if (RawStatistics.Count == 0) if (RawStatistics.Count == 0)
{ {
return; return;
@@ -283,7 +286,7 @@ namespace Shadowsocks.Controller
} }
catch (IOException e) catch (IOException e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }


@@ -300,7 +303,7 @@ namespace Shadowsocks.Controller
{ {
try try
{ {
Logging.Debug("filter raw statistics");
logger.Debug("filter raw statistics");
if (RawStatistics == null) return; if (RawStatistics == null) return;
var filteredStatistics = new Statistics(); var filteredStatistics = new Statistics();


@@ -315,7 +318,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }


@@ -324,7 +327,7 @@ namespace Shadowsocks.Controller
try try
{ {
var path = AvailabilityStatisticsFile; var path = AvailabilityStatisticsFile;
Logging.Debug($"loading statistics from {path}");
logger.Debug($"loading statistics from {path}");
if (!File.Exists(path)) if (!File.Exists(path))
{ {
using (File.Create(path)) using (File.Create(path))
@@ -337,7 +340,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
Console.WriteLine($"failed to load statistics; use runtime statistics, some data may be lost"); Console.WriteLine($"failed to load statistics; use runtime statistics, some data may be lost");
} }
} }
@@ -411,6 +414,8 @@ namespace Shadowsocks.Controller


class MyPing class MyPing
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();

//arguments for ICMP tests //arguments for ICMP tests
public const int TimeoutMilliseconds = 500; public const int TimeoutMilliseconds = 500;


@@ -445,7 +450,7 @@ namespace Shadowsocks.Controller
{ {
try try
{ {
Logging.Debug($"Ping {server.FriendlyName()}");
logger.Debug($"Ping {server.FriendlyName()}");
if (ip == null) if (ip == null)
{ {
ip = Dns.GetHostAddresses(server.server) ip = Dns.GetHostAddresses(server.server)
@@ -461,8 +466,8 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.Error($"An exception occured while eveluating {server.FriendlyName()}");
Logging.LogUsefulException(e);
logger.Error($"An exception occured while eveluating {server.FriendlyName()}");
logger.LogUsefulException(e);
FireCompleted(e, userstate); FireCompleted(e, userstate);
} }
} }
@@ -473,20 +478,20 @@ namespace Shadowsocks.Controller
{ {
if (e.Reply.Status == IPStatus.Success) if (e.Reply.Status == IPStatus.Success)
{ {
Logging.Debug($"Ping {server.FriendlyName()} {e.Reply.RoundtripTime} ms");
logger.Debug($"Ping {server.FriendlyName()} {e.Reply.RoundtripTime} ms");
RoundtripTime.Add((int?)e.Reply.RoundtripTime); RoundtripTime.Add((int?)e.Reply.RoundtripTime);
} }
else else
{ {
Logging.Debug($"Ping {server.FriendlyName()} timeout");
logger.Debug($"Ping {server.FriendlyName()} timeout");
RoundtripTime.Add(null); RoundtripTime.Add(null);
} }
TestNext(e.UserState); TestNext(e.UserState);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.Error($"An exception occured while eveluating {server.FriendlyName()}");
Logging.LogUsefulException(ex);
logger.Error($"An exception occured while eveluating {server.FriendlyName()}");
logger.LogUsefulException(ex);
FireCompleted(ex, e.UserState); FireCompleted(ex, e.UserState);
} }
} }


+ 5
- 3
shadowsocks-csharp/Controller/Service/GfwListUpdater.cs View File

@@ -5,7 +5,7 @@ using System.Net;
using System.Text; using System.Text;


using Newtonsoft.Json; using Newtonsoft.Json;
using NLog;
using Shadowsocks.Model; using Shadowsocks.Model;
using Shadowsocks.Properties; using Shadowsocks.Properties;
using Shadowsocks.Util; using Shadowsocks.Util;
@@ -14,6 +14,8 @@ namespace Shadowsocks.Controller
{ {
public class GFWListUpdater public class GFWListUpdater
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();

private const string GFWLIST_URL = "https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt"; private const string GFWLIST_URL = "https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt";


public event EventHandler<ResultEventArgs> UpdateCompleted; public event EventHandler<ResultEventArgs> UpdateCompleted;
@@ -93,10 +95,10 @@ var __RULES__ = {JsonConvert.SerializeObject(gfwLines, Formatting.Indented)};
string gfwListUrl = GFWLIST_URL; string gfwListUrl = GFWLIST_URL;
if (!string.IsNullOrWhiteSpace(config.gfwListUrl)) if (!string.IsNullOrWhiteSpace(config.gfwListUrl))
{ {
Logging.Info("Found custom GFWListURL in config file");
logger.Info("Found custom GFWListURL in config file");
gfwListUrl = config.gfwListUrl; gfwListUrl = config.gfwListUrl;
} }
Logging.Info($"Checking GFWList from {gfwListUrl}");
logger.Info($"Checking GFWList from {gfwListUrl}");
WebClient http = new WebClient(); WebClient http = new WebClient();
if (config.enabled) if (config.enabled)
{ {


+ 9
- 7
shadowsocks-csharp/Controller/Service/Listener.cs View File

@@ -4,13 +4,15 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
using System.Net.Sockets; using System.Net.Sockets;
using NLog;
using Shadowsocks.Model; using Shadowsocks.Model;
namespace Shadowsocks.Controller namespace Shadowsocks.Controller
{ {
public class Listener public class Listener
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
public interface IService public interface IService
{ {
bool Handle(byte[] firstPacket, int length, Socket socket, object state); bool Handle(byte[] firstPacket, int length, Socket socket, object state);
@@ -80,10 +82,10 @@ namespace Shadowsocks.Controller
_tcpSocket.Listen(1024); _tcpSocket.Listen(1024);
// Start an asynchronous socket to listen for connections. // Start an asynchronous socket to listen for connections.
Logging.Info($"Shadowsocks started ({UpdateChecker.Version})");
logger.Info($"Shadowsocks started ({UpdateChecker.Version})");
if (_config.isVerboseLogging) if (_config.isVerboseLogging)
{ {
Logging.Info(Encryption.EncryptorFactory.DumpRegisteredEncryptor());
logger.Info(Encryption.EncryptorFactory.DumpRegisteredEncryptor());
} }
_tcpSocket.BeginAccept(new AsyncCallback(AcceptCallback), _tcpSocket); _tcpSocket.BeginAccept(new AsyncCallback(AcceptCallback), _tcpSocket);
UDPState udpState = new UDPState(_udpSocket); UDPState udpState = new UDPState(_udpSocket);
@@ -132,7 +134,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.Debug(ex);
logger.Debug(ex);
} }
finally finally
{ {
@@ -171,7 +173,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
finally finally
{ {
@@ -187,7 +189,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }
} }
@@ -218,7 +220,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
conn.Close(); conn.Close();
} }
} }


+ 6
- 3
shadowsocks-csharp/Controller/Service/PACDaemon.cs View File

@@ -1,4 +1,5 @@
using Shadowsocks.Properties;
using NLog;
using Shadowsocks.Properties;
using Shadowsocks.Util; using Shadowsocks.Util;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -15,6 +16,8 @@ namespace Shadowsocks.Controller
/// </summary> /// </summary>
public class PACDaemon public class PACDaemon
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
public const string PAC_FILE = "pac.txt"; public const string PAC_FILE = "pac.txt";
public const string USER_RULE_FILE = "user-rule.txt"; public const string USER_RULE_FILE = "user-rule.txt";
public const string USER_ABP_FILE = "abp.txt"; public const string USER_ABP_FILE = "abp.txt";
@@ -100,7 +103,7 @@ namespace Shadowsocks.Controller
{ {
if (PACFileChanged != null) if (PACFileChanged != null)
{ {
Logging.Info($"Detected: PAC file '{e.Name}' was {e.ChangeType.ToString().ToLower()}.");
logger.Info($"Detected: PAC file '{e.Name}' was {e.ChangeType.ToString().ToLower()}.");
Task.Factory.StartNew(() => Task.Factory.StartNew(() =>
{ {
((FileSystemWatcher)sender).EnableRaisingEvents = false; ((FileSystemWatcher)sender).EnableRaisingEvents = false;
@@ -115,7 +118,7 @@ namespace Shadowsocks.Controller
{ {
if (UserRuleFileChanged != null) if (UserRuleFileChanged != null)
{ {
Logging.Info($"Detected: User Rule file '{e.Name}' was {e.ChangeType.ToString().ToLower()}.");
logger.Info($"Detected: User Rule file '{e.Name}' was {e.ChangeType.ToString().ToLower()}.");
Task.Factory.StartNew(() => Task.Factory.StartNew(() =>
{ {
((FileSystemWatcher)sender).EnableRaisingEvents = false; ((FileSystemWatcher)sender).EnableRaisingEvents = false;


+ 5
- 2
shadowsocks-csharp/Controller/Service/PACServer.cs View File

@@ -6,11 +6,14 @@ using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Web; using System.Web;
using NLog;
namespace Shadowsocks.Controller namespace Shadowsocks.Controller
{ {
public class PACServer : Listener.Service public class PACServer : Listener.Service
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
public const string RESOURCE_NAME = "pac"; public const string RESOURCE_NAME = "pac";
private string PacSecret private string PacSecret
@@ -43,7 +46,7 @@ namespace Shadowsocks.Controller
string usedSecret = _config.secureLocalPac ? $"&secret={PacSecret}" : ""; string usedSecret = _config.secureLocalPac ? $"&secret={PacSecret}" : "";
string contentHash = GetHash(_pacDaemon.GetPACContent()); string contentHash = GetHash(_pacDaemon.GetPACContent());
PacUrl = $"http://{config.localHost}:{config.localPort}/{RESOURCE_NAME}?hash={contentHash}{usedSecret}"; PacUrl = $"http://{config.localHost}:{config.localPort}/{RESOURCE_NAME}?hash={contentHash}{usedSecret}";
Logging.Debug("Set PAC URL:" + PacUrl);
logger.Debug("Set PAC URL:" + PacUrl);
} }
private static string GetHash(string content) private static string GetHash(string content)
@@ -177,7 +180,7 @@ Connection: Close
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
socket.Close(); socket.Close();
} }
} }


+ 13
- 10
shadowsocks-csharp/Controller/Service/PortForwarder.cs View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using NLog;
using Shadowsocks.Util.Sockets; using Shadowsocks.Util.Sockets;
namespace Shadowsocks.Controller namespace Shadowsocks.Controller
@@ -26,6 +27,8 @@ namespace Shadowsocks.Controller
private class Handler private class Handler
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private byte[] _firstPacket; private byte[] _firstPacket;
private int _firstPacketLength; private int _firstPacketLength;
private Socket _local; private Socket _local;
@@ -58,7 +61,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -77,7 +80,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -94,7 +97,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -115,7 +118,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -142,7 +145,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -169,7 +172,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -188,7 +191,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -207,7 +210,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -239,7 +242,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }
if (_remote != null) if (_remote != null)
@@ -251,7 +254,7 @@ namespace Shadowsocks.Controller
} }
catch (SocketException e) catch (SocketException e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }
} }


+ 7
- 4
shadowsocks-csharp/Controller/Service/PrivoxyRunner.cs View File

@@ -6,6 +6,7 @@ using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using NLog;
using Shadowsocks.Model; using Shadowsocks.Model;
using Shadowsocks.Properties; using Shadowsocks.Properties;
using Shadowsocks.Util; using Shadowsocks.Util;
@@ -15,6 +16,8 @@ namespace Shadowsocks.Controller
{ {
class PrivoxyRunner class PrivoxyRunner
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private static int _uid; private static int _uid;
private static string _uniqueConfigFile; private static string _uniqueConfigFile;
private static Job _privoxyJob; private static Job _privoxyJob;
@@ -33,7 +36,7 @@ namespace Shadowsocks.Controller
} }
catch (IOException e) catch (IOException e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }
@@ -106,7 +109,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }
@@ -139,7 +142,7 @@ namespace Shadowsocks.Controller
* are already dead, and that will cause exceptions here. * are already dead, and that will cause exceptions here.
* We could simply ignore those exceptions. * We could simply ignore those exceptions.
*/ */
Logging.LogUsefulException(ex);
logger.LogUsefulException(ex);
return false; return false;
} }
} }
@@ -159,7 +162,7 @@ namespace Shadowsocks.Controller
catch (Exception e) catch (Exception e)
{ {
// in case access denied // in case access denied
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
return defaultPort; return defaultPort;
} }
} }


+ 40
- 36
shadowsocks-csharp/Controller/Service/TCPRelay.cs View File

@@ -1,4 +1,5 @@
using System;
using NLog;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
@@ -17,6 +18,7 @@ namespace Shadowsocks.Controller
{ {
class TCPRelay : Listener.Service class TCPRelay : Listener.Service
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private ShadowsocksController _controller; private ShadowsocksController _controller;
private DateTime _lastSweepTime; private DateTime _lastSweepTime;
private Configuration _config; private Configuration _config;
@@ -54,7 +56,7 @@ namespace Shadowsocks.Controller
} }
foreach (TCPHandler handler1 in handlersToClose) foreach (TCPHandler handler1 in handlersToClose)
{ {
Logging.Debug("Closing timed out TCP connection.");
logger.Debug("Closing timed out TCP connection.");
handler1.Close(); handler1.Close();
} }
@@ -122,6 +124,8 @@ namespace Shadowsocks.Controller
} }
} }
private static Logger Logger = LogManager.GetCurrentClassLogger();
private readonly int _serverTimeout; private readonly int _serverTimeout;
private readonly int _proxyTimeout; private readonly int _proxyTimeout;
@@ -217,7 +221,7 @@ namespace Shadowsocks.Controller
this._server = server; this._server = server;
/* prepare address buffer length for AEAD */ /* prepare address buffer length for AEAD */
Logging.Debug($"_addrBufLength={_addrBufLength}");
Logger.Debug($"_addrBufLength={_addrBufLength}");
_encryptor.AddrBufLength = _addrBufLength; _encryptor.AddrBufLength = _addrBufLength;
} }
@@ -252,7 +256,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
} }
if (_currentRemoteSession != null) if (_currentRemoteSession != null)
@@ -265,7 +269,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
} }
} }
@@ -291,7 +295,7 @@ namespace Shadowsocks.Controller
{ {
// reject socks 4 // reject socks 4
response = new byte[] { 0, 91 }; response = new byte[] { 0, 91 };
Logging.Error("socks 5 protocol error");
Logger.Error("socks 5 protocol error");
} }
_connection.BeginSend(response, 0, response.Length, SocketFlags.None, _connection.BeginSend(response, 0, response.Length, SocketFlags.None,
HandshakeSendCallback, null); HandshakeSendCallback, null);
@@ -301,7 +305,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -326,7 +330,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -358,21 +362,21 @@ namespace Shadowsocks.Controller
break; break;
case CMD_BIND: // not implemented case CMD_BIND: // not implemented
default: default:
Logging.Debug("Unsupported CMD=" + _command);
Logger.Debug("Unsupported CMD=" + _command);
Close(); Close();
break; break;
} }
} }
else else
{ {
Logging.Debug(
Logger.Debug(
"failed to recv data in Shadowsocks.Controller.TCPHandler.handshakeReceive2Callback()"); "failed to recv data in Shadowsocks.Controller.TCPHandler.handshakeReceive2Callback()");
Close(); Close();
} }
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -387,7 +391,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -409,7 +413,7 @@ namespace Shadowsocks.Controller
ReadAddress(16 + ADDR_PORT_LEN - 1, onSuccess); ReadAddress(16 + ADDR_PORT_LEN - 1, onSuccess);
break; break;
default: default:
Logging.Debug("Unsupported ATYP=" + atyp);
Logger.Debug("Unsupported ATYP=" + atyp);
Close(); Close();
break; break;
} }
@@ -470,7 +474,7 @@ namespace Shadowsocks.Controller
if (_config.isVerboseLogging) if (_config.isVerboseLogging)
{ {
Logging.Info($"connect to {dstAddr}:{dstPort}");
Logger.Info($"connect to {dstAddr}:{dstPort}");
} }
_destEndPoint = SocketUtil.GetEndPoint(dstAddr, dstPort); _destEndPoint = SocketUtil.GetEndPoint(dstAddr, dstPort);
@@ -479,13 +483,13 @@ namespace Shadowsocks.Controller
} }
else else
{ {
Logging.Debug("failed to recv data in Shadowsocks.Controller.TCPHandler.OnAddressFullyRead()");
Logger.Debug("failed to recv data in Shadowsocks.Controller.TCPHandler.OnAddressFullyRead()");
Close(); Close();
} }
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -537,7 +541,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -631,7 +635,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -650,7 +654,7 @@ namespace Shadowsocks.Controller
} }
var proxy = timer.Session.Remote; var proxy = timer.Session.Remote;
Logging.Info($"Proxy {proxy.ProxyEndPoint} timed out");
Logger.Info($"Proxy {proxy.ProxyEndPoint} timed out");
proxy.Close(); proxy.Close();
Close(); Close();
} }
@@ -682,7 +686,7 @@ namespace Shadowsocks.Controller
{ {
if (!(remote is DirectConnect)) if (!(remote is DirectConnect))
{ {
Logging.Info($"Socket connected to proxy {remote.ProxyEndPoint}");
Logger.Info($"Socket connected to proxy {remote.ProxyEndPoint}");
} }
} }
@@ -710,7 +714,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -731,7 +735,7 @@ namespace Shadowsocks.Controller
Server server = timer.Server; Server server = timer.Server;
IStrategy strategy = _controller.GetCurrentStrategy(); IStrategy strategy = _controller.GetCurrentStrategy();
strategy?.SetFailure(server); strategy?.SetFailure(server);
Logging.Info($"{server.FriendlyName()} timed out");
Logger.Info($"{server.FriendlyName()} timed out");
session.Remote.Close(); session.Remote.Close();
Close(); Close();
} }
@@ -756,7 +760,7 @@ namespace Shadowsocks.Controller
if (_config.isVerboseLogging) if (_config.isVerboseLogging)
{ {
Logging.Info($"Socket connected to ss server: {_server.FriendlyName()}");
Logger.Info($"Socket connected to ss server: {_server.FriendlyName()}");
} }
var latency = DateTime.Now - _startConnectTime; var latency = DateTime.Now - _startConnectTime;
@@ -776,7 +780,7 @@ namespace Shadowsocks.Controller
IStrategy strategy = _controller.GetCurrentStrategy(); IStrategy strategy = _controller.GetCurrentStrategy();
strategy?.SetFailure(_server); strategy?.SetFailure(_server);
} }
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -803,12 +807,12 @@ namespace Shadowsocks.Controller
PipeRemoteReceiveCallback, session); PipeRemoteReceiveCallback, session);
TryReadAvailableData(); TryReadAvailableData();
Logging.Debug($"_firstPacketLength = {_firstPacketLength}");
Logger.Debug($"_firstPacketLength = {_firstPacketLength}");
SendToServer(_firstPacketLength, session); SendToServer(_firstPacketLength, session);
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -834,7 +838,7 @@ namespace Shadowsocks.Controller
} }
catch (CryptoErrorException) catch (CryptoErrorException)
{ {
Logging.Error("decryption error");
Logger.Error("decryption error");
Close(); Close();
return; return;
} }
@@ -842,12 +846,12 @@ namespace Shadowsocks.Controller
if (bytesToSend == 0) if (bytesToSend == 0)
{ {
// need more to decrypt // need more to decrypt
Logging.Debug("Need more to decrypt");
Logger.Debug("Need more to decrypt");
session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None, session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None,
PipeRemoteReceiveCallback, session); PipeRemoteReceiveCallback, session);
return; return;
} }
Logging.Debug($"start sending {bytesToSend}");
Logger.Debug($"start sending {bytesToSend}");
_connection.BeginSend(_remoteSendBuffer, 0, bytesToSend, SocketFlags.None, _connection.BeginSend(_remoteSendBuffer, 0, bytesToSend, SocketFlags.None,
PipeConnectionSendCallback, new object[] { session, bytesToSend }); PipeConnectionSendCallback, new object[] { session, bytesToSend });
IStrategy strategy = _controller.GetCurrentStrategy(); IStrategy strategy = _controller.GetCurrentStrategy();
@@ -862,7 +866,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -890,7 +894,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -907,7 +911,7 @@ namespace Shadowsocks.Controller
} }
catch (CryptoErrorException) catch (CryptoErrorException)
{ {
Logging.Debug("encryption error");
Logger.Debug("encryption error");
Close(); Close();
return; return;
} }
@@ -932,7 +936,7 @@ namespace Shadowsocks.Controller
int bytesRemaining = bytesShouldSend - bytesSent; int bytesRemaining = bytesShouldSend - bytesSent;
if (bytesRemaining > 0) if (bytesRemaining > 0)
{ {
Logging.Info("reconstruct _connetionSendBuffer to re-send");
Logger.Info("reconstruct _connetionSendBuffer to re-send");
Buffer.BlockCopy(_connetionSendBuffer, bytesSent, _connetionSendBuffer, 0, bytesRemaining); Buffer.BlockCopy(_connetionSendBuffer, bytesSent, _connetionSendBuffer, 0, bytesRemaining);
session.Remote.BeginSend(_connetionSendBuffer, 0, bytesRemaining, SocketFlags.None, session.Remote.BeginSend(_connetionSendBuffer, 0, bytesRemaining, SocketFlags.None,
PipeRemoteSendCallback, new object[] { session, bytesRemaining }); PipeRemoteSendCallback, new object[] { session, bytesRemaining });
@@ -943,7 +947,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }
@@ -960,7 +964,7 @@ namespace Shadowsocks.Controller
var bytesRemaining = bytesShouldSend - bytesSent; var bytesRemaining = bytesShouldSend - bytesSent;
if (bytesRemaining > 0) if (bytesRemaining > 0)
{ {
Logging.Info("reconstruct _remoteSendBuffer to re-send");
Logger.Info("reconstruct _remoteSendBuffer to re-send");
Buffer.BlockCopy(_remoteSendBuffer, bytesSent, _remoteSendBuffer, 0, bytesRemaining); Buffer.BlockCopy(_remoteSendBuffer, bytesSent, _remoteSendBuffer, 0, bytesRemaining);
_connection.BeginSend(_remoteSendBuffer, 0, bytesRemaining, SocketFlags.None, _connection.BeginSend(_remoteSendBuffer, 0, bytesRemaining, SocketFlags.None,
PipeConnectionSendCallback, new object[] { session, bytesRemaining }); PipeConnectionSendCallback, new object[] { session, bytesRemaining });
@@ -971,7 +975,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
Logger.LogUsefulException(e);
Close(); Close();
} }
} }


+ 6
- 3
shadowsocks-csharp/Controller/Service/UDPRelay.cs View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using NLog;
using Shadowsocks.Controller.Strategy; using Shadowsocks.Controller.Strategy;
using Shadowsocks.Encryption; using Shadowsocks.Encryption;
using Shadowsocks.Model; using Shadowsocks.Model;
@@ -49,6 +50,8 @@ namespace Shadowsocks.Controller
public class UDPHandler public class UDPHandler
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private Socket _local; private Socket _local;
private Socket _remote; private Socket _remote;
@@ -98,14 +101,14 @@ namespace Shadowsocks.Controller
byte[] dataOut = new byte[65536]; // enough space for AEAD ciphers byte[] dataOut = new byte[65536]; // enough space for AEAD ciphers
int outlen; int outlen;
encryptor.EncryptUDP(dataIn, length - 3, dataOut, out outlen); encryptor.EncryptUDP(dataIn, length - 3, dataOut, out outlen);
Logging.Debug(_localEndPoint, _remoteEndPoint, outlen, "UDP Relay");
logger.Debug(_localEndPoint, _remoteEndPoint, outlen, "UDP Relay");
_remote?.SendTo(dataOut, outlen, SocketFlags.None, _remoteEndPoint); _remote?.SendTo(dataOut, outlen, SocketFlags.None, _remoteEndPoint);
} }
public void Receive() public void Receive()
{ {
EndPoint remoteEndPoint = new IPEndPoint(GetIPAddress(), 0); EndPoint remoteEndPoint = new IPEndPoint(GetIPAddress(), 0);
Logging.Debug($"++++++Receive Server Port, size:" + _buffer.Length);
logger.Debug($"++++++Receive Server Port, size:" + _buffer.Length);
_remote?.BeginReceiveFrom(_buffer, 0, _buffer.Length, 0, ref remoteEndPoint, new AsyncCallback(RecvFromCallback), null); _remote?.BeginReceiveFrom(_buffer, 0, _buffer.Length, 0, ref remoteEndPoint, new AsyncCallback(RecvFromCallback), null);
} }
@@ -126,7 +129,7 @@ namespace Shadowsocks.Controller
byte[] sendBuf = new byte[outlen + 3]; byte[] sendBuf = new byte[outlen + 3];
Array.Copy(dataOut, 0, sendBuf, 3, outlen); Array.Copy(dataOut, 0, sendBuf, 3, outlen);
Logging.Debug(_localEndPoint, _remoteEndPoint, outlen, "UDP Relay");
logger.Debug(_localEndPoint, _remoteEndPoint, outlen, "UDP Relay");
_local?.SendTo(sendBuf, outlen + 3, 0, _localEndPoint); _local?.SendTo(sendBuf, outlen + 3, 0, _localEndPoint);
Receive(); Receive();


+ 11
- 9
shadowsocks-csharp/Controller/Service/UpdateChecker.cs View File

@@ -4,7 +4,7 @@ using System.Net;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using NLog;
using Shadowsocks.Model; using Shadowsocks.Model;
using Shadowsocks.Util; using Shadowsocks.Util;
@@ -12,6 +12,8 @@ namespace Shadowsocks.Controller
{ {
public class UpdateChecker public class UpdateChecker
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private const string UpdateURL = "https://api.github.com/repos/shadowsocks/shadowsocks-windows/releases"; private const string UpdateURL = "https://api.github.com/repos/shadowsocks/shadowsocks-windows/releases";
private const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"; private const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36";
@@ -60,14 +62,14 @@ namespace Shadowsocks.Controller
try try
{ {
Logging.Debug("Checking updates...");
logger.Debug("Checking updates...");
WebClient http = CreateWebClient(); WebClient http = CreateWebClient();
http.DownloadStringCompleted += http_DownloadStringCompleted; http.DownloadStringCompleted += http_DownloadStringCompleted;
http.DownloadStringAsync(new Uri(UpdateURL)); http.DownloadStringAsync(new Uri(UpdateURL));
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.LogUsefulException(ex);
logger.LogUsefulException(ex);
} }
} }
@@ -117,7 +119,7 @@ namespace Shadowsocks.Controller
} }
else else
{ {
Logging.Debug("No update is available");
logger.Debug("No update is available");
if (CheckUpdateCompleted != null) if (CheckUpdateCompleted != null)
{ {
CheckUpdateCompleted(this, new EventArgs()); CheckUpdateCompleted(this, new EventArgs());
@@ -126,7 +128,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.LogUsefulException(ex);
logger.LogUsefulException(ex);
} }
} }
@@ -141,7 +143,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.LogUsefulException(ex);
logger.LogUsefulException(ex);
} }
} }
@@ -151,10 +153,10 @@ namespace Shadowsocks.Controller
{ {
if (e.Error != null) if (e.Error != null)
{ {
Logging.LogUsefulException(e.Error);
logger.LogUsefulException(e.Error);
return; return;
} }
Logging.Debug($"New version {LatestVersionNumber}{LatestVersionSuffix} found: {LatestVersionLocalName}");
logger.Debug($"New version {LatestVersionNumber}{LatestVersionSuffix} found: {LatestVersionLocalName}");
if (CheckUpdateCompleted != null) if (CheckUpdateCompleted != null)
{ {
CheckUpdateCompleted(this, new EventArgs()); CheckUpdateCompleted(this, new EventArgs());
@@ -162,7 +164,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.LogUsefulException(ex);
logger.LogUsefulException(ex);
} }
} }


+ 7
- 5
shadowsocks-csharp/Controller/ShadowsocksController.cs View File

@@ -9,7 +9,7 @@ using System.Text;
using System.Threading; using System.Threading;
using System.Web; using System.Web;
using System.Windows.Forms; using System.Windows.Forms;
using NLog;
using Shadowsocks.Controller.Service; using Shadowsocks.Controller.Service;
using Shadowsocks.Controller.Strategy; using Shadowsocks.Controller.Strategy;
using Shadowsocks.Model; using Shadowsocks.Model;
@@ -19,6 +19,8 @@ namespace Shadowsocks.Controller
{ {
public class ShadowsocksController public class ShadowsocksController
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
// controller: // controller:
// handle user actions // handle user actions
// manipulates UI // manipulates UI
@@ -165,13 +167,13 @@ namespace Shadowsocks.Controller
{ {
if (plugin.StartIfNeeded()) if (plugin.StartIfNeeded())
{ {
Logging.Info(
logger.Info(
$"Started SIP003 plugin for {server.Identifier()} on {plugin.LocalEndPoint} - PID: {plugin.ProcessId}"); $"Started SIP003 plugin for {server.Identifier()} on {plugin.LocalEndPoint} - PID: {plugin.ProcessId}");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.Error("Failed to start SIP003 plugin: " + ex.Message);
logger.Error("Failed to start SIP003 plugin: " + ex.Message);
throw; throw;
} }
@@ -213,7 +215,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
return false; return false;
} }
} }
@@ -533,7 +535,7 @@ namespace Shadowsocks.Controller
e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e); e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e);
} }
} }
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
ReportError(e); ReportError(e);
} }


+ 10
- 7
shadowsocks-csharp/Controller/Strategy/HighAvailabilityStrategy.cs View File

@@ -1,4 +1,5 @@
using Shadowsocks.Model;
using NLog;
using Shadowsocks.Model;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
@@ -8,6 +9,8 @@ namespace Shadowsocks.Controller.Strategy
{ {
class HighAvailabilityStrategy : IStrategy class HighAvailabilityStrategy : IStrategy
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
protected ServerStatus _currentServer; protected ServerStatus _currentServer;
protected Dictionary<Server, ServerStatus> _serverStatus; protected Dictionary<Server, ServerStatus> _serverStatus;
ShadowsocksController _controller; ShadowsocksController _controller;
@@ -111,7 +114,7 @@ namespace Shadowsocks.Controller.Strategy
100 * 1000 * Math.Min(5 * 60, (now - status.lastFailure).TotalSeconds) 100 * 1000 * Math.Min(5 * 60, (now - status.lastFailure).TotalSeconds)
-2 * 5 * (Math.Min(2000, status.latency.TotalMilliseconds) / (1 + (now - status.lastTimeDetectLatency).TotalSeconds / 30 / 10) + -2 * 5 * (Math.Min(2000, status.latency.TotalMilliseconds) / (1 + (now - status.lastTimeDetectLatency).TotalSeconds / 30 / 10) +
-0.5 * 200 * Math.Min(5, (status.lastRead - status.lastWrite).TotalSeconds)); -0.5 * 200 * Math.Min(5, (status.lastRead - status.lastWrite).TotalSeconds));
Logging.Debug(String.Format("server: {0} latency:{1} score: {2}", status.server.FriendlyName(), status.latency, status.score));
logger.Debug(String.Format("server: {0} latency:{1} score: {2}", status.server.FriendlyName(), status.latency, status.score));
} }
ServerStatus max = null; ServerStatus max = null;
foreach (var status in servers) foreach (var status in servers)
@@ -133,14 +136,14 @@ namespace Shadowsocks.Controller.Strategy
if (_currentServer == null || max.score - _currentServer.score > 200) if (_currentServer == null || max.score - _currentServer.score > 200)
{ {
_currentServer = max; _currentServer = max;
Logging.Info($"HA switching to server: {_currentServer.server.FriendlyName()}");
logger.Info($"HA switching to server: {_currentServer.server.FriendlyName()}");
} }
} }
} }
public void UpdateLatency(Model.Server server, TimeSpan latency) public void UpdateLatency(Model.Server server, TimeSpan latency)
{ {
Logging.Debug($"latency: {server.FriendlyName()} {latency}");
logger.Debug($"latency: {server.FriendlyName()} {latency}");
ServerStatus status; ServerStatus status;
if (_serverStatus.TryGetValue(server, out status)) if (_serverStatus.TryGetValue(server, out status))
@@ -152,7 +155,7 @@ namespace Shadowsocks.Controller.Strategy
public void UpdateLastRead(Model.Server server) public void UpdateLastRead(Model.Server server)
{ {
Logging.Debug($"last read: {server.FriendlyName()}");
logger.Debug($"last read: {server.FriendlyName()}");
ServerStatus status; ServerStatus status;
if (_serverStatus.TryGetValue(server, out status)) if (_serverStatus.TryGetValue(server, out status))
@@ -163,7 +166,7 @@ namespace Shadowsocks.Controller.Strategy
public void UpdateLastWrite(Model.Server server) public void UpdateLastWrite(Model.Server server)
{ {
Logging.Debug($"last write: {server.FriendlyName()}");
logger.Debug($"last write: {server.FriendlyName()}");
ServerStatus status; ServerStatus status;
if (_serverStatus.TryGetValue(server, out status)) if (_serverStatus.TryGetValue(server, out status))
@@ -174,7 +177,7 @@ namespace Shadowsocks.Controller.Strategy
public void SetFailure(Model.Server server) public void SetFailure(Model.Server server)
{ {
Logging.Debug($"failure: {server.FriendlyName()}");
logger.Debug($"failure: {server.FriendlyName()}");
ServerStatus status; ServerStatus status;
if (_serverStatus.TryGetValue(server, out status)) if (_serverStatus.TryGetValue(server, out status))


+ 7
- 5
shadowsocks-csharp/Controller/Strategy/StatisticsStrategy.cs View File

@@ -5,7 +5,7 @@ using System.Net;
using System.Threading; using System.Threading;


using Newtonsoft.Json; using Newtonsoft.Json;
using NLog;
using Shadowsocks.Model; using Shadowsocks.Model;


namespace Shadowsocks.Controller.Strategy namespace Shadowsocks.Controller.Strategy
@@ -14,6 +14,8 @@ namespace Shadowsocks.Controller.Strategy


internal class StatisticsStrategy : IStrategy, IDisposable internal class StatisticsStrategy : IStrategy, IDisposable
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();

private readonly ShadowsocksController _controller; private readonly ShadowsocksController _controller;
private Server _currentServer; private Server _currentServer;
private readonly Timer _timer; private readonly Timer _timer;
@@ -34,7 +36,7 @@ namespace Shadowsocks.Controller.Strategy


private void ReloadStatisticsAndChooseAServer(object obj) private void ReloadStatisticsAndChooseAServer(object obj)
{ {
Logging.Debug("Reloading statistics and choose a new server....");
logger.Debug("Reloading statistics and choose a new server....");
var servers = _controller.GetCurrentConfiguration().configs; var servers = _controller.GetCurrentConfiguration().configs;
LoadStatistics(); LoadStatistics();
ChooseNewServer(servers); ChooseNewServer(servers);
@@ -74,7 +76,7 @@ namespace Shadowsocks.Controller.Strategy


if (score != null) if (score != null)
{ {
Logging.Debug($"Highest score: {score} {JsonConvert.SerializeObject(averageRecord, Formatting.Indented)}");
logger.Debug($"Highest score: {score} {JsonConvert.SerializeObject(averageRecord, Formatting.Indented)}");
} }
return score; return score;
} }
@@ -112,7 +114,7 @@ namespace Shadowsocks.Controller.Strategy
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }


@@ -145,7 +147,7 @@ namespace Shadowsocks.Controller.Strategy


public void SetFailure(Server server) public void SetFailure(Server server)
{ {
Logging.Debug($"failure: {server.FriendlyName()}");
logger.Debug($"failure: {server.FriendlyName()}");
} }


public void UpdateLastRead(Server server) public void UpdateLastRead(Server server)


+ 11
- 8
shadowsocks-csharp/Controller/System/AutoStartup.cs View File

@@ -5,12 +5,15 @@ using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows.Forms; using System.Windows.Forms;
using Microsoft.Win32; using Microsoft.Win32;
using NLog;
using Shadowsocks.Util; using Shadowsocks.Util;
namespace Shadowsocks.Controller namespace Shadowsocks.Controller
{ {
static class AutoStartup static class AutoStartup
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
// Don't use Application.ExecutablePath // Don't use Application.ExecutablePath
// see https://stackoverflow.com/questions/12945805/odd-c-sharp-path-issue // see https://stackoverflow.com/questions/12945805/odd-c-sharp-path-issue
private static readonly string ExecutablePath = Assembly.GetEntryAssembly().Location; private static readonly string ExecutablePath = Assembly.GetEntryAssembly().Location;
@@ -25,7 +28,7 @@ namespace Shadowsocks.Controller
runKey = Utils.OpenRegKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); runKey = Utils.OpenRegKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
if (runKey == null) if (runKey == null)
{ {
Logging.Error(@"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Run");
logger.Error(@"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Run");
return false; return false;
} }
if (enabled) if (enabled)
@@ -42,7 +45,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
return false; return false;
} }
finally finally
@@ -55,7 +58,7 @@ namespace Shadowsocks.Controller
runKey.Dispose(); runKey.Dispose();
} }
catch (Exception e) catch (Exception e)
{ Logging.LogUsefulException(e); }
{ logger.LogUsefulException(e); }
} }
} }
} }
@@ -68,7 +71,7 @@ namespace Shadowsocks.Controller
runKey = Utils.OpenRegKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); runKey = Utils.OpenRegKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
if (runKey == null) if (runKey == null)
{ {
Logging.Error(@"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Run");
logger.Error(@"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Run");
return false; return false;
} }
string[] runList = runKey.GetValueNames(); string[] runList = runKey.GetValueNames();
@@ -91,7 +94,7 @@ namespace Shadowsocks.Controller
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
return false; return false;
} }
finally finally
@@ -104,7 +107,7 @@ namespace Shadowsocks.Controller
runKey.Dispose(); runKey.Dispose();
} }
catch (Exception e) catch (Exception e)
{ Logging.LogUsefulException(e); }
{ logger.LogUsefulException(e); }
} }
} }
} }
@@ -140,13 +143,13 @@ namespace Shadowsocks.Controller
// first parameter is process command line parameter // first parameter is process command line parameter
// needn't include the name of the executable in the command line // needn't include the name of the executable in the command line
RegisterApplicationRestart(cmdline, (int)(ApplicationRestartFlags.RESTART_NO_CRASH | ApplicationRestartFlags.RESTART_NO_HANG)); RegisterApplicationRestart(cmdline, (int)(ApplicationRestartFlags.RESTART_NO_CRASH | ApplicationRestartFlags.RESTART_NO_HANG));
Logging.Debug("Register restart after system reboot, command line:" + cmdline);
logger.Debug("Register restart after system reboot, command line:" + cmdline);
} }
// requested unregister, which has no side effect // requested unregister, which has no side effect
else if (!register) else if (!register)
{ {
UnregisterApplicationRestart(); UnregisterApplicationRestart();
Logging.Debug("Unregister restart after system reboot");
logger.Debug("Unregister restart after system reboot");
} }
} }
} }


+ 4
- 1
shadowsocks-csharp/Controller/System/SystemProxy.cs View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Windows.Forms; using System.Windows.Forms;
using NLog;
using Shadowsocks.Model; using Shadowsocks.Model;
using Shadowsocks.Util.SystemProxy; using Shadowsocks.Util.SystemProxy;
@@ -7,6 +8,8 @@ namespace Shadowsocks.Controller
{ {
public static class SystemProxy public static class SystemProxy
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private static string GetTimestamp(DateTime value) private static string GetTimestamp(DateTime value)
{ {
return value.ToString("yyyyMMddHHmmssfff"); return value.ToString("yyyyMMddHHmmssfff");
@@ -52,7 +55,7 @@ namespace Shadowsocks.Controller
} }
catch (ProxyException ex) catch (ProxyException ex)
{ {
Logging.LogUsefulException(ex);
logger.LogUsefulException(ex);
if (ex.Type != ProxyExceptionType.Unspecific && !noRetry) if (ex.Type != ProxyExceptionType.Unspecific && !noRetry)
{ {
var ret = MessageBox.Show(I18N.GetString("Error occured when process proxy setting, do you want reset current setting and retry?"), I18N.GetString("Shadowsocks"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning); 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);


+ 10
- 0
shadowsocks-csharp/Data/NLog.config View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File" fileName="shadowsocks.log"/>
<target name="richText" xsi:type="RichTextBox" allowAccessoryFormCreation="false" messageRetention="All" maxLines="5120" autoScroll="true" controlName="" formName=""/>
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="file, richText" />
</rules>
</nlog>

+ 20
- 18
shadowsocks-csharp/Encryption/AEAD/AEADEncryptor.cs View File

@@ -1,4 +1,5 @@
using System;
using NLog;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Net; using System.Net;
@@ -13,6 +14,7 @@ namespace Shadowsocks.Encryption.AEAD
public abstract class AEADEncryptor public abstract class AEADEncryptor
: EncryptorBase : EncryptorBase
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
// We are using the same saltLen and keyLen // We are using the same saltLen and keyLen
private const string Info = "ss-subkey"; private const string Info = "ss-subkey";
private static readonly byte[] InfoBytes = Encoding.ASCII.GetBytes(Info); private static readonly byte[] InfoBytes = Encoding.ASCII.GetBytes(Info);
@@ -122,7 +124,7 @@ namespace Shadowsocks.Encryption.AEAD
_decryptSalt = new byte[saltLen]; _decryptSalt = new byte[saltLen];
Array.Copy(salt, _decryptSalt, saltLen); Array.Copy(salt, _decryptSalt, saltLen);
} }
Logging.Dump("Salt", salt, saltLen);
logger.Dump("Salt", salt, saltLen);
} }
public static void randBytes(byte[] buf, int length) { RNG.GetBytes(buf, length); } public static void randBytes(byte[] buf, int length) { RNG.GetBytes(buf, length); }
@@ -139,7 +141,7 @@ namespace Shadowsocks.Encryption.AEAD
_encCircularBuffer.Put(buf, 0, length); _encCircularBuffer.Put(buf, 0, length);
outlength = 0; outlength = 0;
Logging.Debug("---Start Encryption");
logger.Debug("---Start Encryption");
if (! _encryptSaltSent) { if (! _encryptSaltSent) {
_encryptSaltSent = true; _encryptSaltSent = true;
// Generate salt // Generate salt
@@ -148,7 +150,7 @@ namespace Shadowsocks.Encryption.AEAD
InitCipher(saltBytes, true, false); InitCipher(saltBytes, true, false);
Array.Copy(saltBytes, 0, outbuf, 0, saltLen); Array.Copy(saltBytes, 0, outbuf, 0, saltLen);
outlength = saltLen; outlength = saltLen;
Logging.Debug($"_encryptSaltSent outlength {outlength}");
logger.Debug($"_encryptSaltSent outlength {outlength}");
} }
if (! _tcpRequestSent) { if (! _tcpRequestSent) {
@@ -161,7 +163,7 @@ namespace Shadowsocks.Encryption.AEAD
Debug.Assert(encAddrBufLength == AddrBufLength + tagLen * 2 + CHUNK_LEN_BYTES); Debug.Assert(encAddrBufLength == AddrBufLength + tagLen * 2 + CHUNK_LEN_BYTES);
Array.Copy(encAddrBufBytes, 0, outbuf, outlength, encAddrBufLength); Array.Copy(encAddrBufBytes, 0, outbuf, outlength, encAddrBufLength);
outlength += encAddrBufLength; outlength += encAddrBufLength;
Logging.Debug($"_tcpRequestSent outlength {outlength}");
logger.Debug($"_tcpRequestSent outlength {outlength}");
} }
// handle other chunks // handle other chunks
@@ -176,15 +178,15 @@ namespace Shadowsocks.Encryption.AEAD
Debug.Assert(encChunkLength == chunklength + tagLen * 2 + CHUNK_LEN_BYTES); Debug.Assert(encChunkLength == chunklength + tagLen * 2 + CHUNK_LEN_BYTES);
Buffer.BlockCopy(encChunkBytes, 0, outbuf, outlength, encChunkLength); Buffer.BlockCopy(encChunkBytes, 0, outbuf, outlength, encChunkLength);
outlength += encChunkLength; outlength += encChunkLength;
Logging.Debug("chunks enc outlength " + outlength);
logger.Debug("chunks enc outlength " + outlength);
// check if we have enough space for outbuf // check if we have enough space for outbuf
if (outlength + TCPHandler.ChunkOverheadSize > TCPHandler.BufferSize) { if (outlength + TCPHandler.ChunkOverheadSize > TCPHandler.BufferSize) {
Logging.Debug("enc outbuf almost full, giving up");
logger.Debug("enc outbuf almost full, giving up");
return; return;
} }
bufSize = (uint)_encCircularBuffer.Size; bufSize = (uint)_encCircularBuffer.Size;
if (bufSize <= 0) { if (bufSize <= 0) {
Logging.Debug("No more data to encrypt, leaving");
logger.Debug("No more data to encrypt, leaving");
return; return;
} }
} }
@@ -199,7 +201,7 @@ namespace Shadowsocks.Encryption.AEAD
// drop all into buffer // drop all into buffer
_decCircularBuffer.Put(buf, 0, length); _decCircularBuffer.Put(buf, 0, length);
Logging.Debug("---Start Decryption");
logger.Debug("---Start Decryption");
if (! _decryptSaltReceived) { if (! _decryptSaltReceived) {
bufSize = _decCircularBuffer.Size; bufSize = _decCircularBuffer.Size;
// check if we get the leading salt // check if we get the leading salt
@@ -210,7 +212,7 @@ namespace Shadowsocks.Encryption.AEAD
_decryptSaltReceived = true; _decryptSaltReceived = true;
byte[] salt = _decCircularBuffer.Get(saltLen); byte[] salt = _decCircularBuffer.Get(saltLen);
InitCipher(salt, false, false); InitCipher(salt, false, false);
Logging.Debug("get salt len " + saltLen);
logger.Debug("get salt len " + saltLen);
} }
// handle chunks // handle chunks
@@ -218,7 +220,7 @@ namespace Shadowsocks.Encryption.AEAD
bufSize = _decCircularBuffer.Size; bufSize = _decCircularBuffer.Size;
// check if we have any data // check if we have any data
if (bufSize <= 0) { if (bufSize <= 0) {
Logging.Debug("No data in _decCircularBuffer");
logger.Debug("No data in _decCircularBuffer");
return; return;
} }
@@ -241,13 +243,13 @@ namespace Shadowsocks.Encryption.AEAD
if (chunkLen > CHUNK_LEN_MASK) if (chunkLen > CHUNK_LEN_MASK)
{ {
// we get invalid chunk // we get invalid chunk
Logging.Error($"Invalid chunk length: {chunkLen}");
logger.Error($"Invalid chunk length: {chunkLen}");
throw new CryptoErrorException(); throw new CryptoErrorException();
} }
Logging.Debug("Get the real chunk len:" + chunkLen);
logger.Debug("Get the real chunk len:" + chunkLen);
bufSize = _decCircularBuffer.Size; bufSize = _decCircularBuffer.Size;
if (bufSize < CHUNK_LEN_BYTES + tagLen /* we haven't remove them */+ chunkLen + tagLen) { if (bufSize < CHUNK_LEN_BYTES + tagLen /* we haven't remove them */+ chunkLen + tagLen) {
Logging.Debug("No more data to decrypt one chunk");
logger.Debug("No more data to decrypt one chunk");
return; return;
} }
IncrementNonce(false); IncrementNonce(false);
@@ -267,16 +269,16 @@ namespace Shadowsocks.Encryption.AEAD
// output to outbuf // output to outbuf
Buffer.BlockCopy(decChunkBytes, 0, outbuf, outlength, (int) decChunkLen); Buffer.BlockCopy(decChunkBytes, 0, outbuf, outlength, (int) decChunkLen);
outlength += (int)decChunkLen; outlength += (int)decChunkLen;
Logging.Debug("aead dec outlength " + outlength);
logger.Debug("aead dec outlength " + outlength);
if (outlength + 100 > TCPHandler.BufferSize) if (outlength + 100 > TCPHandler.BufferSize)
{ {
Logging.Debug("dec outbuf almost full, giving up");
logger.Debug("dec outbuf almost full, giving up");
return; return;
} }
bufSize = _decCircularBuffer.Size; bufSize = _decCircularBuffer.Size;
// check if we already done all of them // check if we already done all of them
if (bufSize <= 0) { if (bufSize <= 0) {
Logging.Debug("No data in _decCircularBuffer, already all done");
logger.Debug("No data in _decCircularBuffer, already all done");
return; return;
} }
} }
@@ -319,7 +321,7 @@ namespace Shadowsocks.Encryption.AEAD
private void ChunkEncrypt(byte[] plaintext, int plainLen, byte[] ciphertext, out int cipherLen) private void ChunkEncrypt(byte[] plaintext, int plainLen, byte[] ciphertext, out int cipherLen)
{ {
if (plainLen > CHUNK_LEN_MASK) { if (plainLen > CHUNK_LEN_MASK) {
Logging.Error("enc chunk too big");
logger.Error("enc chunk too big");
throw new CryptoErrorException(); throw new CryptoErrorException();
} }


+ 11
- 8
shadowsocks-csharp/Encryption/AEAD/AEADSodiumEncryptor.cs View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using NLog;
using Shadowsocks.Controller; using Shadowsocks.Controller;
using Shadowsocks.Encryption.Exception; using Shadowsocks.Encryption.Exception;
@@ -9,6 +10,8 @@ namespace Shadowsocks.Encryption.AEAD
public class AEADSodiumEncryptor public class AEADSodiumEncryptor
: AEADEncryptor, IDisposable : AEADEncryptor, IDisposable
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private const int CIPHER_CHACHA20IETFPOLY1305 = 1; private const int CIPHER_CHACHA20IETFPOLY1305 = 1;
private const int CIPHER_XCHACHA20IETFPOLY1305 = 2; private const int CIPHER_XCHACHA20IETFPOLY1305 = 2;
private const int CIPHER_AES256GCM = 3; private const int CIPHER_AES256GCM = 3;
@@ -55,9 +58,9 @@ namespace Shadowsocks.Encryption.AEAD
// outbuf: ciphertext + tag // outbuf: ciphertext + tag
int ret; int ret;
ulong encClen = 0; ulong encClen = 0;
Logging.Dump("_encNonce before enc", _encNonce, nonceLen);
Logging.Dump("_sodiumEncSubkey", _sodiumEncSubkey, keyLen);
Logging.Dump("before cipherEncrypt: plain", plaintext, (int) plen);
logger.Dump("_encNonce before enc", _encNonce, nonceLen);
logger.Dump("_sodiumEncSubkey", _sodiumEncSubkey, keyLen);
logger.Dump("before cipherEncrypt: plain", plaintext, (int) plen);
switch (_cipher) switch (_cipher)
{ {
case CIPHER_CHACHA20IETFPOLY1305: case CIPHER_CHACHA20IETFPOLY1305:
@@ -85,7 +88,7 @@ namespace Shadowsocks.Encryption.AEAD
throw new System.Exception("not implemented"); throw new System.Exception("not implemented");
} }
if (ret != 0) throw new CryptoErrorException(String.Format("ret is {0}", ret)); if (ret != 0) throw new CryptoErrorException(String.Format("ret is {0}", ret));
Logging.Dump("after cipherEncrypt: cipher", ciphertext, (int) encClen);
logger.Dump("after cipherEncrypt: cipher", ciphertext, (int) encClen);
clen = (uint) encClen; clen = (uint) encClen;
} }
@@ -96,9 +99,9 @@ namespace Shadowsocks.Encryption.AEAD
// outbuf: plaintext // outbuf: plaintext
int ret; int ret;
ulong decPlen = 0; ulong decPlen = 0;
Logging.Dump("_decNonce before dec", _decNonce, nonceLen);
Logging.Dump("_sodiumDecSubkey", _sodiumDecSubkey, keyLen);
Logging.Dump("before cipherDecrypt: cipher", ciphertext, (int) clen);
logger.Dump("_decNonce before dec", _decNonce, nonceLen);
logger.Dump("_sodiumDecSubkey", _sodiumDecSubkey, keyLen);
logger.Dump("before cipherDecrypt: cipher", ciphertext, (int) clen);
switch (_cipher) switch (_cipher)
{ {
case CIPHER_CHACHA20IETFPOLY1305: case CIPHER_CHACHA20IETFPOLY1305:
@@ -127,7 +130,7 @@ namespace Shadowsocks.Encryption.AEAD
} }
if (ret != 0) throw new CryptoErrorException(String.Format("ret is {0}", ret)); if (ret != 0) throw new CryptoErrorException(String.Format("ret is {0}", ret));
Logging.Dump("after cipherDecrypt: plain", plaintext, (int) decPlen);
logger.Dump("after cipherDecrypt: plain", plaintext, (int) decPlen);
plen = (uint) decPlen; plen = (uint) decPlen;
} }


+ 4
- 1
shadowsocks-csharp/Encryption/MbedTLS.cs View File

@@ -1,6 +1,7 @@
using System; using System;
using System.IO; using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using NLog;
using Shadowsocks.Controller; using Shadowsocks.Controller;
using Shadowsocks.Properties; using Shadowsocks.Properties;
using Shadowsocks.Util; using Shadowsocks.Util;
@@ -9,6 +10,8 @@ namespace Shadowsocks.Encryption
{ {
public static class MbedTLS public static class MbedTLS
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private const string DLLNAME = "libsscrypto.dll"; private const string DLLNAME = "libsscrypto.dll";
public const int MBEDTLS_ENCRYPT = 1; public const int MBEDTLS_ENCRYPT = 1;
@@ -26,7 +29,7 @@ namespace Shadowsocks.Encryption
} }
catch (System.Exception e) catch (System.Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
LoadLibrary(dllPath); LoadLibrary(dllPath);
} }


+ 4
- 1
shadowsocks-csharp/Encryption/OpenSSL.cs View File

@@ -3,6 +3,7 @@ using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security; using System.Security;
using System.Text; using System.Text;
using NLog;
using Shadowsocks.Controller; using Shadowsocks.Controller;
using Shadowsocks.Encryption.Exception; using Shadowsocks.Encryption.Exception;
using Shadowsocks.Properties; using Shadowsocks.Properties;
@@ -13,6 +14,8 @@ namespace Shadowsocks.Encryption
// XXX: only for OpenSSL 1.1.0 and higher // XXX: only for OpenSSL 1.1.0 and higher
public static class OpenSSL public static class OpenSSL
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private const string DLLNAME = "libsscrypto.dll"; private const string DLLNAME = "libsscrypto.dll";
public const int OPENSSL_ENCRYPT = 1; public const int OPENSSL_ENCRYPT = 1;
@@ -34,7 +37,7 @@ namespace Shadowsocks.Encryption
} }
catch (System.Exception e) catch (System.Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
LoadLibrary(dllPath); LoadLibrary(dllPath);
} }


+ 5
- 2
shadowsocks-csharp/Encryption/Sodium.cs View File

@@ -1,6 +1,7 @@
using System; using System;
using System.IO; using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using NLog;
using Shadowsocks.Controller; using Shadowsocks.Controller;
using Shadowsocks.Properties; using Shadowsocks.Properties;
using Shadowsocks.Util; using Shadowsocks.Util;
@@ -9,6 +10,8 @@ namespace Shadowsocks.Encryption
{ {
public static class Sodium public static class Sodium
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private const string DLLNAME = "libsscrypto.dll"; private const string DLLNAME = "libsscrypto.dll";
private static bool _initialized = false; private static bool _initialized = false;
@@ -28,7 +31,7 @@ namespace Shadowsocks.Encryption
} }
catch (System.Exception e) catch (System.Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
LoadLibrary(dllPath); LoadLibrary(dllPath);
@@ -46,7 +49,7 @@ namespace Shadowsocks.Encryption
} }
AES256GCMAvailable = crypto_aead_aes256gcm_is_available() == 1; AES256GCMAvailable = crypto_aead_aes256gcm_is_available() == 1;
Logging.Debug($"sodium: AES256GCMAvailable is {AES256GCMAvailable}");
logger.Debug($"sodium: AES256GCMAvailable is {AES256GCMAvailable}");
} }
} }
} }


+ 6
- 2
shadowsocks-csharp/Model/Configuration.cs View File

@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using Newtonsoft.Json; using Newtonsoft.Json;
using NLog;
using Shadowsocks.Controller; using Shadowsocks.Controller;
namespace Shadowsocks.Model namespace Shadowsocks.Model
@@ -9,6 +10,9 @@ namespace Shadowsocks.Model
[Serializable] [Serializable]
public class Configuration public class Configuration
{ {
[JsonIgnore]
private static Logger logger = LogManager.GetCurrentClassLogger();
public string version; public string version;
public List<Server> configs; public List<Server> configs;
@@ -105,7 +109,7 @@ namespace Shadowsocks.Model
catch (Exception e) catch (Exception e)
{ {
if (!(e is FileNotFoundException)) if (!(e is FileNotFoundException))
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
return new Configuration return new Configuration
{ {
index = 0, index = 0,
@@ -144,7 +148,7 @@ namespace Shadowsocks.Model
} }
catch (IOException e) catch (IOException e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }


+ 5
- 3
shadowsocks-csharp/Model/StatisticsStrategyConfiguration.cs View File

@@ -5,7 +5,7 @@ using System.Linq;
using System.Reflection; using System.Reflection;


using Newtonsoft.Json; using Newtonsoft.Json;
using NLog;
using Shadowsocks.Controller; using Shadowsocks.Controller;


namespace Shadowsocks.Model namespace Shadowsocks.Model
@@ -13,6 +13,8 @@ namespace Shadowsocks.Model
[Serializable] [Serializable]
public class StatisticsStrategyConfiguration public class StatisticsStrategyConfiguration
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();

public static readonly string ID = "com.shadowsocks.strategy.statistics"; public static readonly string ID = "com.shadowsocks.strategy.statistics";
public bool StatisticsEnabled { get; set; } = false; public bool StatisticsEnabled { get; set; } = false;
public bool ByHourOfDay { get; set; } = true; public bool ByHourOfDay { get; set; } = true;
@@ -39,7 +41,7 @@ namespace Shadowsocks.Model
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
return new StatisticsStrategyConfiguration(); return new StatisticsStrategyConfiguration();
} }
} }
@@ -53,7 +55,7 @@ namespace Shadowsocks.Model
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }




+ 22
- 11
shadowsocks-csharp/Program.cs View File

@@ -3,6 +3,7 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
using NLog;
using Microsoft.Win32; using Microsoft.Win32;
using Shadowsocks.Controller; using Shadowsocks.Controller;
@@ -14,6 +15,7 @@ namespace Shadowsocks
{ {
static class Program static class Program
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
public static ShadowsocksController MainController { get; private set; } public static ShadowsocksController MainController { get; private set; }
public static MenuViewController MenuController { get; private set; } public static MenuViewController MenuController { get; private set; }
public static string[] Args { get; private set; } public static string[] Args { get; private set; }
@@ -24,6 +26,9 @@ namespace Shadowsocks
[STAThread] [STAThread]
static void Main(string[] args) static void Main(string[] args)
{ {
// todo: initialize the NLog configuartion
TouchAndApplyNLogConfig();
// .NET Framework 4.7.2 on Win7 compatibility // .NET Framework 4.7.2 on Win7 compatibility
System.Net.ServicePointManager.SecurityProtocol |= System.Net.ServicePointManager.SecurityProtocol |=
System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12; System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
@@ -79,14 +84,10 @@ namespace Shadowsocks
} }
Directory.SetCurrentDirectory(Application.StartupPath); Directory.SetCurrentDirectory(Application.StartupPath);
#if DEBUG #if DEBUG
Logging.OpenLogFile();
// truncate privoxy log file while debugging // truncate privoxy log file while debugging
string privoxyLogFilename = Utils.GetTempPath("privoxy.log"); string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
if (File.Exists(privoxyLogFilename)) if (File.Exists(privoxyLogFilename))
using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { } using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
#else
Logging.OpenLogFile();
#endif #endif
MainController = new ShadowsocksController(); MainController = new ShadowsocksController();
MenuController = new MenuViewController(MainController); MenuController = new MenuViewController(MainController);
@@ -96,13 +97,23 @@ namespace Shadowsocks
} }
} }
private static void TouchAndApplyNLogConfig()
{
string NLogConfigFileName = "NLog.config";
if (!File.Exists(NLogConfigFileName))
{
File.WriteAllText(NLogConfigFileName, Properties.Resources.NLog_config);
LogManager.LoadConfiguration(NLogConfigFileName);
}
}
private static int exited = 0; private static int exited = 0;
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{ {
if (Interlocked.Increment(ref exited) == 1) if (Interlocked.Increment(ref exited) == 1)
{ {
string errMsg = e.ExceptionObject.ToString(); string errMsg = e.ExceptionObject.ToString();
Logging.Error(errMsg);
logger.Error(errMsg);
MessageBox.Show( MessageBox.Show(
$"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errMsg}", $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errMsg}",
"Shadowsocks non-UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error); "Shadowsocks non-UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
@@ -115,7 +126,7 @@ namespace Shadowsocks
if (Interlocked.Increment(ref exited) == 1) if (Interlocked.Increment(ref exited) == 1)
{ {
string errorMsg = $"Exception Detail: {Environment.NewLine}{e.Exception}"; string errorMsg = $"Exception Detail: {Environment.NewLine}{e.Exception}";
Logging.Error(errorMsg);
logger.Error(errorMsg);
MessageBox.Show( MessageBox.Show(
$"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errorMsg}", $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errorMsg}",
"Shadowsocks UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error); "Shadowsocks UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
@@ -128,7 +139,7 @@ namespace Shadowsocks
switch (e.Mode) switch (e.Mode)
{ {
case PowerModes.Resume: case PowerModes.Resume:
Logging.Info("os wake up");
logger.Info("os wake up");
if (MainController != null) if (MainController != null)
{ {
System.Threading.Tasks.Task.Factory.StartNew(() => System.Threading.Tasks.Task.Factory.StartNew(() =>
@@ -137,11 +148,11 @@ namespace Shadowsocks
try try
{ {
MainController.Start(false); MainController.Start(false);
Logging.Info("controller started");
logger.Info("controller started");
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.LogUsefulException(ex);
logger.LogUsefulException(ex);
} }
}); });
} }
@@ -150,9 +161,9 @@ namespace Shadowsocks
if (MainController != null) if (MainController != null)
{ {
MainController.Stop(); MainController.Stop();
Logging.Info("controller stopped");
logger.Info("controller stopped");
} }
Logging.Info("os suspend");
logger.Info("os suspend");
break; break;
} }
} }


+ 252
- 231
shadowsocks-csharp/Properties/Resources.Designer.cs View File

@@ -1,91 +1,91 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Shadowsocks.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Shadowsocks.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性
/// 重写当前线程的 CurrentUICulture 属性。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// 查找类似 /* eslint-disable */
///// Was generated by gfwlist2pac in precise mode
///// https://github.com/clowwindy/gfwlist2pac
///
///// 2019-10-06: More &apos;javascript&apos; way to interaction with main program
///// 2019-02-08: Updated to support shadowsocks-windows user rules.
///
///var proxy = __PROXY__;
///var userrules = __USERRULES__;
///var rules = __RULES__;
///
////*
///* This file is part of Adblock Plus &lt;http://adblockplus.org/&gt;,
///* Copyright (C) 2006-2014 Eyeo GmbH
///*
///* Adblock Plus is free software: you can redistribute it and/or [字符串的其余部分被截断]&quot;; 的本地化字符串。
/// </summary>
internal static string abp_js {
get {
return ResourceManager.GetString("abp_js", resourceCulture);
}
}
/// <summary>
/// 查找类似 var __USERRULES__ = [];
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Shadowsocks.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Shadowsocks.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to /* eslint-disable */
///// Was generated by gfwlist2pac in precise mode
///// https://github.com/clowwindy/gfwlist2pac
///
///// 2019-10-06: More &apos;javascript&apos; way to interaction with main program
///// 2019-02-08: Updated to support shadowsocks-windows user rules.
///
///var proxy = __PROXY__;
///var userrules = __USERRULES__;
///var rules = __RULES__;
///
////*
///* This file is part of Adblock Plus &lt;http://adblockplus.org/&gt;,
///* Copyright (C) 2006-2014 Eyeo GmbH
///*
///* Adblock Plus is free software: you can redistribute it and/or [rest of string was truncated]&quot;;.
/// </summary>
internal static string abp_js {
get {
return ResourceManager.GetString("abp_js", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to var __USERRULES__ = [];
///var __RULES__ = [ ///var __RULES__ = [
/// &quot;|http://85.17.73.31/&quot;, /// &quot;|http://85.17.73.31/&quot;,
/// &quot;||agnesb.fr&quot;, /// &quot;||agnesb.fr&quot;,
@@ -106,154 +106,175 @@ namespace Shadowsocks.Properties {
/// &quot;||beeg.com&quot;, /// &quot;||beeg.com&quot;,
/// &quot;||global.bing.com&quot;, /// &quot;||global.bing.com&quot;,
/// &quot;||bloombergview.com&quot;, /// &quot;||bloombergview.com&quot;,
/// &quot; [字符串的其余部分被截断]&quot;; 的本地化字符串。
/// </summary>
internal static string default_abp_rule {
get {
return ResourceManager.GetString("default_abp_rule", resourceCulture);
}
}
/// <summary>
/// 查找类似 en,zh-CN,zh-TW,ja
/// &quot;||booktopia.com.au&quot;,
/// [rest of string was truncated]&quot;;.
/// </summary>
internal static string default_abp_rule {
get {
return ResourceManager.GetString("default_abp_rule", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to en,zh-CN,zh-TW,ja
///#Restart program to apply translation,,,
///#This is comment line,,,
///#Always keep language name at head of file,,,
///#Language name is output in log,,,
///&quot;#You can find it by search &quot;&quot;Current language is:&quot;&quot;&quot;,,,
///#Please use UTF-8 with BOM encoding so we can edit it in Excel,,,
///,,, ///,,,
///Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks ///Shadowsocks,Shadowsocks,Shadowsocks,Shadowsocks
///,,, ///,,,
///#Menu,,,
///,,,
///System Proxy,系统代理,系統代理,システムプロキシ ///System Proxy,系统代理,系統代理,システムプロキシ
///Disable,禁用,禁用,無効 ///Disable,禁用,禁用,無効
///PAC,PAC 模式,PAC 模式,PAC ///PAC,PAC 模式,PAC 模式,PAC
///Global,全局模式,全局模式,全般 ///Global,全局模式,全局模式,全般
///Servers,服务器,伺服器,サーバー ///Servers,服务器,伺服器,サーバー
///Edit Servers...,编辑服务器...,編輯伺服器...,サーバーの編集...
///Statistics Config...,统计配置...,統計設定檔...,統計情報の設定...
///Start on Boot,开机启动,開機啟動,システムと同時に起動
///Forward Proxy...,正向代理设置...,正向 Proxy 設定...,フォワードプロキシの設定...
///Allow other Devices to connect,允许其他设备连入,允許其他裝置連入,他のデバイスからの接続を許可する
///Local PAC,使用本地 PAC,使用本機 PAC,ローカル PAC
///Online PAC,使用在线 PAC,使 [字符串的其余部分被截断]&quot;; 的本地化字符串。
/// </summary>
internal static string i18n_csv {
get {
return ResourceManager.GetString("i18n_csv", resourceCulture);
}
}
/// <summary>
/// 查找 System.Byte[] 类型的本地化资源。
/// </summary>
internal static byte[] libsscrypto_dll {
get {
object obj = ResourceManager.GetObject("libsscrypto_dll", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// 查找类似 listen-address __PRIVOXY_BIND_IP__:__PRIVOXY_BIND_PORT__
///toggle 0
///logfile ss_privoxy.log
///show-on-task-bar 0
///activity-animation 0
///forward-socks5 / __SOCKS_HOST__:__SOCKS_PORT__ .
///max-client-connections 2048
///hide-console
/// 的本地化字符串。
/// </summary>
internal static string privoxy_conf {
get {
return ResourceManager.GetString("privoxy_conf", resourceCulture);
}
}
/// <summary>
/// 查找 System.Byte[] 类型的本地化资源。
/// </summary>
internal static byte[] privoxy_exe {
get {
object obj = ResourceManager.GetObject("privoxy_exe", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap ss32Fill {
get {
object obj = ResourceManager.GetObject("ss32Fill", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap ss32In {
get {
object obj = ResourceManager.GetObject("ss32In", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap ss32Out {
get {
object obj = ResourceManager.GetObject("ss32Out", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap ss32Outline {
get {
object obj = ResourceManager.GetObject("ss32Outline", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap ssw128 {
get {
object obj = ResourceManager.GetObject("ssw128", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Byte[] 类型的本地化资源。
/// </summary>
internal static byte[] sysproxy_exe {
get {
object obj = ResourceManager.GetObject("sysproxy_exe", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// 查找 System.Byte[] 类型的本地化资源。
/// </summary>
internal static byte[] sysproxy64_exe {
get {
object obj = ResourceManager.GetObject("sysproxy64_exe", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// 查找类似 ! Put user rules line by line in this file.
///! See https://adblockplus.org/en/filter-cheatsheet
/// 的本地化字符串。
/// </summary>
internal static string user_rule {
get {
return ResourceManager.GetString("user_rule", resourceCulture);
}
}
}
}
///Edit Servers...,编辑服务器...,編輯伺服器...,サーバーの編集.. [rest of string was truncated]&quot;;.
/// </summary>
internal static string i18n_csv {
get {
return ResourceManager.GetString("i18n_csv", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] libsscrypto_dll {
get {
object obj = ResourceManager.GetObject("libsscrypto_dll", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized string similar to &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
///&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;
/// &lt;targets&gt;
/// &lt;target name=&quot;file&quot; xsi:type=&quot;File&quot; fileName=&quot;shadowsocks.log&quot;/&gt;
///
/// &lt;/targets&gt;
/// &lt;rules&gt;
/// &lt;logger name=&quot;Name.Space.Class1&quot; minlevel=&quot;Debug&quot; writeTo=&quot;f1&quot; /&gt;
/// &lt;/rules&gt;
///&lt;/nlog&gt;.
/// </summary>
internal static string NLog_config {
get {
return ResourceManager.GetString("NLog_config", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to listen-address __PRIVOXY_BIND_IP__:__PRIVOXY_BIND_PORT__
///toggle 0
///logfile ss_privoxy.log
///show-on-task-bar 0
///activity-animation 0
///forward-socks5 / __SOCKS_HOST__:__SOCKS_PORT__ .
///max-client-connections 2048
///hide-console
///.
/// </summary>
internal static string privoxy_conf {
get {
return ResourceManager.GetString("privoxy_conf", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] privoxy_exe {
get {
object obj = ResourceManager.GetObject("privoxy_exe", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ss32Fill {
get {
object obj = ResourceManager.GetObject("ss32Fill", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ss32In {
get {
object obj = ResourceManager.GetObject("ss32In", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ss32Out {
get {
object obj = ResourceManager.GetObject("ss32Out", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ss32Outline {
get {
object obj = ResourceManager.GetObject("ss32Outline", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ssw128 {
get {
object obj = ResourceManager.GetObject("ssw128", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sysproxy_exe {
get {
object obj = ResourceManager.GetObject("sysproxy_exe", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sysproxy64_exe {
get {
object obj = ResourceManager.GetObject("sysproxy64_exe", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized string similar to ! Put user rules line by line in this file.
///! See https://adblockplus.org/en/filter-cheatsheet
///.
/// </summary>
internal static string user_rule {
get {
return ResourceManager.GetString("user_rule", resourceCulture);
}
}
}
}

+ 3
- 0
shadowsocks-csharp/Properties/Resources.resx View File

@@ -130,6 +130,9 @@
<data name="libsscrypto_dll" type="System.Resources.ResXFileRef, System.Windows.Forms"> <data name="libsscrypto_dll" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Data\libsscrypto.dll.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>..\Data\libsscrypto.dll.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data> </data>
<data name="NLog_config" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\data\nlog.config;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
<data name="privoxy_conf" type="System.Resources.ResXFileRef, System.Windows.Forms"> <data name="privoxy_conf" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\data\privoxy_conf.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value> <value>..\data\privoxy_conf.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data> </data>


+ 4
- 1
shadowsocks-csharp/Proxy/HttpProxy.cs View File

@@ -4,6 +4,7 @@ using System.Net.Sockets;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
using NLog;
using Shadowsocks.Controller; using Shadowsocks.Controller;
using Shadowsocks.Util.Sockets; using Shadowsocks.Util.Sockets;


@@ -11,6 +12,8 @@ namespace Shadowsocks.Proxy
{ {
public class HttpProxy : IProxy public class HttpProxy : IProxy
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();

private class FakeAsyncResult : IAsyncResult private class FakeAsyncResult : IAsyncResult
{ {
public readonly HttpState innerState; public readonly HttpState innerState;
@@ -179,7 +182,7 @@ namespace Shadowsocks.Proxy


private bool OnLineRead(string line, object state) private bool OnLineRead(string line, object state)
{ {
Logging.Debug(line);
logger.Debug(line);


if (_respondLineCount == 0) if (_respondLineCount == 0)
{ {


+ 4
- 1
shadowsocks-csharp/Util/ProcessManagement/Job.cs View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using NLog;
using Shadowsocks.Controller; using Shadowsocks.Controller;


namespace Shadowsocks.Util.ProcessManagement namespace Shadowsocks.Util.ProcessManagement
@@ -11,6 +12,8 @@ namespace Shadowsocks.Util.ProcessManagement
*/ */
public class Job : IDisposable public class Job : IDisposable
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();

private IntPtr handle = IntPtr.Zero; private IntPtr handle = IntPtr.Zero;


public Job() public Job()
@@ -54,7 +57,7 @@ namespace Shadowsocks.Util.ProcessManagement


if (!succ) if (!succ)
{ {
Logging.Error("Failed to call AssignProcessToJobObject! GetLastError=" + Marshal.GetLastWin32Error());
logger.Error("Failed to call AssignProcessToJobObject! GetLastError=" + Marshal.GetLastWin32Error());
} }


return succ; return succ;


+ 5
- 2
shadowsocks-csharp/Util/SystemProxy/Sysproxy.cs View File

@@ -1,4 +1,5 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using NLog;
using Shadowsocks.Controller; using Shadowsocks.Controller;
using Shadowsocks.Model; using Shadowsocks.Model;
using Shadowsocks.Properties; using Shadowsocks.Properties;
@@ -14,6 +15,8 @@ namespace Shadowsocks.Util.SystemProxy
{ {
public static class Sysproxy public static class Sysproxy
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private const string _userWininetConfigFile = "user-wininet.json"; private const string _userWininetConfigFile = "user-wininet.json";
private readonly static string[] _lanIP = { private readonly static string[] _lanIP = {
@@ -70,7 +73,7 @@ namespace Shadowsocks.Util.SystemProxy
} }
catch (IOException e) catch (IOException e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }
@@ -233,7 +236,7 @@ namespace Shadowsocks.Util.SystemProxy
} }
catch (IOException e) catch (IOException e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
} }
} }


+ 7
- 4
shadowsocks-csharp/Util/Util.cs View File

@@ -1,4 +1,5 @@
using System;
using NLog;
using System;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
@@ -26,6 +27,8 @@ namespace Shadowsocks.Util
public static class Utils public static class Utils
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
private static string _tempPath = null; private static string _tempPath = null;
// return path to store temporary files // return path to store temporary files
@@ -48,7 +51,7 @@ namespace Shadowsocks.Util
} }
catch (Exception e) catch (Exception e)
{ {
Logging.Error(e);
logger.Error(e);
throw; throw;
} }
} }
@@ -80,7 +83,7 @@ namespace Shadowsocks.Util
{ {
if (isVerbose) if (isVerbose)
{ {
Logging.Info(
logger.Info(
$"Cannot get Windows 10 system theme mode, return default value 0 (dark mode)."); $"Cannot get Windows 10 system theme mode, return default value 0 (dark mode).");
} }
} }
@@ -251,7 +254,7 @@ namespace Shadowsocks.Util
} }
catch (Exception e) catch (Exception e)
{ {
Logging.LogUsefulException(e);
logger.LogUsefulException(e);
return null; return null;
} }
} }


+ 7
- 4
shadowsocks-csharp/View/LogForm.cs View File

@@ -11,11 +11,14 @@ using Shadowsocks.Properties;
using Shadowsocks.Model; using Shadowsocks.Model;
using Shadowsocks.Util; using Shadowsocks.Util;
using System.Text; using System.Text;
using NLog;
namespace Shadowsocks.View namespace Shadowsocks.View
{ {
public partial class LogForm : Form public partial class LogForm : Form
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
long lastOffset; long lastOffset;
string filename; string filename;
Timer timer; Timer timer;
@@ -38,7 +41,7 @@ namespace Shadowsocks.View
TextAnnotation outboundAnnotation = new TextAnnotation(); TextAnnotation outboundAnnotation = new TextAnnotation();
#endregion #endregion
public LogForm(ShadowsocksController controller, string filename)
public LogForm(ShadowsocksController controller, string filename=null)
{ {
this.controller = controller; this.controller = controller;
this.filename = filename; this.filename = filename;
@@ -270,7 +273,7 @@ namespace Shadowsocks.View
private void OpenLocationMenuItem_Click(object sender, EventArgs e) private void OpenLocationMenuItem_Click(object sender, EventArgs e)
{ {
string argument = "/select, \"" + filename + "\""; string argument = "/select, \"" + filename + "\"";
Logging.Debug(argument);
logger.Debug(argument);
System.Diagnostics.Process.Start("explorer.exe", argument); System.Diagnostics.Process.Start("explorer.exe", argument);
} }
@@ -287,7 +290,7 @@ namespace Shadowsocks.View
#region Clean up the content in LogMessageTextBox. #region Clean up the content in LogMessageTextBox.
private void DoClearLogs() private void DoClearLogs()
{ {
Logging.Clear();
//logger.Clear();
lastOffset = 0; lastOffset = 0;
LogMessageTextBox.Clear(); LogMessageTextBox.Clear();
} }
@@ -317,7 +320,7 @@ namespace Shadowsocks.View
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.LogUsefulException(ex);
logger.LogUsefulException(ex);
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
} }
} }


+ 5
- 3
shadowsocks-csharp/View/MenuViewController.cs View File

@@ -1,4 +1,5 @@
using Shadowsocks.Controller;
using NLog;
using Shadowsocks.Controller;
using Shadowsocks.Model; using Shadowsocks.Model;
using Shadowsocks.Properties; using Shadowsocks.Properties;
using Shadowsocks.Util; using Shadowsocks.Util;
@@ -17,6 +18,7 @@ namespace Shadowsocks.View
{ {
public class MenuViewController public class MenuViewController
{ {
private static Logger logger = LogManager.GetCurrentClassLogger();
// yes this is just a menu view controller // yes this is just a menu view controller
// when config form is closed, it moves away from RAM // when config form is closed, it moves away from RAM
// and it should just do anything related to the config form // and it should just do anything related to the config form
@@ -386,7 +388,7 @@ namespace Shadowsocks.View
void controller_UpdatePACFromGFWListError(object sender, System.IO.ErrorEventArgs e) void controller_UpdatePACFromGFWListError(object sender, System.IO.ErrorEventArgs e)
{ {
ShowBalloonTip(I18N.GetString("Failed to update PAC file"), e.GetException().Message, ToolTipIcon.Error, 5000); ShowBalloonTip(I18N.GetString("Failed to update PAC file"), e.GetException().Message, ToolTipIcon.Error, 5000);
Logging.LogUsefulException(e.GetException());
logger.LogUsefulException(e.GetException());
} }
void controller_UpdatePACFromGFWListCompleted(object sender, GFWListUpdater.ResultEventArgs e) void controller_UpdatePACFromGFWListCompleted(object sender, GFWListUpdater.ResultEventArgs e)
@@ -543,7 +545,7 @@ namespace Shadowsocks.View
} }
else else
{ {
logForm = new LogForm(controller, Logging.LogFilePath);
logForm = new LogForm(controller);
logForm.Show(); logForm.Show();
logForm.Activate(); logForm.Activate();
logForm.FormClosed += logForm_FormClosed; logForm.FormClosed += logForm_FormClosed;


+ 1
- 0
shadowsocks-csharp/packages.config View File

@@ -5,6 +5,7 @@
<package id="Fody" version="4.2.1" targetFramework="net472" developmentDependency="true" /> <package id="Fody" version="4.2.1" targetFramework="net472" developmentDependency="true" />
<package id="GlobalHotKey" version="1.1.0" targetFramework="net472" /> <package id="GlobalHotKey" version="1.1.0" targetFramework="net472" />
<package id="Newtonsoft.Json" version="12.0.2" targetFramework="net472" /> <package id="Newtonsoft.Json" version="12.0.2" targetFramework="net472" />
<package id="NLog" version="4.6.8" targetFramework="net472" />
<package id="StringEx.CS" version="0.3.1" targetFramework="net472" developmentDependency="true" /> <package id="StringEx.CS" version="0.3.1" targetFramework="net472" developmentDependency="true" />
<package id="ZXing.Net" version="0.16.5" targetFramework="net472" /> <package id="ZXing.Net" version="0.16.5" targetFramework="net472" />
</packages> </packages>

+ 11
- 1
shadowsocks-csharp/shadowsocks-csharp.csproj View File

@@ -82,12 +82,21 @@
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> <Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll</HintPath> <HintPath>..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference> </Reference>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.6.8\lib\net45\NLog.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" /> <Reference Include="PresentationCore" />
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Drawing" /> <Reference Include="System.Drawing" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Management" /> <Reference Include="System.Management" />
<Reference Include="System.Net" /> <Reference Include="System.Net" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Transactions" />
<Reference Include="System.Web" /> <Reference Include="System.Web" />
<Reference Include="System.Windows.Forms" /> <Reference Include="System.Windows.Forms" />
<Reference Include="System.Windows.Forms.DataVisualization" /> <Reference Include="System.Windows.Forms.DataVisualization" />
@@ -102,6 +111,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Controller\HotkeyReg.cs" /> <Compile Include="Controller\HotkeyReg.cs" />
<Compile Include="Controller\LoggerExtension.cs" />
<Compile Include="Controller\Service\PACDaemon.cs" /> <Compile Include="Controller\Service\PACDaemon.cs" />
<Compile Include="Controller\System\Hotkeys\HotkeyCallbacks.cs" /> <Compile Include="Controller\System\Hotkeys\HotkeyCallbacks.cs" />
<Compile Include="Encryption\AEAD\AEADEncryptor.cs" /> <Compile Include="Encryption\AEAD\AEADEncryptor.cs" />
@@ -145,7 +155,6 @@
<Compile Include="Controller\Service\GFWListUpdater.cs" /> <Compile Include="Controller\Service\GFWListUpdater.cs" />
<Compile Include="Controller\I18N.cs" /> <Compile Include="Controller\I18N.cs" />
<Compile Include="Controller\Service\Listener.cs" /> <Compile Include="Controller\Service\Listener.cs" />
<Compile Include="Controller\Logging.cs" />
<Compile Include="Controller\Service\PortForwarder.cs" /> <Compile Include="Controller\Service\PortForwarder.cs" />
<Compile Include="Controller\Service\UDPRelay.cs" /> <Compile Include="Controller\Service\UDPRelay.cs" />
<Compile Include="Controller\Service\UpdateChecker.cs" /> <Compile Include="Controller\Service\UpdateChecker.cs" />
@@ -257,6 +266,7 @@
</None> </None>
<None Include="Data\i18n.csv" /> <None Include="Data\i18n.csv" />
<None Include="Data\libsscrypto.dll.gz" /> <None Include="Data\libsscrypto.dll.gz" />
<None Include="Data\NLog.config" />
<None Include="Data\privoxy.exe.gz" /> <None Include="Data\privoxy.exe.gz" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>


Loading…
Cancel
Save