Compare commits

...
51 Commits
Author SHA1 Message Date
clowwindy a2cd2a5408 update CHANGES 2015-07-25 19:20:17 +08:00
clowwindy 9332741e18 update README 2015-07-25 19:19:20 +08:00
clowwindy 1a68544f7f bump 2015-07-25 19:06:03 +08:00
clowwindy dafe33f7ed fix a crash 2015-07-25 19:05:37 +08:00
clowwindy 008e3544f2 refine HA 2015-07-25 18:39:14 +08:00
clowwindy 449df1022d add connect timeout 2015-07-25 17:40:08 +08:00
clowwindy cb5fece8b3 HA almost works 2015-07-25 16:22:28 +08:00
clowwindy 8c869ca38e add retry 2015-07-25 14:16:29 +08:00
clowwindy ddd46ed8c6 add HA 2015-07-24 04:17:33 +08:00
clowwindy 4afd5faf3f add load balancing 2015-07-22 15:58:39 +08:00
clowwindy da41514839 fix zero IP 2015-07-22 14:32:32 +08:00
clowwindy f6cbf7b73a Update README.md 2015-07-11 19:58:43 +08:00
clowwindy c673f18f80 update CHANGES 2015-07-11 19:47:26 +08:00
clowwindy ccce252d62 bump 2015-07-11 19:36:09 +08:00
clowwindy 544c9dc766 update generated code 2015-07-11 19:35:02 +08:00
clowwindy 21fda9e81b use GitHub releases instead of SourceForge 2015-07-11 19:31:43 +08:00
clowwindy 5906ddbc4b fix warnings 2015-07-11 18:50:10 +08:00
clowwindy f9f49552ae add port check for 8123 2015-07-11 18:38:45 +08:00
clowwindy 09def2fc27 add LRUCache for UDPRelay 2015-07-11 18:32:32 +08:00
clowwindy 680d465393 add UDPRelay 2015-07-11 18:07:49 +08:00
clowwindy f5500c4080 support UDP assoc in UDP relay 2015-07-11 15:41:47 +08:00
clowwindy ef357bbbcf handshake before connecting to server 2015-07-11 13:19:16 +08:00
clowwindy 96f996c6de Update README.md 2015-06-28 14:15:49 +08:00
clowwindy 967c4e8c8b Update CONTRIBUTING.md 2015-04-29 11:42:57 +08:00
clowwindy 5182dcdc66 Update CONTRIBUTING.md 2015-04-29 11:40:05 +08:00
clowwindy 660857a348 Update CONTRIBUTING.md 2015-04-29 11:39:34 +08:00
clowwindy 5c172a3e49 Update README.md 2015-04-04 12:33:23 +08:00
clowwindy dd0ac006b5 Update README.md 2015-04-04 12:25:05 +08:00
clowwindy 95242208ec UX fix
1. only enable menu items relevant to pac status
2. rename edit pac file into edit local pac file
3. users are allowed to enable online pac then input online pac url, not to input then enable
2015-03-22 20:28:40 +08:00
clowwindy 0d4dc2ada6 Merge pull request #197 from GangZhuo/online-pac
Support Online PAC URL
2015-03-21 19:23:38 +08:00
Gang Zhuo 532a53c971 revert 2015-03-21 19:07:58 +08:00
Gang Zhuo c6e6d019f1 fix regular expression 2015-03-21 19:02:17 +08:00
Gang Zhuo 00f57ee329 validate user input 2015-03-21 18:47:05 +08:00
Gang Zhuo 80dc5c0e90 remove not use message 2015-03-20 21:51:07 +08:00
Gang Zhuo 5f2ec3ccff Use VB.NET InputBox instead of implement a message box 2015-03-20 21:26:31 +08:00
Gang Zhuo b762c8046a Direct set the system PAC to the online PAC URL 2015-03-20 21:14:27 +08:00
Gang Zhuo 1bb01bb68e rename CancelButton to MyCancelButton 2015-03-20 01:37:05 -04:00
Gang Zhuo 4d4d02604c layout by TableLayoutPanel 2015-03-20 01:08:01 -04:00
Gang Zhuo f946b0d99c fix I18N 2015-03-20 01:07:10 -04:00
Gang Zhuo e0612854d6 support online pac, see https://github.com/shadowsocks/shadowsocks-csharp/issues/163 2015-03-20 00:46:46 -04:00
clowwindy 9a4f724653 bump 2.3.1 2015-03-06 23:21:56 +08:00
clowwindy fcb0adfc3f add comments in cn.txt 2015-03-06 23:18:23 +08:00
clowwindy eb2e5cc242 add GUI for user rule support 2015-03-06 23:02:07 +08:00
clowwindy 3e16978968 Merge branch 'minoscc-master' 2015-03-04 18:33:41 +08:00
Siuzuk Zan 28887b9896 自定义规则使用user-rule.txt保存 2015-03-04 18:33:13 +08:00
clowwindy d4d3e804cb Merge pull request #174 from wenxiao/master
新增了端口占用检测
2015-02-17 23:35:08 +09:00
WenX 336e0368a1 新增了端口占用检测 2015-02-14 00:14:55 +08:00
clowwindy 138e4f0715 language 2015-01-25 01:18:53 +08:00
clowwindy dbaa2372e2 update README for 2.3 2015-01-25 01:15:49 +08:00
clowwindy 19370a88c5 fix date 2015-01-25 01:10:07 +08:00
clowwindy fbc33ad337 update designer.cs 2015-01-25 01:09:55 +08:00
30 changed files with 1463 additions and 315 deletions
+14 -1
View File
@@ -1,4 +1,17 @@
2.3 2015-01-14
2.5 2015-07-11
- Support load balance
- Support high availability
2.4 2015-07-11
- Support UDP relay
- Support online PAC
- Migrate update checker to GitHub releases
- Other fixes
2.3.1 2015-03-06
- Support user rule
2.3 2015-01-25
- Use the same port for every profile
- Use the same port for HTTP/Socks5/PAC
- Fix GFWList PAC compatibility issue with IE11
+3 -12
View File
@@ -4,24 +4,15 @@ How to Contribute
Pull Requests
-------------
1. Pull requests are welcome. If you would like to add a large feature
or make a significant change, make sure to open an issue to discuss with
people first.
1. Pull requests are welcome.
2. Make sure to pass the unit tests. Write unit tests for new modules if
needed.
Issues
------
1. Only bugs and feature requests are accepted here.
2. We'll only work on important features. If the feature you're asking only
benefits a few people, you'd better implement the feature yourself and send us
a pull request, or ask some of your friends to do so.
3. We don't answer questions of any other types here. Since very few people
are watching the issue tracker here, you'll probably get no help from here.
Read [Troubleshooting] and get help from forums or [mailing lists].
4. Issues in languages other than English will be Google translated into English
later.
1. Nobody has reported any bugs but posted a lot of questions in the last
few months. So we're closing the issue tracker.
[Troubleshooting]: https://github.com/clowwindy/shadowsocks/wiki/Troubleshooting
+32 -17
View File
@@ -6,32 +6,47 @@ Shadowsocks for Windows
#### Features
1. System proxy configuration
2. Fast profile switching
3. PAC mode and global mode
4. Compatible with IE
5. Only a single exe file of 200KB size
2. PAC mode and global mode
3. GFWList and user rules
4. Supports HTTP proxy
5. Supports server auto switching
6. Supports UDP relay (see Usage)
#### Download
Download [latest release].
Download a [latest release].
For <= Windows 7, download Shadowsocks-win-x.x.x.zip.
For >= Windows 8 or with .Net 4.0, download Shadowsocks-win-dotnet4.0-x.x.x.zip.
For >= Windows 8, download Shadowsocks-win-dotnet4.0-x.x.x.zip, unless you have .Net 2.0 installed.
For <= Windows 7 or with .Net 2.0, download Shadowsocks-win-x.x.x.zip.
#### Usage
#### Basic
1. Find Shadowsocks icon in notification tray
1. Find Shadowsocks icon in the notification tray
2. You can add multiple servers in servers menu
3. Select Enable System Proxy menu to enable system proxy
4. After you saved PAC file with any editor, Shadowsocks will notify browsers
about the change automatically
5. Please disable other proxy addons in your browser, or set them to use
system proxy
3. Select Enable System Proxy menu to enable system proxy. Please disable other
proxy addons in your browser, or set them to use system proxy
4. You can also configure your browser proxy manually if you don't want to enable
system proxy. Set Socks5 or HTTP proxy to 127.0.0.1:1080. You can change this
port in Server -> Edit Servers
### Develop
#### PAC
Visual Studio Express 2012 is recommended.
1. You can change PAC rules by editing the PAC file. When you save the PAC file
with any editor, Shadowsocks will notify browsers about the change automatically
2. You can also update PAC file from GFWList (maintained by 3rd party)
3. You can also use online PAC URL
#### Server Auto Switching
1. Load balance: choosing server randomly
2. High availability: choosing the best server (low latency and packet loss)
3. Write your own strategy by implement IStrategy interface and send us a pull request!
#### UDP
For UDP, you need to use SocksCap or ProxyCap to force programs you want
to proxy to tunnel over Shadowsocks
#### License
@@ -40,4 +55,4 @@ GPLv3
[Appveyor]: https://ci.appveyor.com/project/clowwindy/shadowsocks-csharp
[Build Status]: https://ci.appveyor.com/api/projects/status/gknc8l1lxy423ehv/branch/master
[latest release]: https://sourceforge.net/projects/shadowsocksgui/files/dist/
[latest release]: https://github.com/shadowsocks/shadowsocks-csharp/releases
+4
View File
@@ -18,6 +18,10 @@ namespace Shadowsocks.Controller
string[] lines = Regex.Split(Resources.cn, "\r\n|\r|\n");
foreach (string line in lines)
{
if (line.StartsWith("#"))
{
continue;
}
string[] kv = Regex.Split(line, "=");
if (kv.Length == 2)
{
-143
View File
@@ -1,143 +0,0 @@
using Shadowsocks.Model;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Shadowsocks.Controller
{
public class Listener
{
public interface Service
{
bool Handle(byte[] firstPacket, int length, Socket socket);
}
Configuration _config;
bool _shareOverLAN;
Socket _socket;
IList<Service> _services;
public Listener(IList<Service> services)
{
this._services = services;
}
public void Start(Configuration config)
{
this._config = config;
this._shareOverLAN = config.shareOverLan;
try
{
// Create a TCP/IP socket.
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint localEndPoint = null;
if (_shareOverLAN)
{
localEndPoint = new IPEndPoint(IPAddress.Any, _config.localPort);
}
else
{
localEndPoint = new IPEndPoint(IPAddress.Loopback, _config.localPort);
}
// Bind the socket to the local endpoint and listen for incoming connections.
_socket.Bind(localEndPoint);
_socket.Listen(1024);
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Shadowsocks started");
_socket.BeginAccept(
new AsyncCallback(AcceptCallback),
_socket);
}
catch (SocketException)
{
_socket.Close();
throw;
}
}
public void Stop()
{
if (_socket != null)
{
_socket.Close();
_socket = null;
}
}
public void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
try
{
Socket conn = listener.EndAccept(ar);
byte[] buf = new byte[4096];
object[] state = new object[] {
conn,
buf
};
conn.BeginReceive(buf, 0, buf.Length, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (ObjectDisposedException)
{
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
try
{
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
}
catch (ObjectDisposedException)
{
// do nothing
}
catch (Exception e)
{
Logging.LogUsefulException(e);
}
}
}
private void ReceiveCallback(IAsyncResult ar)
{
object[] state = (object[])ar.AsyncState;
Socket conn = (Socket)state[0];
byte[] buf = (byte[])state[1];
try
{
int bytesRead = conn.EndReceive(ar);
foreach (Service service in _services)
{
if (service.Handle(buf, bytesRead, conn))
{
return;
}
}
// no service found for this
// shouldn't happen
conn.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
conn.Close();
}
}
}
}
+11
View File
@@ -31,6 +31,14 @@ namespace Shadowsocks.Controller
}
}
public static void Debug(object o)
{
#if DEBUG
Console.WriteLine(o);
#endif
}
public static void LogUsefulException(Exception e)
{
// just log useful exceptions, not all of them
@@ -55,6 +63,9 @@ namespace Shadowsocks.Controller
Console.WriteLine(e);
}
}
else if (e is ObjectDisposedException)
{
}
else
{
Console.WriteLine(e);
@@ -16,6 +16,8 @@ namespace Shadowsocks.Controller
private static string PAC_FILE = PACServer.PAC_FILE;
private static string USER_RULE_FILE = PACServer.USER_RULE_FILE;
public event EventHandler<ResultEventArgs> UpdateCompleted;
public event ErrorEventHandler Error;
@@ -35,7 +37,17 @@ namespace Shadowsocks.Controller
try
{
List<string> lines = ParseResult(e.Result);
if (File.Exists(USER_RULE_FILE))
{
string local = File.ReadAllText(USER_RULE_FILE, Encoding.UTF8);
string[] rules = local.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string rule in rules)
{
if (rule.StartsWith("!") || rule.StartsWith("["))
continue;
lines.Add(rule);
}
}
string abpContent = Utils.UnGzip(Resources.abp_js);
abpContent = abpContent.Replace("__RULES__", SimpleJson.SimpleJson.SerializeObject(lines));
if (File.Exists(PAC_FILE))
@@ -0,0 +1,218 @@
using Shadowsocks.Model;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
namespace Shadowsocks.Controller
{
public class Listener
{
public interface Service
{
bool Handle(byte[] firstPacket, int length, Socket socket, object state);
}
public class UDPState
{
public byte[] buffer = new byte[4096];
public EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
}
Configuration _config;
bool _shareOverLAN;
Socket _tcpSocket;
Socket _udpSocket;
IList<Service> _services;
public Listener(IList<Service> services)
{
this._services = services;
}
private bool CheckIfPortInUse(int port)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
foreach (IPEndPoint endPoint in ipEndPoints)
{
if (endPoint.Port == port)
{
return true;
}
}
return false;
}
public void Start(Configuration config)
{
this._config = config;
this._shareOverLAN = config.shareOverLan;
if (CheckIfPortInUse(_config.localPort))
throw new Exception(I18N.GetString("Port already in use"));
try
{
// Create a TCP/IP socket.
_tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint localEndPoint = null;
if (_shareOverLAN)
{
localEndPoint = new IPEndPoint(IPAddress.Any, _config.localPort);
}
else
{
localEndPoint = new IPEndPoint(IPAddress.Loopback, _config.localPort);
}
// Bind the socket to the local endpoint and listen for incoming connections.
_tcpSocket.Bind(localEndPoint);
_udpSocket.Bind(localEndPoint);
_tcpSocket.Listen(1024);
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Shadowsocks started");
_tcpSocket.BeginAccept(
new AsyncCallback(AcceptCallback),
_tcpSocket);
UDPState udpState = new UDPState();
_udpSocket.BeginReceiveFrom(udpState.buffer, 0, udpState.buffer.Length, 0, ref udpState.remoteEndPoint, new AsyncCallback(RecvFromCallback), udpState);
}
catch (SocketException)
{
_tcpSocket.Close();
throw;
}
}
public void Stop()
{
if (_tcpSocket != null)
{
_tcpSocket.Close();
_tcpSocket = null;
}
if (_udpSocket != null)
{
_udpSocket.Close();
_udpSocket = null;
}
}
public void RecvFromCallback(IAsyncResult ar)
{
UDPState state = (UDPState)ar.AsyncState;
try
{
int bytesRead = _udpSocket.EndReceiveFrom(ar, ref state.remoteEndPoint);
foreach (Service service in _services)
{
if (service.Handle(state.buffer, bytesRead, _udpSocket, state))
{
break;
}
}
}
catch (ObjectDisposedException)
{
}
catch (Exception)
{
}
finally
{
try
{
_udpSocket.BeginReceiveFrom(state.buffer, 0, state.buffer.Length, 0, ref state.remoteEndPoint, new AsyncCallback(RecvFromCallback), state);
}
catch (ObjectDisposedException)
{
// do nothing
}
catch (Exception)
{
}
}
}
public void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
try
{
Socket conn = listener.EndAccept(ar);
byte[] buf = new byte[4096];
object[] state = new object[] {
conn,
buf
};
conn.BeginReceive(buf, 0, buf.Length, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (ObjectDisposedException)
{
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
try
{
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
}
catch (ObjectDisposedException)
{
// do nothing
}
catch (Exception e)
{
Logging.LogUsefulException(e);
}
}
}
private void ReceiveCallback(IAsyncResult ar)
{
object[] state = (object[])ar.AsyncState;
Socket conn = (Socket)state[0];
byte[] buf = (byte[])state[1];
try
{
int bytesRead = conn.EndReceive(ar);
foreach (Service service in _services)
{
if (service.Handle(buf, bytesRead, conn, null))
{
return;
}
}
// no service found for this
if (conn.ProtocolType == ProtocolType.Tcp)
{
conn.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e);
conn.Close();
}
}
}
}
@@ -16,6 +16,8 @@ namespace Shadowsocks.Controller
{
public static string PAC_FILE = "pac.txt";
public static string USER_RULE_FILE = "user-rule.txt";
FileSystemWatcher watcher;
private Configuration _config;
@@ -31,8 +33,12 @@ namespace Shadowsocks.Controller
this._config = config;
}
public bool Handle(byte[] firstPacket, int length, Socket socket)
public bool Handle(byte[] firstPacket, int length, Socket socket, object state)
{
if (socket.ProtocolType != ProtocolType.Tcp)
{
return false;
}
try
{
string request = Encoding.UTF8.GetString(firstPacket, 0, length);
@@ -94,6 +100,19 @@ namespace Shadowsocks.Controller
}
}
internal string TouchUserRuleFile()
{
if (File.Exists(USER_RULE_FILE))
{
return USER_RULE_FILE;
}
else
{
File.WriteAllText(USER_RULE_FILE, Resources.user_rule);
return USER_RULE_FILE;
}
}
private string GetPACContent()
{
if (File.Exists(PAC_FILE))
@@ -15,8 +15,12 @@ namespace Shadowsocks.Controller
this._targetPort = targetPort;
}
public bool Handle(byte[] firstPacket, int length, Socket socket)
public bool Handle(byte[] firstPacket, int length, Socket socket, object state)
{
if (socket.ProtocolType != ProtocolType.Tcp)
{
return false;
}
new Handler().Start(firstPacket, length, socket, this._targetPort);
return true;
}
@@ -5,20 +5,26 @@ using System.Net.Sockets;
using System.Net;
using Shadowsocks.Encryption;
using Shadowsocks.Model;
using Shadowsocks.Controller.Strategy;
using System.Timers;
namespace Shadowsocks.Controller
{
class Local : Listener.Service
class TCPRelay : Listener.Service
{
private Configuration _config;
public Local(Configuration config)
private ShadowsocksController _controller;
public TCPRelay(ShadowsocksController controller)
{
this._config = config;
this._controller = controller;
}
public bool Handle(byte[] firstPacket, int length, Socket socket)
public bool Handle(byte[] firstPacket, int length, Socket socket, object state)
{
if (socket.ProtocolType != ProtocolType.Tcp)
{
return false;
}
if (length < 2 || firstPacket[0] != 5)
{
return false;
@@ -26,9 +32,7 @@ namespace Shadowsocks.Controller
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
Handler handler = new Handler();
handler.connection = socket;
Server server = _config.GetCurrentServer();
handler.encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
handler.server = server;
handler.controller = _controller;
handler.Start(firstPacket, length);
return true;
@@ -43,12 +47,20 @@ namespace Shadowsocks.Controller
// Client socket.
public Socket remote;
public Socket connection;
public ShadowsocksController controller;
private int retryCount = 0;
private bool connected;
private byte command;
private byte[] _firstPacket;
private int _firstPacketLength;
// Size of receive buffer.
public const int RecvSize = 16384;
public const int BufferSize = RecvSize + 32;
private int totalRead = 0;
private int totalWrite = 0;
// remote receive buffer
private byte[] remoteRecvBuffer = new byte[RecvSize];
// remote send buffer
@@ -66,36 +78,20 @@ namespace Shadowsocks.Controller
private object encryptionLock = new object();
private object decryptionLock = new object();
private DateTime _startConnectTime;
public void CreateRemote()
{
Server server = controller.GetAServer(IStrategyCallerType.TCP, (IPEndPoint)connection.RemoteEndPoint);
this.encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
this.server = server;
}
public void Start(byte[] firstPacket, int length)
{
this._firstPacket = firstPacket;
this._firstPacketLength = length;
try
{
// TODO async resolving
IPAddress ipAddress;
bool parsed = IPAddress.TryParse(server.server, out ipAddress);
if (!parsed)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server);
ipAddress = ipHostInfo.AddressList[0];
}
IPEndPoint remoteEP = new IPEndPoint(ipAddress, server.server_port);
remote = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
// Connect to the remote endpoint.
remote.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), null);
}
catch (Exception e)
{
Logging.LogUsefulException(e);
this.Close();
}
this.HandshakeReceive();
}
private void CheckClose()
@@ -135,7 +131,7 @@ namespace Shadowsocks.Controller
remote.Shutdown(SocketShutdown.Both);
remote.Close();
}
catch (SocketException e)
catch (Exception e)
{
Logging.LogUsefulException(e);
}
@@ -144,33 +140,14 @@ namespace Shadowsocks.Controller
{
lock (decryptionLock)
{
((IDisposable)encryptor).Dispose();
if (encryptor != null)
{
((IDisposable)encryptor).Dispose();
}
}
}
}
private void ConnectCallback(IAsyncResult ar)
{
if (closed)
{
return;
}
try
{
// Complete the connection.
remote.EndConnect(ar);
//Console.WriteLine("Socket connected to {0}",
// remote.RemoteEndPoint.ToString());
HandshakeReceive();
}
catch (Exception e)
{
Logging.LogUsefulException(e);
this.Close();
}
}
private void HandshakeReceive()
{
@@ -241,11 +218,19 @@ namespace Shadowsocks.Controller
try
{
int bytesRead = connection.EndReceive(ar);
if (bytesRead > 0)
if (bytesRead >= 3)
{
byte[] response = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 };
connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(StartPipe), null);
command = connetionRecvBuffer[1];
if (command == 1)
{
byte[] response = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 };
connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(ResponseCallback), null);
}
else if (command == 3)
{
HandleUDPAssociate();
}
}
else
{
@@ -260,8 +245,209 @@ namespace Shadowsocks.Controller
}
}
private void HandleUDPAssociate()
{
IPEndPoint endPoint = (IPEndPoint)connection.LocalEndPoint;
byte[] address = endPoint.Address.GetAddressBytes();
int port = endPoint.Port;
byte[] response = new byte[4 + address.Length + 2];
response[0] = 5;
if (endPoint.AddressFamily == AddressFamily.InterNetwork)
{
response[3] = 1;
}
else if (endPoint.AddressFamily == AddressFamily.InterNetworkV6)
{
response[3] = 4;
}
address.CopyTo(response, 4);
response[response.Length - 1] = (byte)(port & 0xFF);
response[response.Length - 2] = (byte)((port >> 8) & 0xFF);
connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(ReadAll), true);
}
private void StartPipe(IAsyncResult ar)
private void ReadAll(IAsyncResult ar)
{
if (closed)
{
return;
}
try
{
if (ar.AsyncState != null)
{
connection.EndSend(ar);
connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
new AsyncCallback(ReadAll), null);
}
else
{
int bytesRead = connection.EndReceive(ar);
if (bytesRead > 0)
{
connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
new AsyncCallback(ReadAll), null);
}
else
{
this.Close();
}
}
}
catch (Exception e)
{
Logging.LogUsefulException(e);
this.Close();
}
}
private void ResponseCallback(IAsyncResult ar)
{
try
{
connection.EndSend(ar);
StartConnect();
}
catch (Exception e)
{
Logging.LogUsefulException(e);
this.Close();
}
}
private class ServerTimer : Timer
{
public Server Server;
public ServerTimer(int p) :base(p)
{
}
}
private void StartConnect()
{
try
{
CreateRemote();
// TODO async resolving
IPAddress ipAddress;
bool parsed = IPAddress.TryParse(server.server, out ipAddress);
if (!parsed)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server);
ipAddress = ipHostInfo.AddressList[0];
}
IPEndPoint remoteEP = new IPEndPoint(ipAddress, server.server_port);
remote = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
_startConnectTime = DateTime.Now;
ServerTimer connectTimer = new ServerTimer(3000);
connectTimer.AutoReset = false;
connectTimer.Elapsed += connectTimer_Elapsed;
connectTimer.Enabled = true;
connectTimer.Server = server;
connected = false;
// Connect to the remote endpoint.
remote.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), connectTimer);
}
catch (Exception e)
{
Logging.LogUsefulException(e);
this.Close();
}
}
private void connectTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (connected)
{
return;
}
Server server = ((ServerTimer)sender).Server;
IStrategy strategy = controller.GetCurrentStrategy();
if (strategy != null)
{
strategy.SetFailure(server);
}
Console.WriteLine(String.Format("{0} timed out", server.FriendlyName()));
remote.Close();
RetryConnect();
}
private void RetryConnect()
{
if (retryCount < 4)
{
Logging.Debug("Connection failed, retrying");
StartConnect();
retryCount++;
}
else
{
this.Close();
}
}
private void ConnectCallback(IAsyncResult ar)
{
Server server = null;
if (closed)
{
return;
}
try
{
ServerTimer timer = (ServerTimer)ar.AsyncState;
server = timer.Server;
timer.Elapsed -= connectTimer_Elapsed;
timer.Enabled = false;
timer.Dispose();
// Complete the connection.
remote.EndConnect(ar);
connected = true;
//Console.WriteLine("Socket connected to {0}",
// remote.RemoteEndPoint.ToString());
var latency = DateTime.Now - _startConnectTime;
IStrategy strategy = controller.GetCurrentStrategy();
if (strategy != null)
{
strategy.UpdateLatency(server, latency);
}
StartPipe();
}
catch (ArgumentException e)
{
}
catch (Exception e)
{
if (server != null)
{
IStrategy strategy = controller.GetCurrentStrategy();
if (strategy != null)
{
strategy.SetFailure(server);
}
}
Logging.LogUsefulException(e);
RetryConnect();
}
}
private void StartPipe()
{
if (closed)
{
@@ -269,7 +455,6 @@ namespace Shadowsocks.Controller
}
try
{
connection.EndReceive(ar);
remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0,
new AsyncCallback(PipeRemoteReceiveCallback), null);
connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
@@ -291,6 +476,7 @@ namespace Shadowsocks.Controller
try
{
int bytesRead = remote.EndReceive(ar);
totalRead += bytesRead;
if (bytesRead > 0)
{
@@ -304,6 +490,12 @@ namespace Shadowsocks.Controller
encryptor.Decrypt(remoteRecvBuffer, bytesRead, remoteSendBuffer, out bytesToSend);
}
connection.BeginSend(remoteSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeConnectionSendCallback), null);
IStrategy strategy = controller.GetCurrentStrategy();
if (strategy != null)
{
strategy.UpdateLastRead(this.server);
}
}
else
{
@@ -311,6 +503,13 @@ namespace Shadowsocks.Controller
connection.Shutdown(SocketShutdown.Send);
connectionShutdown = true;
CheckClose();
if (totalRead == 0)
{
// closed before anything received, reports as failure
// disable this feature
// controller.GetCurrentStrategy().SetFailure(this.server);
}
}
}
catch (Exception e)
@@ -329,6 +528,7 @@ namespace Shadowsocks.Controller
try
{
int bytesRead = connection.EndReceive(ar);
totalWrite += bytesRead;
if (bytesRead > 0)
{
@@ -342,6 +542,13 @@ namespace Shadowsocks.Controller
encryptor.Encrypt(connetionRecvBuffer, bytesRead, connetionSendBuffer, out bytesToSend);
}
remote.BeginSend(connetionSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeRemoteSendCallback), null);
IStrategy strategy = controller.GetCurrentStrategy();
if (strategy != null)
{
strategy.UpdateLastWrite(this.server);
}
}
else
{
@@ -0,0 +1,200 @@
using System;
using System.Collections.Generic;
using System.Text;
using Shadowsocks.Encryption;
using Shadowsocks.Model;
using System.Net.Sockets;
using System.Net;
using System.Runtime.CompilerServices;
using Shadowsocks.Controller.Strategy;
namespace Shadowsocks.Controller
{
class UDPRelay : Listener.Service
{
private ShadowsocksController _controller;
private LRUCache<IPEndPoint, UDPHandler> _cache;
public UDPRelay(ShadowsocksController controller)
{
this._controller = controller;
this._cache = new LRUCache<IPEndPoint, UDPHandler>(512); // todo: choose a smart number
}
public bool Handle(byte[] firstPacket, int length, Socket socket, object state)
{
if (socket.ProtocolType != ProtocolType.Udp)
{
return false;
}
if (length < 4)
{
return false;
}
Listener.UDPState udpState = (Listener.UDPState)state;
IPEndPoint remoteEndPoint = (IPEndPoint)udpState.remoteEndPoint;
UDPHandler handler = _cache.get(remoteEndPoint);
if (handler == null)
{
handler = new UDPHandler(socket, _controller.GetAServer(IStrategyCallerType.UDP, remoteEndPoint), remoteEndPoint);
_cache.add(remoteEndPoint, handler);
}
handler.Send(firstPacket, length);
handler.Receive();
return true;
}
public class UDPHandler
{
private Socket _local;
private Socket _remote;
private Server _server;
private byte[] _buffer = new byte[1500];
private IPEndPoint _localEndPoint;
private IPEndPoint _remoteEndPoint;
public UDPHandler(Socket local, Server server, IPEndPoint localEndPoint)
{
_local = local;
_server = server;
_localEndPoint = localEndPoint;
// TODO async resolving
IPAddress ipAddress;
bool parsed = IPAddress.TryParse(server.server, out ipAddress);
if (!parsed)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server);
ipAddress = ipHostInfo.AddressList[0];
}
_remoteEndPoint = new IPEndPoint(ipAddress, server.server_port);
_remote = new Socket(_remoteEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
}
public void Send(byte[] data, int length)
{
IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);
byte[] dataIn = new byte[length - 3];
Array.Copy(data, 3, dataIn, 0, length - 3);
byte[] dataOut = new byte[length - 3 + 16];
int outlen;
encryptor.Encrypt(dataIn, dataIn.Length, dataOut, out outlen);
_remote.SendTo(dataOut, _remoteEndPoint);
}
public void Receive()
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
_remote.BeginReceiveFrom(_buffer, 0, _buffer.Length, 0, ref remoteEndPoint, new AsyncCallback(RecvFromCallback), null);
}
public void RecvFromCallback(IAsyncResult ar)
{
try
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
int bytesRead = _remote.EndReceiveFrom(ar, ref remoteEndPoint);
byte[] dataOut = new byte[bytesRead];
int outlen;
IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);
encryptor.Decrypt(_buffer, bytesRead, dataOut, out outlen);
byte[] sendBuf = new byte[outlen + 3];
Array.Copy(dataOut, 0, sendBuf, 3, outlen);
_local.SendTo(sendBuf, outlen + 3, 0, _localEndPoint);
Receive();
}
catch (ObjectDisposedException)
{
}
catch (Exception)
{
}
finally
{
}
}
public void Close()
{
try
{
_remote.Close();
}
catch (ObjectDisposedException)
{
}
catch (Exception)
{
}
finally
{
}
}
}
}
// cc by-sa 3.0 http://stackoverflow.com/a/3719378/1124054
class LRUCache<K, V> where V : UDPRelay.UDPHandler
{
private int capacity;
private Dictionary<K, LinkedListNode<LRUCacheItem<K, V>>> cacheMap = new Dictionary<K, LinkedListNode<LRUCacheItem<K, V>>>();
private LinkedList<LRUCacheItem<K, V>> lruList = new LinkedList<LRUCacheItem<K, V>>();
public LRUCache(int capacity)
{
this.capacity = capacity;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public V get(K key)
{
LinkedListNode<LRUCacheItem<K, V>> node;
if (cacheMap.TryGetValue(key, out node))
{
V value = node.Value.value;
lruList.Remove(node);
lruList.AddLast(node);
return value;
}
return default(V);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void add(K key, V val)
{
if (cacheMap.Count >= capacity)
{
RemoveFirst();
}
LRUCacheItem<K, V> cacheItem = new LRUCacheItem<K, V>(key, val);
LinkedListNode<LRUCacheItem<K, V>> node = new LinkedListNode<LRUCacheItem<K, V>>(cacheItem);
lruList.AddLast(node);
cacheMap.Add(key, node);
}
private void RemoveFirst()
{
// Remove from LRUPriority
LinkedListNode<LRUCacheItem<K, V>> node = lruList.First;
lruList.RemoveFirst();
// Remove from cache
cacheMap.Remove(node.Value.key);
node.Value.value.Close();
}
}
class LRUCacheItem<K, V>
{
public LRUCacheItem(K k, V v)
{
key = k;
value = v;
}
public K key;
public V value;
}
}
@@ -6,24 +6,25 @@ using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using SimpleJson;
namespace Shadowsocks.Controller
{
public class UpdateChecker
{
private const string UpdateURL = "https://sourceforge.net/api/file/index/project-id/1817190/path/dist/mtime/desc/limit/10/rss";
private const string UpdateURL = "https://api.github.com/repos/shadowsocks/shadowsocks-csharp/releases";
public string LatestVersionNumber;
public string LatestVersionURL;
public event EventHandler NewVersionFound;
public const string Version = "2.3";
public const string Version = "2.5";
public void CheckUpdate(Configuration config)
{
// TODO test failures
WebClient http = new WebClient();
http.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.3319.102 Safari/537.36");
http.Proxy = new WebProxy(IPAddress.Loopback.ToString(), config.localPort);
http.DownloadStringCompleted += http_DownloadStringCompleted;
http.DownloadStringAsync(new Uri(UpdateURL));
@@ -119,23 +120,25 @@ namespace Shadowsocks.Controller
{
string response = e.Result;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(response);
XmlNodeList elements = xmlDoc.GetElementsByTagName("media:content");
JsonArray result = (JsonArray)SimpleJson.SimpleJson.DeserializeObject(e.Result);
List<string> versions = new List<string>();
foreach (XmlNode el in elements)
foreach (JsonObject release in result)
{
foreach (XmlAttribute attr in el.Attributes)
if ((bool)release["prerelease"])
{
if (attr.Name == "url")
continue;
}
foreach (JsonObject asset in (JsonArray)release["assets"])
{
string url = (string)asset["browser_download_url"];
if (IsNewVersion(url))
{
if (IsNewVersion(attr.Value))
{
versions.Add(attr.Value);
}
versions.Add(url);
}
}
}
if (versions.Count == 0)
{
return;
@@ -5,6 +5,8 @@ using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using Shadowsocks.Controller.Strategy;
using System.Net;
namespace Shadowsocks.Controller
{
@@ -20,6 +22,7 @@ namespace Shadowsocks.Controller
private Listener _listener;
private PACServer _pacServer;
private Configuration _config;
private StrategyManager _strategyManager;
private PolipoRunner polipoRunner;
private GFWListUpdater gfwListUpdater;
private bool stopped = false;
@@ -38,6 +41,7 @@ namespace Shadowsocks.Controller
// when user clicked Edit PAC, and PAC file has already created
public event EventHandler<PathEventArgs> PACFileReadyToOpen;
public event EventHandler<PathEventArgs> UserRuleFileReadyToOpen;
public event EventHandler<GFWListUpdater.ResultEventArgs> UpdatePACFromGFWListCompleted;
@@ -48,6 +52,7 @@ namespace Shadowsocks.Controller
public ShadowsocksController()
{
_config = Configuration.Load();
_strategyManager = new StrategyManager(this);
}
public void Start()
@@ -69,11 +74,44 @@ namespace Shadowsocks.Controller
}
// always return copy
public Configuration GetConfiguration()
public Configuration GetConfigurationCopy()
{
return Configuration.Load();
}
// always return current instance
public Configuration GetCurrentConfiguration()
{
return _config;
}
public IList<IStrategy> GetStrategies()
{
return _strategyManager.GetStrategies();
}
public IStrategy GetCurrentStrategy()
{
foreach (var strategy in _strategyManager.GetStrategies())
{
if (strategy.ID == this._config.strategy)
{
return strategy;
}
}
return null;
}
public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint)
{
IStrategy strategy = GetCurrentStrategy();
if (strategy != null)
{
return strategy.GetAServer(type, localIPEndPoint);
}
return GetCurrentServer();
}
public void SaveServers(List<Server> servers, int localPort)
{
_config.configs = servers;
@@ -133,6 +171,14 @@ namespace Shadowsocks.Controller
public void SelectServerIndex(int index)
{
_config.index = index;
_config.strategy = null;
SaveConfig(_config);
}
public void SelectStrategy(string strategyID)
{
_config.index = -1;
_config.strategy = strategyID;
SaveConfig(_config);
}
@@ -166,6 +212,15 @@ namespace Shadowsocks.Controller
}
}
public void TouchUserRuleFile()
{
string userRuleFilename = _pacServer.TouchUserRuleFile();
if (UserRuleFileReadyToOpen != null)
{
UserRuleFileReadyToOpen(this, new PathEventArgs() { Path = userRuleFilename });
}
}
public string GetQRCodeForCurrentServer()
{
Server server = GetCurrentServer();
@@ -182,6 +237,28 @@ namespace Shadowsocks.Controller
}
}
public void SavePACUrl(string pacUrl)
{
_config.pacUrl = pacUrl;
UpdateSystemProxy();
SaveConfig(_config);
if (ConfigChanged != null)
{
ConfigChanged(this, new EventArgs());
}
}
public void UseOnlinePAC(bool useOnlinePac)
{
_config.useOnlinePac = useOnlinePac;
UpdateSystemProxy();
SaveConfig(_config);
if (ConfigChanged != null)
{
ConfigChanged(this, new EventArgs());
}
}
protected void Reload()
{
// some logic in configuration updated the config when saving, we need to read it again
@@ -216,11 +293,18 @@ namespace Shadowsocks.Controller
polipoRunner.Stop();
try
{
foreach (var strategy in GetStrategies())
{
strategy.ReloadServers();
}
polipoRunner.Start(_config);
Local local = new Local(_config);
TCPRelay tcpRelay = new TCPRelay(this);
UDPRelay udpRelay = new UDPRelay(this);
List<Listener.Service> services = new List<Listener.Service>();
services.Add(local);
services.Add(tcpRelay);
services.Add(udpRelay);
services.Add(_pacServer);
services.Add(new PortForwarder(polipoRunner.RunningPort));
_listener = new Listener(services);
@@ -0,0 +1,71 @@
using Shadowsocks.Controller;
using Shadowsocks.Model;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace Shadowsocks.Controller.Strategy
{
class BalancingStrategy : IStrategy
{
ShadowsocksController _controller;
Random _random;
public BalancingStrategy(ShadowsocksController controller)
{
_controller = controller;
_random = new Random();
}
public string Name
{
get { return I18N.GetString("Load Balance"); }
}
public string ID
{
get { return "com.shadowsocks.strategy.balancing"; }
}
public void ReloadServers()
{
// do nothing
}
public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint)
{
var configs = _controller.GetCurrentConfiguration().configs;
int index;
if (type == IStrategyCallerType.TCP)
{
index = _random.Next();
}
else
{
index = localIPEndPoint.GetHashCode();
}
return configs[index % configs.Count];
}
public void UpdateLatency(Model.Server server, TimeSpan latency)
{
// do nothing
}
public void UpdateLastRead(Model.Server server)
{
// do nothing
}
public void UpdateLastWrite(Model.Server server)
{
// do nothing
}
public void SetFailure(Model.Server server)
{
// do nothing
}
}
}
@@ -0,0 +1,177 @@
using Shadowsocks.Model;
using System;
using System.Collections.Generic;
using System.Text;
namespace Shadowsocks.Controller.Strategy
{
class HighAvailabilityStrategy : IStrategy
{
protected Server _currentServer;
protected Dictionary<Server, ServerStatus> _serverStatus;
ShadowsocksController _controller;
Random _random;
public class ServerStatus
{
// time interval between SYN and SYN+ACK
public TimeSpan latency;
public DateTime lastTimeDetectLatency;
// last time anything received
public DateTime lastRead;
// last time anything sent
public DateTime lastWrite;
// connection refused or closed before anything received
public DateTime lastFailure;
public Server server;
public double score;
}
public HighAvailabilityStrategy(ShadowsocksController controller)
{
_controller = controller;
_random = new Random();
_serverStatus = new Dictionary<Server, ServerStatus>();
}
public string Name
{
get { return I18N.GetString("High Availability"); }
}
public string ID
{
get { return "com.shadowsocks.strategy.ha"; }
}
public void ReloadServers()
{
// make a copy to avoid locking
var newServerStatus = new Dictionary<Server, ServerStatus>(_serverStatus);
foreach (var server in _controller.GetCurrentConfiguration().configs)
{
if (!newServerStatus.ContainsKey(server))
{
var status = new ServerStatus();
status.server = server;
status.lastFailure = DateTime.MinValue;
status.lastRead = DateTime.Now;
status.lastWrite = DateTime.Now;
status.latency = new TimeSpan(0, 0, 0, 0, 10);
status.lastTimeDetectLatency = DateTime.Now;
newServerStatus[server] = status;
}
}
_serverStatus = newServerStatus;
ChooseNewServer();
}
public Server GetAServer(IStrategyCallerType type, System.Net.IPEndPoint localIPEndPoint)
{
if (type == IStrategyCallerType.TCP)
{
ChooseNewServer();
}
return _currentServer;
}
/**
* once failed, try after 5 min
* and (last write - last read) < 5s
* and (now - last read) < 5s // means not stuck
* and latency < 200ms, try after 30s
*/
public void ChooseNewServer()
{
Server oldServer = _currentServer;
List<ServerStatus> servers = new List<ServerStatus>(_serverStatus.Values);
DateTime now = DateTime.Now;
foreach (var status in servers)
{
// all of failure, latency, (lastread - lastwrite) normalized to 1000, then
// 100 * failure - 2 * latency - 0.5 * (lastread - lastwrite)
status.score =
100 * 1000 * Math.Min(5 * 60, (now - status.lastFailure).TotalSeconds)
-2 * 5 * (Math.Min(2000, status.latency.TotalMilliseconds) / (1 + (now - status.lastTimeDetectLatency).TotalSeconds / 30 / 10) +
-0.5 * 200 * Math.Min(5, (status.lastRead - status.lastWrite).TotalSeconds));
Logging.Debug(String.Format("server: {0} latency:{1} score: {2}", status.server.FriendlyName(), status.latency, status.score));
}
ServerStatus max = null;
foreach (var status in servers)
{
if (max == null)
{
max = status;
}
else
{
if (status.score >= max.score)
{
max = status;
}
}
}
if (max != null)
{
_currentServer = max.server;
if (_currentServer != oldServer)
{
Console.WriteLine("HA switching to server: {0}", _currentServer.FriendlyName());
}
Logging.Debug(String.Format("choosing server: {0}", _currentServer.FriendlyName()));
}
}
public void UpdateLatency(Model.Server server, TimeSpan latency)
{
Logging.Debug(String.Format("latency: {0} {1}", server.FriendlyName(), latency));
ServerStatus status;
if (_serverStatus.TryGetValue(server, out status))
{
status.latency = latency;
status.lastTimeDetectLatency = DateTime.Now;
}
}
public void UpdateLastRead(Model.Server server)
{
Logging.Debug(String.Format("last read: {0}", server.FriendlyName()));
ServerStatus status;
if (_serverStatus.TryGetValue(server, out status))
{
status.lastRead = DateTime.Now;
}
}
public void UpdateLastWrite(Model.Server server)
{
Logging.Debug(String.Format("last write: {0}", server.FriendlyName()));
ServerStatus status;
if (_serverStatus.TryGetValue(server, out status))
{
status.lastWrite = DateTime.Now;
}
}
public void SetFailure(Model.Server server)
{
Logging.Debug(String.Format("failure: {0}", server.FriendlyName()));
ServerStatus status;
if (_serverStatus.TryGetValue(server, out status))
{
status.lastFailure = DateTime.Now;
}
}
}
}
@@ -0,0 +1,56 @@
using Shadowsocks.Model;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace Shadowsocks.Controller.Strategy
{
public enum IStrategyCallerType
{
TCP,
UDP
}
/*
* IStrategy
*
* Subclasses must be thread-safe
*/
public interface IStrategy
{
string Name { get; }
string ID { get; }
/*
* Called when servers need to be reloaded, i.e. new configuration saved
*/
void ReloadServers();
/*
* Get a new server to use in TCPRelay or UDPRelay
*/
Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint);
/*
* TCPRelay will call this when latency of a server detected
*/
void UpdateLatency(Server server, TimeSpan latency);
/*
* TCPRelay will call this when reading from a server
*/
void UpdateLastRead(Server server);
/*
* TCPRelay will call this when writing to a server
*/
void UpdateLastWrite(Server server);
/*
* TCPRelay will call this when fatal failure detected
*/
void SetFailure(Server server);
}
}
@@ -0,0 +1,23 @@
using Shadowsocks.Controller;
using System;
using System.Collections.Generic;
using System.Text;
namespace Shadowsocks.Controller.Strategy
{
class StrategyManager
{
List<IStrategy> _strategies;
public StrategyManager(ShadowsocksController controller)
{
_strategies = new List<IStrategy>();
_strategies.Add(new BalancingStrategy(controller));
_strategies.Add(new HighAvailabilityStrategy(controller));
// TODO: load DLL plugins
}
public IList<IStrategy> GetStrategies()
{
return _strategies;
}
}
}
@@ -49,9 +49,14 @@ namespace Shadowsocks.Controller
}
else
{
string pacUrl;
if (config.useOnlinePac && !string.IsNullOrEmpty(config.pacUrl))
pacUrl = config.pacUrl;
else
pacUrl = "http://127.0.0.1:" + config.localPort.ToString() + "/pac?t=" + GetTimestamp(DateTime.Now);
registry.SetValue("ProxyEnable", 0);
registry.SetValue("ProxyServer", "");
registry.SetValue("AutoConfigURL", "http://127.0.0.1:" + config.localPort.ToString() + "/pac?t=" + GetTimestamp(DateTime.Now));
registry.SetValue("AutoConfigURL", pacUrl);
}
}
else
+29 -3
View File
@@ -1,4 +1,9 @@
# translation for Simplified Chinese
Shadowsocks=Shadowsocks
# Menu items
Enable System Proxy=启用系统代理
Mode=系统代理模式
PAC=PAC 模式
@@ -7,13 +12,22 @@ Servers=服务器
Edit Servers...=编辑服务器...
Start on Boot=开机启动
Allow Clients from LAN=允许来自局域网的连接
Edit PAC File...=编辑 PAC 文件...
Local PAC=使用本地 PAC
Online PAC=使用在线 PAC
Edit Local PAC File...=编辑本地 PAC 文件...
Update Local PAC from GFWList=从 GFWList 更新本地 PAC
Edit User Rule for GFWList...=编辑 GFWList 的用户规则...
Show QRCode...=显示二维码...
Scan QRCode from Screen...=扫描屏幕上的二维码...
Show Logs...=显示日志...
About...=关于...
Quit=退出
Edit Servers=编辑服务器
Load Balance=负载均衡
High Availability=高可用
# Config Form
&Add=添加(&A)
&Delete=删除(&D)
Server=服务器
@@ -26,7 +40,19 @@ Remarks=备注
OK=确定
Cancel=取消
New server=未配置的服务器
# QRCode Form
QRCode=二维码
# PAC Url Form
Edit Online PAC URL=编辑在线 PAC 网址
Edit Online PAC URL...=编辑在线 PAC 网址...
Please input PAC Url=请输入 PAC 网址
# Messages
Shadowsocks Error: {0}=Shadowsocks 错误: {0}
Port already in use=端口已被占用
Illegal port number format=非法端口格式
@@ -34,17 +60,17 @@ Please add at least one server=请添加至少一个服务器
Server IP can not be blank=服务器 IP 不能为空
Password can not be blank=密码不能为空
Port out of range=端口超出范围
Port can't be 8123=端口不能为 8123
Shadowsocks {0} Update Found=Shadowsocks {0} 更新
Click here to download=点击这里下载
Shadowsocks is here=Shadowsocks 在这里
You can turn on/off Shadowsocks in the context menu=可以在右键菜单中开关 Shadowsocks
System Proxy Enabled=系统代理已启用
System Proxy Disabled=系统代理未启用
Update PAC from GFWList=从 GFWList 更新 PAC
Failed to update PAC file =更新 PAC 文件失败
PAC updated=更新 PAC 成功
No updates found. Please report to GFWList if you have problems with it.=未发现更新。如有问题请提交给 GFWList。
No QRCode found. Try to zoom in or move it to the center of the screen.=找不到二维码,尝试把它放大或者移动到靠近屏幕中间的位置
No QRCode found. Try to zoom in or move it to the center of the screen.=未发现二维码,尝试把它放大或移动到靠近屏幕中间的位置
Failed to decode QRCode=无法解析二维码
Failed to update registry=无法修改注册表
System Proxy On: =系统代理已启用:
+2
View File
@@ -0,0 +1,2 @@
! Put user rules line by line in this file.
! See https://adblockplus.org/en/filter-cheatsheet
+11 -2
View File
@@ -11,12 +11,17 @@ namespace Shadowsocks.Model
public class Configuration
{
public List<Server> configs;
// when strategy is set, index is ignored
public string strategy;
public int index;
public bool global;
public bool enabled;
public bool shareOverLan;
public bool isDefault;
public int localPort;
public string pacUrl;
public bool useOnlinePac;
private static string CONFIG_FILE = "gui-config.json";
@@ -77,9 +82,9 @@ namespace Shadowsocks.Model
{
config.index = config.configs.Count - 1;
}
if (config.index < 0)
if (config.index < -1)
{
config.index = 0;
config.index = -1;
}
config.isDefault = false;
try
@@ -116,6 +121,10 @@ namespace Shadowsocks.Model
{
throw new ArgumentException(I18N.GetString("Port out of range"));
}
if (port == 8123)
{
throw new ArgumentException(I18N.GetString("Port can't be 8123"));
}
}
private static void CheckPassword(string password)
+11
View File
@@ -18,6 +18,17 @@ namespace Shadowsocks.Model
public string method;
public string remarks;
public override int GetHashCode()
{
return server.GetHashCode() ^ server_port;
}
public override bool Equals(object obj)
{
Server o2 = (Server)obj;
return this.server == o2.server && this.server_port == o2.server_port;
}
public string FriendlyName()
{
if (string.IsNullOrEmpty(server))
+29 -23
View File
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -71,36 +71,30 @@ namespace Shadowsocks.Properties {
}
/// <summary>
/// Looks up a localized string similar to Shadowsocks=Shadowsocks
///Enable=启用代理
///Mode=代理模式
/// Looks up a localized string similar to # translation for Simplified Chinese
///
///Shadowsocks=Shadowsocks
///
///# Menu items
///
///Enable System Proxy=启用系统代理
///Mode=系统代理模式
///PAC=PAC 模式
///Global=全局模式
///Servers=服务器
///Edit Servers...=编辑服务器...
///Start on Boot=开机启动
///Share over LAN=在局域网共享代理
///Edit PAC File...=编辑 PAC 文件...
///Allow Clients from LAN=允许来自局域网的连接
///Local PAC=使用本地 PAC
///Online PAC=使用在线 PAC
///Edit Local PAC File...=编辑本地 PAC 文件...
///Update Local PAC from GFWList=从 GFWList 更新本地 PAC
///Edit User Rule for GFWList...=编辑 GFWList 的用户规则...
///Show QRCode...=显示二维码...
///Scan QRCode from Screen...=扫描屏幕上的二维码...
///Show Logs...=显示日志...
///About...=关于...
///Quit=退出
///Edit Servers=编辑服务器
///&amp;Add=添加(&amp;A)
///&amp;Delete=删除(&amp;D)
///Server=服务器
///Server IP=服务器 IP
///Server Port=服务器端口
///Password=密码
///Encryption=加密
///Proxy Port=代理端口
///Remarks=备注
///OK=确定
///Cancel=取消
///New server=未配置的服务器
///QRCode=二维码
///Shadowsocks Error: {0}=Shadowsocks [rest of string was truncated]&quot;;.
///Quit=退出 [rest of string was truncated]&quot;;.
/// </summary>
internal static string cn {
get {
@@ -119,7 +113,8 @@ namespace Shadowsocks.Properties {
}
/// <summary>
/// Looks up a localized string similar to proxyAddress = &quot;__POLIPO_BIND_IP__&quot;
/// Looks up a localized string similar to proxyAddress = &quot;__POLIPO_BIND_IP__&quot;
///proxyPort = 8123
///
///socksParentProxy = &quot;127.0.0.1:__SOCKS_PORT__&quot;
///socksProxyType = socks5
@@ -194,5 +189,16 @@ namespace Shadowsocks.Properties {
return ((System.Drawing.Bitmap)(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);
}
}
}
}
@@ -148,4 +148,7 @@
<data name="ssw128" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ssw128.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="user_rule" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\data\user-rule.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
</root>
+6 -2
View File
@@ -133,10 +133,14 @@ namespace Shadowsocks.View
private void LoadCurrentConfiguration()
{
_modifiedConfiguration = controller.GetConfiguration();
_modifiedConfiguration = controller.GetConfigurationCopy();
LoadConfiguration(_modifiedConfiguration);
_oldSelectedIndex = _modifiedConfiguration.index;
ServersListBox.SelectedIndex = _modifiedConfiguration.index;
if (_oldSelectedIndex < 0)
{
_oldSelectedIndex = 0;
}
ServersListBox.SelectedIndex = _oldSelectedIndex;
LoadSelectedServer();
}
+129 -19
View File
@@ -35,6 +35,12 @@ namespace Shadowsocks.View
private MenuItem ServersItem;
private MenuItem globalModeItem;
private MenuItem PACModeItem;
private MenuItem localPACItem;
private MenuItem onlinePACItem;
private MenuItem editLocalPACItem;
private MenuItem updateFromGFWListItem;
private MenuItem editGFWUserRuleItem;
private MenuItem editOnlinePACItem;
private ConfigForm configForm;
private string _urlToOpen;
@@ -46,7 +52,8 @@ namespace Shadowsocks.View
controller.EnableStatusChanged += controller_EnableStatusChanged;
controller.ConfigChanged += controller_ConfigChanged;
controller.PACFileReadyToOpen += controller_PACFileReadyToOpen;
controller.PACFileReadyToOpen += controller_FileReadyToOpen;
controller.UserRuleFileReadyToOpen += controller_FileReadyToOpen;
controller.ShareOverLANStatusChanged += controller_ShareOverLANStatusChanged;
controller.EnableGlobalChanged += controller_EnableGlobalChanged;
controller.Errored += controller_Errored;
@@ -64,9 +71,9 @@ namespace Shadowsocks.View
LoadCurrentConfiguration();
updateChecker.CheckUpdate(controller.GetConfiguration());
updateChecker.CheckUpdate(controller.GetConfigurationCopy());
if (controller.GetConfiguration().isDefault)
if (controller.GetConfigurationCopy().isDefault)
{
_isFirstRun = true;
ShowConfigForm();
@@ -99,7 +106,7 @@ namespace Shadowsocks.View
{
icon = Resources.ss24;
}
Configuration config = controller.GetConfiguration();
Configuration config = controller.GetConfigurationCopy();
bool enabled = config.enabled;
bool global = config.global;
if (!enabled)
@@ -117,12 +124,21 @@ namespace Shadowsocks.View
}
_notifyIcon.Icon = Icon.FromHandle(icon.GetHicon());
string serverInfo = null;
if (controller.GetCurrentStrategy() != null)
{
serverInfo = controller.GetCurrentStrategy().Name;
}
else
{
serverInfo = config.GetCurrentServer().FriendlyName();
}
// we want to show more details but notify icon title is limited to 63 characters
string text = I18N.GetString("Shadowsocks") + " " + UpdateChecker.Version + "\n" +
(enabled ?
I18N.GetString("System Proxy On: ") + (global ? I18N.GetString("Global") : I18N.GetString("PAC")) :
String.Format(I18N.GetString("Running: Port {0}"), config.localPort)) // this feedback is very important because they need to know Shadowsocks is running
+ "\n" + config.GetCurrentServer().FriendlyName();
+ "\n" + serverInfo;
_notifyIcon.Text = text.Substring(0, Math.Min(63, text.Length));
}
@@ -150,11 +166,18 @@ namespace Shadowsocks.View
CreateMenuItem("Show QRCode...", new EventHandler(this.QRCodeItem_Click)),
CreateMenuItem("Scan QRCode from Screen...", new EventHandler(this.ScanQRCodeItem_Click))
}),
CreateMenuGroup("PAC ", new MenuItem[] {
this.localPACItem = CreateMenuItem("Local PAC", new EventHandler(this.LocalPACItem_Click)),
this.onlinePACItem = CreateMenuItem("Online PAC", new EventHandler(this.OnlinePACItem_Click)),
new MenuItem("-"),
this.editLocalPACItem = CreateMenuItem("Edit Local PAC File...", new EventHandler(this.EditPACFileItem_Click)),
this.updateFromGFWListItem = CreateMenuItem("Update Local PAC from GFWList", new EventHandler(this.UpdatePACFromGFWListItem_Click)),
this.editGFWUserRuleItem = CreateMenuItem("Edit User Rule for GFWList...", new EventHandler(this.EditUserRuleFileForGFWListItem_Click)),
this.editOnlinePACItem = CreateMenuItem("Edit Online PAC URL...", new EventHandler(this.UpdateOnlinePACURLItem_Click)),
}),
new MenuItem("-"),
this.AutoStartupItem = CreateMenuItem("Start on Boot", new EventHandler(this.AutoStartupItem_Click)),
this.ShareOverLANItem = CreateMenuItem("Allow Clients from LAN", new EventHandler(this.ShareOverLANItem_Click)),
CreateMenuItem("Edit PAC File...", new EventHandler(this.EditPACFileItem_Click)),
CreateMenuItem("Update PAC from GFWList", new EventHandler(this.UpdatePACFromGFWListItem_Click)),
new MenuItem("-"),
CreateMenuItem("Show Logs...", new EventHandler(this.ShowLogItem_Click)),
CreateMenuItem("About...", new EventHandler(this.AboutItem_Click)),
@@ -171,22 +194,22 @@ namespace Shadowsocks.View
private void controller_EnableStatusChanged(object sender, EventArgs e)
{
enableItem.Checked = controller.GetConfiguration().enabled;
enableItem.Checked = controller.GetConfigurationCopy().enabled;
modeItem.Enabled = enableItem.Checked;
}
void controller_ShareOverLANStatusChanged(object sender, EventArgs e)
{
ShareOverLANItem.Checked = controller.GetConfiguration().shareOverLan;
ShareOverLANItem.Checked = controller.GetConfigurationCopy().shareOverLan;
}
void controller_EnableGlobalChanged(object sender, EventArgs e)
{
globalModeItem.Checked = controller.GetConfiguration().global;
globalModeItem.Checked = controller.GetConfigurationCopy().global;
PACModeItem.Checked = !globalModeItem.Checked;
}
void controller_PACFileReadyToOpen(object sender, ShadowsocksController.PathEventArgs e)
void controller_FileReadyToOpen(object sender, ShadowsocksController.PathEventArgs e)
{
string argument = @"/select, " + e.Path;
@@ -229,7 +252,7 @@ namespace Shadowsocks.View
private void LoadCurrentConfiguration()
{
Configuration config = controller.GetConfiguration();
Configuration config = controller.GetConfigurationCopy();
UpdateServersMenu();
enableItem.Checked = config.enabled;
modeItem.Enabled = config.enabled;
@@ -237,6 +260,9 @@ namespace Shadowsocks.View
PACModeItem.Checked = !config.global;
ShareOverLANItem.Checked = config.shareOverLan;
AutoStartupItem.Checked = AutoStartup.Check();
onlinePACItem.Checked = onlinePACItem.Enabled && config.useOnlinePac;
localPACItem.Checked = !onlinePACItem.Checked;
UpdatePACItemsEnabledStatus();
}
private void UpdateServersMenu()
@@ -246,20 +272,33 @@ namespace Shadowsocks.View
{
items.RemoveAt(0);
}
Configuration configuration = controller.GetConfiguration();
for (int i = 0; i < configuration.configs.Count; i++)
int i = 0;
foreach (var strategy in controller.GetStrategies())
{
MenuItem item = new MenuItem(strategy.Name);
item.Tag = strategy.ID;
item.Click += AStrategyItem_Click;
items.Add(i, item);
i++;
}
int strategyCount = i;
Configuration configuration = controller.GetConfigurationCopy();
foreach (var server in configuration.configs)
{
Server server = configuration.configs[i];
MenuItem item = new MenuItem(server.FriendlyName());
item.Tag = i;
item.Tag = i - strategyCount;
item.Click += AServerItem_Click;
items.Add(i, item);
i++;
}
if (configuration.index >= 0 && configuration.index < configuration.configs.Count)
foreach (MenuItem item in items)
{
items[configuration.index].Checked = true;
if (item.Tag != null && (item.Tag.ToString() == configuration.index.ToString() || item.Tag.ToString() == configuration.strategy))
{
item.Checked = true;
}
}
}
@@ -352,12 +391,23 @@ namespace Shadowsocks.View
controller.UpdatePACFromGFWList();
}
private void EditUserRuleFileForGFWListItem_Click(object sender, EventArgs e)
{
controller.TouchUserRuleFile();
}
private void AServerItem_Click(object sender, EventArgs e)
{
MenuItem item = (MenuItem)sender;
controller.SelectServerIndex((int)item.Tag);
}
private void AStrategyItem_Click(object sender, EventArgs e)
{
MenuItem item = (MenuItem)sender;
controller.SelectStrategy((string)item.Tag);
}
private void ShowLogItem_Click(object sender, EventArgs e)
{
string argument = Logging.LogFile;
@@ -473,5 +523,65 @@ namespace Shadowsocks.View
MessageBox.Show(I18N.GetString("Failed to update registry"));
}
}
private void LocalPACItem_Click(object sender, EventArgs e)
{
if (!localPACItem.Checked)
{
localPACItem.Checked = true;
onlinePACItem.Checked = false;
controller.UseOnlinePAC(false);
UpdatePACItemsEnabledStatus();
}
}
private void OnlinePACItem_Click(object sender, EventArgs e)
{
if (!onlinePACItem.Checked)
{
if (String.IsNullOrEmpty(controller.GetConfigurationCopy().pacUrl))
{
UpdateOnlinePACURLItem_Click(sender, e);
}
if (!String.IsNullOrEmpty(controller.GetConfigurationCopy().pacUrl))
{
localPACItem.Checked = false;
onlinePACItem.Checked = true;
controller.UseOnlinePAC(true);
}
UpdatePACItemsEnabledStatus();
}
}
private void UpdateOnlinePACURLItem_Click(object sender, EventArgs e)
{
string origPacUrl = controller.GetConfigurationCopy().pacUrl;
string pacUrl = Microsoft.VisualBasic.Interaction.InputBox(
I18N.GetString("Please input PAC Url"),
I18N.GetString("Edit Online PAC URL"),
origPacUrl, -1, -1);
if (!string.IsNullOrEmpty(pacUrl) && pacUrl != origPacUrl)
{
controller.SavePACUrl(pacUrl);
}
}
private void UpdatePACItemsEnabledStatus()
{
if (this.localPACItem.Checked)
{
this.editLocalPACItem.Enabled = true;
this.updateFromGFWListItem.Enabled = true;
this.editGFWUserRuleItem.Enabled = true;
this.editOnlinePACItem.Enabled = false;
}
else
{
this.editLocalPACItem.Enabled = false;
this.updateFromGFWListItem.Enabled = false;
this.editGFWUserRuleItem.Enabled = false;
this.editOnlinePACItem.Enabled = true;
}
}
}
}
+16 -9
View File
@@ -63,6 +63,7 @@
<ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualBasic" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
@@ -123,14 +124,16 @@
<Compile Include="3rd\zxing\ResultPoint.cs" />
<Compile Include="3rd\zxing\ResultPointCallback.cs" />
<Compile Include="3rd\zxing\WriterException.cs" />
<Compile Include="Controller\AutoStartup.cs" />
<Compile Include="Controller\Strategy\HighAvailabilityStrategy.cs" />
<Compile Include="Controller\System\AutoStartup.cs" />
<Compile Include="Controller\FileManager.cs" />
<Compile Include="Controller\GFWListUpdater.cs" />
<Compile Include="Controller\Service\GFWListUpdater.cs" />
<Compile Include="Controller\I18N.cs" />
<Compile Include="Controller\Listener.cs" />
<Compile Include="Controller\Service\Listener.cs" />
<Compile Include="Controller\Logging.cs" />
<Compile Include="Controller\PortForwarder.cs" />
<Compile Include="Controller\UpdateChecker.cs" />
<Compile Include="Controller\Service\PortForwarder.cs" />
<Compile Include="Controller\Service\UDPRelay.cs" />
<Compile Include="Controller\Service\UpdateChecker.cs" />
<Compile Include="Encryption\EncryptorBase.cs" />
<Compile Include="Encryption\EncryptorFactory.cs" />
<Compile Include="Encryption\IVEncryptor.cs" />
@@ -140,7 +143,7 @@
<Compile Include="Encryption\SodiumEncryptor.cs" />
<Compile Include="Encryption\TableEncryptor.cs" />
<Compile Include="Encryption\IEncryptor.cs" />
<Compile Include="Controller\PACServer.cs" />
<Compile Include="Controller\Service\PACServer.cs" />
<Compile Include="Model\Server.cs" />
<Compile Include="Model\Configuration.cs" />
<Compile Include="Properties\Resources.Designer.cs">
@@ -148,6 +151,9 @@
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Controller\Strategy\BalancingStrategy.cs" />
<Compile Include="Controller\Strategy\StrategyManager.cs" />
<Compile Include="Controller\Strategy\IStrategy.cs" />
<Compile Include="Util\Util.cs" />
<Compile Include="View\ConfigForm.cs">
<SubType>Form</SubType>
@@ -155,12 +161,12 @@
<Compile Include="View\ConfigForm.Designer.cs">
<DependentUpon>ConfigForm.cs</DependentUpon>
</Compile>
<Compile Include="Controller\Local.cs" />
<Compile Include="Controller\PolipoRunner.cs" />
<Compile Include="Controller\Service\TCPRelay.cs" />
<Compile Include="Controller\Service\PolipoRunner.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Controller\ShadowsocksController.cs" />
<Compile Include="Controller\SystemProxy.cs" />
<Compile Include="Controller\System\SystemProxy.cs" />
<Compile Include="View\MenuViewController.cs" />
<Compile Include="View\QRCodeForm.cs">
<SubType>Form</SubType>
@@ -198,6 +204,7 @@
<None Include="Resources\ss24.png" />
<None Include="Resources\ssw128.png" />
<Content Include="Data\cn.txt" />
<Content Include="Data\user-rule.txt" />
<Content Include="shadowsocks.ico" />
<None Include="Data\polipo_config.txt" />
</ItemGroup>