Upgraded project

This commit is contained in:
Brandon Scott 2019-01-29 20:06:57 -06:00
parent caff2c3c25
commit c87a61b589
5 changed files with 224 additions and 217 deletions

View File

@ -1,213 +1,213 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using ProxyServerSharp.Interfaces;
namespace ProxyServerSharp.Implementation
{
class Socks4ProxyCore: IProxyCore
{
private readonly int _port;
private readonly int _transferUnitSize;
private Socket _serverSocket;
private Thread _acceptThread;
private List<ConnectionInfo> _connections =
new List<ConnectionInfo>();
public Socks4ProxyCore(int port, int transferUnitSize)
{
_port = port;
_transferUnitSize = transferUnitSize;
}
public event LocalConnectEventHandler LocalConnect;
public event LocalDisconnectEventHandler LocalDisconnect;
public event LocalSentEventHandler LocalSent;
public event LocalReceiveEventHandler LocalReceive;
public event RemoteConnectEventHandler RemoteConnect;
public event RemoteDisconnectEventHandler RemoteDisconnect;
public event RemoteSendEventHandler RemoteSend;
public event RemoteReceivedEventHandler RemoteReceive;
public void Start()
{
SetupServerSocket();
_acceptThread = new Thread(AcceptConnections);
_acceptThread.IsBackground = true;
_acceptThread.Start();
}
public void Shutdown()
{
throw new NotImplementedException();
}
private void SetupServerSocket()
{
IPEndPoint myEndpoint = new IPEndPoint(IPAddress.Loopback,
_port);
// Create the socket, bind it, and start listening
_serverSocket = new Socket(myEndpoint.Address.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Bind(myEndpoint);
_serverSocket.Listen((int)SocketOptionName.MaxConnections);
}
private void AcceptConnections()
{
while (true)
{
// Accept a connection
ConnectionInfo connection = new ConnectionInfo();
Socket socket = _serverSocket.Accept();
connection.LocalSocket = socket;
connection.RemoteSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Create the thread for the receives.
connection.LocalThread = new Thread(ProcessLocalConnection);
connection.LocalThread.IsBackground = true;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using ProxyServerSharp.Interfaces;
namespace ProxyServerSharp.Implementation
{
class Socks4ProxyCore: IProxyCore
{
private readonly int _port;
private readonly int _transferUnitSize;
private Socket _serverSocket;
private Thread _acceptThread;
private List<ConnectionInfo> _connections =
new List<ConnectionInfo>();
public Socks4ProxyCore(int port, int transferUnitSize)
{
_port = port;
_transferUnitSize = transferUnitSize;
}
public event LocalConnectEventHandler LocalConnect;
public event LocalDisconnectEventHandler LocalDisconnect;
public event LocalSentEventHandler LocalSent;
public event LocalReceiveEventHandler LocalReceive;
public event RemoteConnectEventHandler RemoteConnect;
public event RemoteDisconnectEventHandler RemoteDisconnect;
public event RemoteSendEventHandler RemoteSend;
public event RemoteReceivedEventHandler RemoteReceive;
public void Start()
{
SetupServerSocket();
_acceptThread = new Thread(AcceptConnections);
_acceptThread.IsBackground = true;
_acceptThread.Start();
}
public void Shutdown()
{
throw new NotImplementedException();
}
private void SetupServerSocket()
{
IPEndPoint myEndpoint = new IPEndPoint(IPAddress.Loopback,
_port);
// Create the socket, bind it, and start listening
_serverSocket = new Socket(myEndpoint.Address.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Bind(myEndpoint);
_serverSocket.Listen((int)SocketOptionName.MaxConnections);
}
private void AcceptConnections()
{
while (true)
{
// Accept a connection
ConnectionInfo connection = new ConnectionInfo();
Socket socket = _serverSocket.Accept();
connection.LocalSocket = socket;
connection.RemoteSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Create the thread for the receives.
connection.LocalThread = new Thread(ProcessLocalConnection);
connection.LocalThread.IsBackground = true;
connection.LocalThread.Start(connection);
LocalConnect?.Invoke(this, (IPEndPoint)socket.RemoteEndPoint);
// Store the socket
lock (_connections) _connections.Add(connection);
}
}
private void ProcessLocalConnection(object state)
{
ConnectionInfo connection = (ConnectionInfo)state;
int bytesRead = 0;
byte[] buffer = new byte[_transferUnitSize];
try
{
// we are setting up the socks!
bytesRead = connection.LocalSocket.Receive(buffer);
Console.WriteLine("ProcessLocalConnection::Receive bytesRead={0}", bytesRead);
for (int i = 0; i < bytesRead; i++)
Console.Write("{0:X2} ", buffer[i]);
Console.Write("\n");
if (bytesRead > 0)
{
if (buffer[0] == 0x04 && buffer[1] == 0x01)
{
int remotePort = buffer[2] << 8 | buffer[3];
byte[] ipAddressBuffer = new byte[4];
Buffer.BlockCopy(buffer, 4, ipAddressBuffer, 0, 4);
IPEndPoint remoteEndPoint = new IPEndPoint(new IPAddress(ipAddressBuffer), remotePort);
connection.RemoteSocket.Connect(remoteEndPoint);
if (connection.RemoteSocket.Connected)
{
Console.WriteLine("Connected to remote!");
RemoteConnect?.Invoke(this, remoteEndPoint);
byte[] socksResponse = new byte[] {
0x00, 0x5a,
buffer[2], buffer[3], // port
buffer[4], buffer[5], buffer[6], buffer[7] // IP
};
connection.LocalSocket.Send(socksResponse);
// Create the thread for the receives.
connection.RemoteThread = new Thread(ProcessRemoteConnection);
connection.RemoteThread.IsBackground = true;
connection.RemoteThread.Start(connection);
}
else
{
Console.WriteLine("Connection failed.");
byte[] socksResponse = new byte[] {
0x04,
0x5b,
buffer[2], buffer[3], // port
buffer[4], buffer[5], buffer[6], buffer[7] // IP
};
connection.LocalSocket.Send(socksResponse);
return;
}
}
}
else if (bytesRead == 0) return;
// start receiving actual data
while (true)
{
bytesRead = connection.LocalSocket.Receive(buffer);
if (bytesRead == 0) {
Console.WriteLine("Local connection closed!");
break;
} else {
connection.RemoteSocket.Send(buffer, bytesRead, SocketFlags.None);
}
}
}
catch (Exception exc)
{
Console.WriteLine("Exception: " + exc);
}
finally
{
Console.WriteLine("ProcessLocalConnection Cleaning up...");
connection.LocalSocket.Close();
connection.RemoteSocket.Close();
lock (_connections) _connections.Remove(connection);
}
}
private void ProcessRemoteConnection(object state)
{
ConnectionInfo connection = (ConnectionInfo)state;
int bytesRead = 0;
byte[] buffer = new byte[_transferUnitSize];
try
{
// start receiving actual data
while (true)
{
bytesRead = connection.RemoteSocket.Receive(buffer);
if (bytesRead == 0) {
Console.WriteLine("Remote connection closed!");
break;
} else {
connection.LocalSocket.Send(buffer, bytesRead, SocketFlags.None);
}
}
}
catch (SocketException exc)
{
Console.WriteLine("Socket exception: " + exc.SocketErrorCode);
}
catch (Exception exc)
{
Console.WriteLine("Exception: " + exc);
}
finally
{
Console.WriteLine("ProcessRemoteConnection Cleaning up...");
connection.LocalSocket.Close();
connection.RemoteSocket.Close();
lock (_connections)
_connections.Remove(connection);
}
}
}
}
LocalConnect?.Invoke(this, (IPEndPoint)socket.RemoteEndPoint);
// Store the socket
lock (_connections) _connections.Add(connection);
}
}
private void ProcessLocalConnection(object state)
{
ConnectionInfo connection = (ConnectionInfo)state;
int bytesRead = 0;
byte[] buffer = new byte[_transferUnitSize];
try
{
// we are setting up the socks!
bytesRead = connection.LocalSocket.Receive(buffer);
Console.WriteLine("ProcessLocalConnection::Receive bytesRead={0}", bytesRead);
for (int i = 0; i < bytesRead; i++)
Console.Write("{0:X2} ", buffer[i]);
Console.Write("\n");
if (bytesRead > 0)
{
if (buffer[0] == 0x04 && buffer[1] == 0x01)
{
int remotePort = buffer[2] << 8 | buffer[3];
byte[] ipAddressBuffer = new byte[4];
Buffer.BlockCopy(buffer, 4, ipAddressBuffer, 0, 4);
IPEndPoint remoteEndPoint = new IPEndPoint(new IPAddress(ipAddressBuffer), remotePort);
connection.RemoteSocket.Connect(remoteEndPoint);
if (connection.RemoteSocket.Connected)
{
Console.WriteLine("Connected to remote!");
RemoteConnect?.Invoke(this, remoteEndPoint);
byte[] socksResponse = new byte[] {
0x00, 0x5a,
buffer[2], buffer[3], // port
buffer[4], buffer[5], buffer[6], buffer[7] // IP
};
connection.LocalSocket.Send(socksResponse);
// Create the thread for the receives.
connection.RemoteThread = new Thread(ProcessRemoteConnection);
connection.RemoteThread.IsBackground = true;
connection.RemoteThread.Start(connection);
}
else
{
Console.WriteLine("Connection failed.");
byte[] socksResponse = new byte[] {
0x04,
0x5b,
buffer[2], buffer[3], // port
buffer[4], buffer[5], buffer[6], buffer[7] // IP
};
connection.LocalSocket.Send(socksResponse);
return;
}
}
}
else if (bytesRead == 0) return;
// start receiving actual data
while (true)
{
bytesRead = connection.LocalSocket.Receive(buffer);
if (bytesRead == 0) {
Console.WriteLine("Local connection closed!");
break;
} else {
connection.RemoteSocket.Send(buffer, bytesRead, SocketFlags.None);
}
}
}
catch (Exception exc)
{
Console.WriteLine("Exception: " + exc);
}
finally
{
Console.WriteLine("ProcessLocalConnection Cleaning up...");
connection.LocalSocket.Close();
connection.RemoteSocket.Close();
lock (_connections) _connections.Remove(connection);
}
}
private void ProcessRemoteConnection(object state)
{
ConnectionInfo connection = (ConnectionInfo)state;
int bytesRead = 0;
byte[] buffer = new byte[_transferUnitSize];
try
{
// start receiving actual data
while (true)
{
bytesRead = connection.RemoteSocket.Receive(buffer);
if (bytesRead == 0) {
Console.WriteLine("Remote connection closed!");
break;
} else {
connection.LocalSocket.Send(buffer, bytesRead, SocketFlags.None);
}
}
}
catch (SocketException exc)
{
Console.WriteLine("Socket exception: " + exc.SocketErrorCode);
}
catch (Exception exc)
{
Console.WriteLine("Exception: " + exc);
}
finally
{
Console.WriteLine("ProcessRemoteConnection Cleaning up...");
connection.LocalSocket.Close();
connection.RemoteSocket.Close();
lock (_connections)
_connections.Remove(connection);
}
}
}
}

View File

@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@ -19,7 +19,7 @@ namespace ProxyServerSharp.Properties {
// 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", "4.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {

View File

@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@ -12,7 +12,7 @@ namespace ProxyServerSharp.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.8.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
@ -10,13 +10,14 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ProxyServerSharp</RootNamespace>
<AssemblyName>ProxyServerSharp</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>3.5</OldToolsVersion>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -26,6 +27,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@ -34,6 +36,7 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
@ -67,6 +70,7 @@
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="app.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>

View File

@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1"/></startup></configuration>