Skip to content

Commit

Permalink
Merge commit 'a1993b0cc9073aa7968605dc83ef052b5cab4039' into PR-82
Browse files Browse the repository at this point in the history
# Conflicts:
#	shadowsocks-csharp/View/SettingsForm.Designer.cs
  • Loading branch information
Akkariiin committed Apr 19, 2019
2 parents 105d7cf + a1993b0 commit 5b5b39c
Show file tree
Hide file tree
Showing 18 changed files with 938 additions and 89 deletions.
7 changes: 5 additions & 2 deletions shadowsocks-csharp/Controller/Listener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,11 @@ public void AcceptCallback(IAsyncResult ar)
conn.Close();
}

if ((_authUser ?? "").Length == 0 && !Util.Utils.isLAN(conn))
int local_port = ((IPEndPoint)conn.LocalEndPoint).Port;

if ((_authUser ?? "").Length == 0 && !Util.Utils.isLAN(conn)
&& !(_config.GetPortMapCache().ContainsKey(local_port)
|| _config.GetPortMapCache()[local_port].type == PortMapType.Forward))
{
conn.Shutdown(SocketShutdown.Both);
conn.Close();
Expand All @@ -273,7 +277,6 @@ public void AcceptCallback(IAsyncResult ar)
buf
};

int local_port = ((IPEndPoint)conn.LocalEndPoint).Port;
if (!_config.GetPortMapCache().ContainsKey(local_port) || _config.GetPortMapCache()[local_port].type != PortMapType.Forward)
{
conn.BeginReceive(buf, 0, buf.Length, 0,
Expand Down
85 changes: 67 additions & 18 deletions shadowsocks-csharp/Controller/Local.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,15 @@ public bool Handle(byte[] firstPacket, int length, Socket socket)
}
}

class HandlerConfig
class HandlerConfig : ICloneable
{
public string targetHost;
public int targetPort;

public Double TTL = 0; // Second
public Double connect_timeout = 0;
public int try_keep_alive = 0;
public string local_dns_servers;
public string dns_servers;
public bool fouce_local_dns_query = false;
// Server proxy
Expand All @@ -127,6 +128,31 @@ class HandlerConfig
public int reconnectTimes = 0;
public bool random = false;
public bool forceRandom = false;

public object Clone()
{
HandlerConfig obj = new HandlerConfig();
obj.targetHost = targetHost;
obj.targetPort = targetPort;
obj.TTL = TTL;
obj.connect_timeout = connect_timeout;
obj.try_keep_alive = try_keep_alive;
obj.local_dns_servers = local_dns_servers;
obj.dns_servers = dns_servers;
obj.fouce_local_dns_query = fouce_local_dns_query;
obj.proxyType = proxyType;
obj.socks5RemoteHost = socks5RemoteHost;
obj.socks5RemotePort = socks5RemotePort;
obj.socks5RemoteUsername = socks5RemoteUsername;
obj.socks5RemotePassword = socks5RemotePassword;
obj.proxyUserAgent = proxyUserAgent;
obj.autoSwitchOff = autoSwitchOff;
obj.reconnectTimesRemain = reconnectTimesRemain;
obj.reconnectTimes = reconnectTimes;
obj.random = random;
obj.forceRandom = forceRandom;
return obj;
}
}

class Handler
Expand Down Expand Up @@ -230,7 +256,7 @@ private void ResetTimeout(double time, bool reset_keep_alive = true)
}
}
}
else
else if (!closed)
{
if (lastTimerSetTime != null && (DateTime.Now - lastTimerSetTime).TotalMilliseconds > 500)
{
Expand Down Expand Up @@ -459,7 +485,7 @@ public bool ReConnect()
handler.select_server = select_server;
handler.connection = connection;
handler.connectionUDP = connectionUDP;
handler.cfg = cfg;
handler.cfg = cfg.Clone() as HandlerConfig;
handler.cfg.reconnectTimesRemain = cfg.reconnectTimesRemain - 1;
handler.cfg.reconnectTimes = cfg.reconnectTimes + 1;

Expand Down Expand Up @@ -505,7 +531,15 @@ public void Start(byte[] firstPacket, int length, string rsp_protocol)
connectionSendBufferList.Add(data);
remoteHeaderSendBuffer = data;

Connect();
if (cfg.reconnectTimes > 0)
{
InvokeHandler handler = () => Connect();
handler.BeginInvoke(null, null);
}
else
{
Connect();
}
}
else
{
Expand Down Expand Up @@ -745,8 +779,6 @@ public void Close()
}
this.State = ConnectState.END;
}
getCurrentServer = null;
keepCurrentServer = null;
}

if (!reconnect)
Expand All @@ -761,19 +793,24 @@ public void Close()
connection = null;
connectionUDP = null;
}

detector = null;
speedTester = null;
random = null;
remoteUDPRecvBuffer = null;

server = null;
select_server = null;
}
catch (Exception e)
{
Logging.LogUsefulException(e);
}

getCurrentServer = null;
keepCurrentServer = null;

detector = null;
speedTester = null;
random = null;
remoteUDPRecvBuffer = null;

server = null;
select_server = null;

cfg = null;
}

private bool ConnectProxyServer(string strRemoteHost, int iRemotePort)
Expand Down Expand Up @@ -835,10 +872,10 @@ private void Connect()
}
}
speedTester.server = server.server;
Logging.Info($"Connect {cfg.targetHost}:{cfg.targetPort.ToString()}");
Logging.Info($"Connect {cfg.targetHost}:{cfg.targetPort.ToString()} via {server.server}:{server.server_port}");

ResetTimeout(cfg.TTL);
if (cfg.fouce_local_dns_query && cfg.targetHost != null)
if (cfg.targetHost != null)
{
IPAddress ipAddress;

Expand All @@ -858,6 +895,7 @@ private void Connect()
ipAddress = Utils.QueryDns(host, null);
}
}
Logging.Info($"DNS nolock query {host} answer {ipAddress.ToString()}");
if (ipAddress != null)
{
Utils.DnsBuffer.Set(host, new IPAddress(ipAddress.GetAddressBytes()));
Expand Down Expand Up @@ -899,18 +937,20 @@ private void Connect()
bool parsed = IPAddress.TryParse(serverHost, out ipAddress);
if (!parsed)
{
if (server.ServerSpeedLog().ErrorContinurousTimes > 10)
server.DnsBuffer().force_expired = true;
if (server.DnsBuffer().isExpired(serverHost))
{
bool dns_ok = false;
{
DnsBuffer buf = server.DnsBuffer();
lock (buf)
if (Monitor.TryEnter(buf, buf.ip != null ? 100 : 1000000))
{
if (buf.isExpired(serverHost))
{
if (serverHost.IndexOf('.') >= 0)
{
ipAddress = Util.Utils.QueryDns(serverHost, cfg.dns_servers);
ipAddress = Util.Utils.QueryDns(serverHost, cfg.local_dns_servers);
}
else
{
Expand All @@ -927,6 +967,15 @@ private void Connect()
ipAddress = buf.ip;
dns_ok = true;
}
Monitor.Exit(buf);
}
else
{
if (buf.ip != null)
{
ipAddress = buf.ip;
dns_ok = true;
}
}
}
if (!dns_ok)
Expand Down
4 changes: 4 additions & 0 deletions shadowsocks-csharp/Controller/ProxyAuth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,10 @@ private void Connect()
handler.cfg.TTL = _config.TTL;
handler.cfg.connect_timeout = _config.connectTimeout;
handler.cfg.autoSwitchOff = _config.autoBan;
if (!string.IsNullOrEmpty(_config.localDnsServer))
{
handler.cfg.local_dns_servers = _config.localDnsServer;
}
if (!string.IsNullOrEmpty(_config.dnsServer))
{
handler.cfg.dns_servers = _config.dnsServer;
Expand Down
8 changes: 4 additions & 4 deletions shadowsocks-csharp/Controller/Socks5Forwarder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -302,14 +302,14 @@ private void Connect()
}
if (ipAddress == null)
{
ipAddress = Utils.DnsBuffer.Get(_remote_host);
ipAddress = Utils.LocalDnsBuffer.Get(_remote_host);
}
}
if (ipAddress == null)
{
if (_remote_host.IndexOf('.') >= 0)
{
ipAddress = Util.Utils.QueryDns(_remote_host, _config.dnsServer);
ipAddress = Util.Utils.QueryDns(_remote_host, _config.localDnsServer);
}
else
{
Expand All @@ -318,8 +318,8 @@ private void Connect()
}
if (ipAddress != null)
{
Utils.DnsBuffer.Set(_remote_host, new IPAddress(ipAddress.GetAddressBytes()));
Utils.DnsBuffer.Sweep();
Utils.LocalDnsBuffer.Set(_remote_host, new IPAddress(ipAddress.GetAddressBytes()));
Utils.LocalDnsBuffer.Sweep();
}
else
{
Expand Down
53 changes: 16 additions & 37 deletions shadowsocks-csharp/Model/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ public class Configuration
public int localPort;
public string localAuthPassword;

public string localDnsServer;
public string dnsServer;
public int reconnectTimes;
public string balanceAlgorithm;
Expand Down Expand Up @@ -147,9 +148,8 @@ public class Configuration
public Dictionary<string, PortMapConfig> portMap = new Dictionary<string, PortMapConfig>();

private Dictionary<int, ServerSelectStrategy> serverStrategyMap = new Dictionary<int, ServerSelectStrategy>();
private Dictionary<string, UriVisitTime> uri2time = new Dictionary<string, UriVisitTime>();
private SortedDictionary<UriVisitTime, string> time2uri = new SortedDictionary<UriVisitTime, string>();
private Dictionary<int, PortMapConfigCache> portMapCache = new Dictionary<int, PortMapConfigCache>();
private LRUCache<string, UriVisitTime> uricache = new LRUCache<string, UriVisitTime>(180);

private static string CONFIG_FILE = "gui-config.json";

Expand All @@ -175,9 +175,9 @@ public bool KeepCurrentServer(int localPort, string targetAddr, string id)
serverStrategyMap[localPort] = new ServerSelectStrategy();
ServerSelectStrategy serverStrategy = serverStrategyMap[localPort];

if (uri2time.ContainsKey(targetAddr))
if (uricache.ContainsKey(targetAddr))
{
UriVisitTime visit = uri2time[targetAddr];
UriVisitTime visit = uricache.Get(targetAddr);
int index = -1;
for (int i = 0; i < configs.Count; ++i)
{
Expand All @@ -189,11 +189,7 @@ public bool KeepCurrentServer(int localPort, string targetAddr, string id)
}
if (index >= 0 && visit.index == index && configs[index].enable)
{
time2uri.Remove(visit);
visit.index = index;
visit.visitTime = DateTime.Now;
uri2time[targetAddr] = visit;
time2uri[visit] = targetAddr;
uricache.Del(targetAddr);
return true;
}
}
Expand All @@ -210,25 +206,14 @@ public Server GetCurrentServer(int localPort, ServerSelectStrategy.FilterFunc fi
serverStrategyMap[localPort] = new ServerSelectStrategy();
ServerSelectStrategy serverStrategy = serverStrategyMap[localPort];

foreach (KeyValuePair<UriVisitTime, string> p in time2uri)
uricache.SetTimeout(keepVisitTime);
uricache.Sweep();
if (sameHostForSameTarget && !forceRandom && targetAddr != null && uricache.ContainsKey(targetAddr))
{
if ((DateTime.Now - p.Key.visitTime).TotalSeconds < keepVisitTime)
break;

uri2time.Remove(p.Value);
time2uri.Remove(p.Key);
break;
}
if (sameHostForSameTarget && !forceRandom && targetAddr != null && uri2time.ContainsKey(targetAddr))
{
UriVisitTime visit = uri2time[targetAddr];
UriVisitTime visit = uricache.Get(targetAddr);
if (visit.index < configs.Count && configs[visit.index].enable && configs[visit.index].ServerSpeedLog().ErrorContinurousTimes == 0)
{
//uri2time.Remove(targetURI);
time2uri.Remove(visit);
visit.visitTime = DateTime.Now;
uri2time[targetAddr] = visit;
time2uri[visit] = targetAddr;
uricache.Del(targetAddr);
return configs[visit.index];
}
}
Expand Down Expand Up @@ -274,12 +259,7 @@ public Server GetCurrentServer(int localPort, ServerSelectStrategy.FilterFunc fi
visit.uri = targetAddr;
visit.index = index;
visit.visitTime = DateTime.Now;
if (uri2time.ContainsKey(targetAddr))
{
time2uri.Remove(uri2time[targetAddr]);
}
uri2time[targetAddr] = visit;
time2uri[visit] = targetAddr;
uricache.Set(targetAddr, visit);
}
return configs[index];
}
Expand Down Expand Up @@ -309,12 +289,7 @@ public Server GetCurrentServer(int localPort, ServerSelectStrategy.FilterFunc fi
visit.uri = targetAddr;
visit.index = selIndex;
visit.visitTime = DateTime.Now;
if (uri2time.ContainsKey(targetAddr))
{
time2uri.Remove(uri2time[targetAddr]);
}
uri2time[targetAddr] = visit;
time2uri[visit] = targetAddr;
uricache.Set(targetAddr, visit);
}
return configs[selIndex];
}
Expand Down Expand Up @@ -381,6 +356,8 @@ public void FlushPortMapCache()
if (!portMapCache.ContainsKey(localPort))
serverStrategyMap.Remove(localPort);
}

uricache.Clear();
}

public Dictionary<int, PortMapConfigCache> GetPortMapCache()
Expand Down Expand Up @@ -414,6 +391,7 @@ public Configuration()
keepVisitTime = 180;
connectTimeout = 5;
dnsServer = "";
localDnsServer = "";

balanceAlgorithm = "LowException";
random = true;
Expand Down Expand Up @@ -446,6 +424,7 @@ public void CopyFrom(Configuration config)
TTL = config.TTL;
connectTimeout = config.connectTimeout;
dnsServer = config.dnsServer;
localDnsServer = config.localDnsServer;
proxyEnable = config.proxyEnable;
pacDirectGoProxy = config.pacDirectGoProxy;
proxyType = config.proxyType;
Expand Down
10 changes: 10 additions & 0 deletions shadowsocks-csharp/Model/LRUCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ public void SetTimeout(int time)
_sweep_time = time;
}

public void Clear()
{
lock (_lock)
{
_store.Clear();
_key_2_time.Clear();
_time_2_key.Clear();
}
}

public bool isTimeout(K key)
{
lock (_lock)
Expand Down
Loading

0 comments on commit 5b5b39c

Please sign in to comment.