lint project

This commit is contained in:
clowwindy
2014-11-07 01:33:36 +08:00
parent aa105ccfe3
commit 1de2d001d7
18 changed files with 37 additions and 36 deletions
+386
View File
@@ -0,0 +1,386 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using shadowsocks_csharp.Encrypt;
namespace shadowsocks_csharp
{
class Local
{
private Config config;
//private Encryptor encryptor;
Socket listener;
public Local(Config config)
{
this.config = config;
//this.encryptor = new Encryptor(config.method, config.password);
}
public void Start()
{
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(0, config.local_port);
// Bind the socket to the local endpoint and listen for incoming connections.
listener.Bind(localEndPoint);
listener.Listen(100);
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Shadowsocks started");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
}
public void Stop()
{
listener.Close();
}
public void AcceptCallback(IAsyncResult ar)
{
try
{
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
//if (!listener.Connected)
//{
// return;
//}
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
Socket conn = listener.EndAccept(ar);
// Create the state object.
Handler handler = new Handler();
handler.connection = conn;
//if (encryptor.method == "table")
//{
// handler.encryptor = encryptor;
//}
//else
//{
// handler.encryptor = new Encryptor(config.method, config.password);
//}
handler.encryptor = EncryptorFactory.GetEncryptor(config.method, config.password);
handler.config = config;
handler.Start();
//handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
// new AsyncCallback(ReadCallback), state);
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
}
}
}
class Handler
{
//public Encryptor encryptor;
public IEncryptor encryptor;
public Config config;
// Client socket.
public Socket remote;
public Socket connection;
// Size of receive buffer.
public const int RecvSize = 16384;
public const int BufferSize = RecvSize + 32;
// remote receive buffer
public byte[] remoteRecvBuffer = new byte[RecvSize];
// remote send buffer
public byte[] remoteSendBuffer = new byte[BufferSize];
// connection receive buffer
public byte[] connetionRecvBuffer = new byte[RecvSize];
// connection send buffer
public byte[] connetionSendBuffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
private bool closed = false;
public void Start()
{
try
{
// TODO async resolving
IPAddress ipAddress;
bool parsed = IPAddress.TryParse(config.server, out ipAddress);
if (!parsed)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(config.server);
ipAddress = ipHostInfo.AddressList[0];
}
IPEndPoint remoteEP = new IPEndPoint(ipAddress, config.server_port);
remote = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
remote.BeginConnect(remoteEP,
new AsyncCallback(connectCallback), null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
public void Close()
{
if (closed)
{
return;
}
closed = true;
if (connection != null)
{
try
{
connection.Shutdown(SocketShutdown.Send);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
if (remote != null)
{
try
{
remote.Shutdown(SocketShutdown.Send);
}
catch (SocketException e)
{
Console.WriteLine(e.ToString());
}
}
((IDisposable)encryptor).Dispose();
}
private void connectCallback(IAsyncResult ar)
{
try
{
// Complete the connection.
remote.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
remote.RemoteEndPoint.ToString());
handshakeReceive();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
private void handshakeReceive()
{
try
{
connection.BeginReceive(connetionRecvBuffer, 0, 256, 0,
new AsyncCallback(handshakeReceiveCallback), null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
private void handshakeReceiveCallback(IAsyncResult ar)
{
try
{
int bytesRead = connection.EndReceive(ar);
if (bytesRead > 1)
{
byte[] response = { 5, 0 };
if (connetionRecvBuffer[0] != 5)
{
// reject socks 4
response = new byte[]{ 0, 91 };
}
connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(handshakeSendCallback), null);
}
else
{
this.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
private void handshakeSendCallback(IAsyncResult ar)
{
try
{
connection.EndSend(ar);
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
// Skip first 3 bytes
// TODO validate
connection.BeginReceive(connetionRecvBuffer, 0, 3, 0,
new AsyncCallback(handshakeReceive2Callback), null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
private void handshakeReceive2Callback(IAsyncResult ar)
{
try
{
int bytesRead = connection.EndReceive(ar);
if (bytesRead > 0)
{
byte[] response = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 };
connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(startPipe), null);
}
else
{
this.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
private void startPipe(IAsyncResult ar)
{
try
{
connection.EndReceive(ar);
remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0,
new AsyncCallback(pipeRemoteReceiveCallback), null);
connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
new AsyncCallback(pipeConnectionReceiveCallback), null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
private void pipeRemoteReceiveCallback(IAsyncResult ar)
{
try
{
int bytesRead = remote.EndReceive(ar);
if (bytesRead > 0)
{
int bytesToSend;
encryptor.Decrypt(remoteRecvBuffer, bytesRead, remoteSendBuffer, out bytesToSend);
connection.BeginSend(remoteSendBuffer, 0, bytesToSend, 0, new AsyncCallback(pipeConnectionSendCallback), null);
}
else
{
Console.WriteLine("bytesRead: " + bytesRead.ToString());
this.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
private void pipeConnectionReceiveCallback(IAsyncResult ar)
{
try
{
int bytesRead = connection.EndReceive(ar);
if (bytesRead > 0)
{
int bytesToSend;
encryptor.Encrypt(connetionRecvBuffer, bytesRead, connetionSendBuffer, out bytesToSend);
remote.BeginSend(connetionSendBuffer, 0, bytesToSend, 0, new AsyncCallback(pipeRemoteSendCallback), null);
}
else
{
Console.WriteLine("bytesRead: " + bytesRead.ToString());
this.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
private void pipeRemoteSendCallback(IAsyncResult ar)
{
try
{
remote.EndSend(ar);
connection.BeginReceive(this.connetionRecvBuffer, 0, RecvSize, 0,
new AsyncCallback(pipeConnectionReceiveCallback), null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
private void pipeConnectionSendCallback(IAsyncResult ar)
{
try
{
connection.EndSend(ar);
remote.BeginReceive(this.remoteRecvBuffer, 0, RecvSize, 0,
new AsyncCallback(pipeRemoteReceiveCallback), null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
}
}
+115
View File
@@ -0,0 +1,115 @@
using shadowsocks_csharp.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace shadowsocks_csharp
{
class PACServer
{
Socket listener;
public void Start()
{
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(0, 8090);
// Bind the socket to the local endpoint and listen for incoming connections.
listener.Bind(localEndPoint);
listener.Listen(100);
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
}
public void AcceptCallback(IAsyncResult ar)
{
try
{
Socket listener = (Socket)ar.AsyncState;
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
Socket conn = listener.EndAccept(ar);
conn.BeginReceive(new byte[1024], 0, 256, 0,
new AsyncCallback(receiveCallback), conn);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private string getPACContent()
{
// TODO try pac.txt in current directory
byte[] pacGZ = Resources.proxy_pac_txt;
byte[] buffer = new byte[1024 * 1024]; // builtin pac gzip size: maximum 1M
int n;
using (GZipStream input = new GZipStream(new MemoryStream(pacGZ),
CompressionMode.Decompress, false))
{
n = input.Read(buffer, 0, buffer.Length);
if (n == 0)
{
throw new IOException("can not decompress pac");
}
return System.Text.Encoding.UTF8.GetString(buffer, 0, n);
}
}
private void receiveCallback(IAsyncResult ar)
{
Socket conn = (Socket)ar.AsyncState;
try
{
int bytesRead = conn.EndReceive(ar);
string pac = getPACContent();
string proxy = "PROXY 127.0.0.1:8123; DIRECT;";
pac = pac.Replace("__PROXY__", proxy);
if (bytesRead > 0)
{
string text = String.Format(@"HTTP/1.1 200 OK
Server: Shadowsocks
Content-Type: application/x-ns-proxy-autoconfig
Content-Length: {0}
Connection: Close
", System.Text.Encoding.UTF8.GetBytes(pac).Length) + pac;
byte[] response = System.Text.Encoding.UTF8.GetBytes(text);
conn.BeginSend(response, 0, response.Length, 0, new AsyncCallback(sendCallback), conn);
}
else
{
conn.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
conn.Close();
}
}
private void sendCallback(IAsyncResult ar)
{
Socket conn = (Socket)ar.AsyncState;
conn.Shutdown(SocketShutdown.Send);
}
}
}
+105
View File
@@ -0,0 +1,105 @@
using shadowsocks_csharp.Properties;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace shadowsocks_csharp
{
class PolipoRunner
{
private Process process;
private bool ByteArrayToFile(string fileName, byte[] content)
{
try
{
System.IO.FileStream _FileStream =
new System.IO.FileStream(fileName, System.IO.FileMode.Create,
System.IO.FileAccess.Write);
_FileStream.Write(content, 0, content.Length);
_FileStream.Close();
return true;
}
catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}",
_Exception.ToString());
}
return false;
}
public static void UncompressFile(string fileName, byte[] content)
{
FileStream destinationFile = File.Create(fileName);
// Because the uncompressed size of the file is unknown,
// we are using an arbitrary buffer size.
byte[] buffer = new byte[4096];
int n;
using (GZipStream input = new GZipStream(new MemoryStream(content),
CompressionMode.Decompress, false))
{
while (true)
{
n = input.Read(buffer, 0, buffer.Length);
if (n == 0)
{
break;
}
destinationFile.Write(buffer, 0, n);
}
}
destinationFile.Close();
}
public void Start(Config config)
{
if (process == null)
{
Process[] existingPolipo = Process.GetProcessesByName("ss_polipo");
foreach (Process p in existingPolipo)
{
p.Kill();
p.WaitForExit();
}
string temppath = Path.GetTempPath();
string polipoConfig = Resources.polipo_config;
polipoConfig = polipoConfig.Replace("__SOCKS_PORT__", config.local_port.ToString());
ByteArrayToFile(temppath + "/polipo.conf", System.Text.Encoding.UTF8.GetBytes(polipoConfig));
UncompressFile(temppath + "/ss_polipo.exe", Resources.polipo_exe);
process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = temppath + "/ss_polipo.exe";
process.StartInfo.Arguments = "-c \"" + temppath + "/polipo.conf\"";
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
//process.StandardOutput
process.Start();
}
}
public void Stop()
{
if (process != null)
{
process.Kill();
try
{
process.WaitForExit();
}
catch (InvalidOperationException)
{
// do nothing
}
process = null;
}
}
}
}
+89
View File
@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace shadowsocks_csharp
{
public class ShadowsocksController
{
// controller:
// handle user actions
// manipulates UI
// interacts with low level logic
private Local local;
private PACServer pacServer;
private Config config;
private PolipoRunner polipoRunner;
private bool stopped = false;
public event EventHandler ConfigChanged;
public event EventHandler EnableStatusChanged;
public ShadowsocksController()
{
config = Config.Load();
polipoRunner = new PolipoRunner();
polipoRunner.Start(config);
local = new Local(config);
local.Start();
pacServer = new PACServer();
pacServer.Start();
updateSystemProxy();
}
public void SaveConfig(Config newConfig)
{
Config.Save(newConfig);
config = newConfig;
if (ConfigChanged != null)
{
ConfigChanged(this, new EventArgs());
}
}
public Config GetConfig()
{
return config;
}
public void ToggleEnable(bool enabled)
{
config.enabled = enabled;
updateSystemProxy();
SaveConfig(config);
if (EnableStatusChanged != null)
{
EnableStatusChanged(this, new EventArgs());
}
}
public void Stop()
{
if (stopped)
{
return;
}
stopped = true;
local.Stop();
polipoRunner.Stop();
if (config.enabled)
{
SystemProxy.Disable();
}
}
private void updateSystemProxy()
{
if (config.enabled)
{
SystemProxy.Enable();
}
else
{
SystemProxy.Disable();
}
}
}
}
+44
View File
@@ -0,0 +1,44 @@
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace shadowsocks_csharp
{
class SystemProxy
{
[DllImport("wininet.dll")]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
public const int INTERNET_OPTION_REFRESH = 37;
static bool settingsReturn, refreshReturn;
public static void NotifyIE()
{
// These lines implement the Interface in the beginning of program
// They cause the OS to refresh the settings, causing IP to realy update
settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
}
public static void Enable()
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 0);
registry.SetValue("ProxyServer", "");
registry.SetValue("AutoConfigURL", "http://127.0.0.1:8090/pac");
SystemProxy.NotifyIE();
}
public static void Disable()
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 0);
registry.SetValue("ProxyServer", "");
registry.SetValue("AutoConfigURL", "");
SystemProxy.NotifyIE();
}
}
}