Commit ef2dbb18 authored by justcoding121's avatar justcoding121 Committed by justcoding121

Merge pull request #9 from titanium007/breaking-change

Use Async for each session
parents 2c8fdcf8 1a83e59b
......@@ -33,8 +33,9 @@ namespace Titanium.Web.Proxy.Models
internal Stream ClientStream { get; set; }
internal Stream ServerResponseStream { get; set; }
internal Encoding Encoding { get; set; }
internal bool WasModified { get; set; }
internal System.Threading.ManualResetEvent FinishedRequestEvent { get; set; }
internal bool RequestWasModified { get; set; }
internal bool ResponseWasModified { get; set; }
internal string UpgradeProtocol { get; set; }
......@@ -64,11 +65,13 @@ namespace Titanium.Web.Proxy.Models
mw.Close();
RequestHtmlBody = Encoding.Default.GetString(mw.ToArray());
}
RequestWasModified = true;
return RequestHtmlBody;
}
public void SetRequestHtmlBody(string Body)
{
this.RequestHtmlBody = Body;
RequestWasModified = true;
}
public string GetResponseHtmlBody()
{
......@@ -97,7 +100,7 @@ namespace Titanium.Web.Proxy.Models
break;
}
ResponseHtmlBody = ResponseData;
WasModified = true;
ResponseWasModified = true;
}
return ResponseHtmlBody;
......@@ -153,7 +156,13 @@ namespace Titanium.Web.Proxy.Models
public System.Net.Sockets.TcpClient Client { get; set; }
public string tunnelHostName { get; set; }
public string securehost { get; set; }
}
}
\ No newline at end of file
......@@ -33,7 +33,7 @@ namespace Titanium.Web.Proxy
private static object certificateAccessLock = new object();
private static List<string> pinnedCertificateClients = new List<string>();
private static ManualResetEvent tcpClientConnected = new ManualResetEvent(false);
private static TcpListener listener;
private static Thread listenerThread;
......@@ -46,6 +46,8 @@ namespace Titanium.Web.Proxy
public static IPAddress ListeningIPInterface { get; set; }
public static string RootCertificateName { get; set; }
public static bool EnableSSL { get; set; }
public static bool SetAsSystemProxy { get; set; }
public static Int32 ListeningPort
{
......@@ -141,65 +143,24 @@ namespace Titanium.Web.Proxy
{
while (ShouldListen)
{
// Set the event to nonsignaled state.
tcpClientConnected.Reset();
listener.BeginAcceptTcpClient(new AsyncCallback(AcceptTcpClientCallback), listener);
// Wait until a connection is made and processed before
// continuing.
tcpClientConnected.WaitOne();
var client = listener.AcceptTcpClient();
Task.Factory.StartNew(() => HandleClient(client));
}
}
catch (ThreadInterruptedException) { }
catch (SocketException ex)
catch (SocketException)
{
Debug.WriteLine(ex.Message);
}
}
public static void AcceptTcpClientCallback(IAsyncResult ar)
{
try
{
// Get the listener that handles the client request.
TcpListener listener = (TcpListener)ar.AsyncState;
TcpClient client = null;
// End the operation and display the received data on
// the console.
client = listener.EndAcceptTcpClient(ar);
Task.Factory.StartNew(() => ProcessClient(client));
// Signal the calling thread to continue.
tcpClientConnected.Set();
}
catch(ObjectDisposedException) { }
}
private static void ProcessClient(Object param)
{
try
{
TcpClient client = param as TcpClient;
HandleClientRequest(client);
client.Close();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
public static bool EnableSSL { get; set; }
public static bool SetAsSystemProxy { get; set; }
}
}
\ No newline at end of file
......@@ -13,6 +13,7 @@ using System.Security.Cryptography.X509Certificates;
using System.Reflection;
using Titanium.Web.Proxy.Helpers;
using Titanium.Web.Proxy.Models;
using System.Threading.Tasks;
namespace Titanium.Web.Proxy
......@@ -21,7 +22,7 @@ namespace Titanium.Web.Proxy
partial class ProxyServer
{
private static void HandleClientRequest(TcpClient Client)
private static void HandleClient(TcpClient Client)
{
string connectionGroup = null;
......@@ -120,7 +121,7 @@ namespace Titanium.Web.Proxy
return;
}
Monitor.Enter(certificateAccessLock);
var _certificate = ProxyServer.CertManager.CreateCertificate(tunnelHostName); //CertificateHelper.GetCertificate(RootCertificateName, tunnelHostName);
var _certificate = ProxyServer.CertManager.CreateCertificate(tunnelHostName);
Monitor.Exit(certificateAccessLock);
SslStream sslStream = null;
......@@ -173,223 +174,202 @@ namespace Titanium.Web.Proxy
securehost = remoteUri;
}
int count = 0;
HandleHttpSessionRequest(Client, httpCmd, connectionGroup, clientStream, tunnelHostName, requestLines, clientStreamReader, securehost);
SessionEventArgs args = new SessionEventArgs(BUFFER_SIZE);
while (!String.IsNullOrEmpty(httpCmd))
{
count++;
}
catch (AuthenticationException)
{
return;
}
catch (EndOfStreamException)
{
return;
}
catch (IOException)
{
return;
}
catch (UriFormatException)
{
return;
}
catch (WebException)
{
return;
}
finally
{
MemoryStream mw = null;
StreamWriter sw = null;
args = new SessionEventArgs(BUFFER_SIZE);
try
{
splitBuffer = httpCmd.Split(spaceSplit, 3);
}
if (splitBuffer.Length != 3)
{
TcpHelper.SendRaw(httpCmd, tunnelHostName, ref requestLines, args.IsSSLRequest, clientStreamReader.BaseStream);
if (clientStream != null)
clientStream.Close();
}
private static void HandleHttpSessionRequest(TcpClient Client, string httpCmd, string connectionGroup, Stream clientStream, string tunnelHostName, List<string> requestLines, CustomBinaryReader clientStreamReader, string securehost)
{
return;
}
method = splitBuffer[0];
remoteUri = splitBuffer[1];
if (splitBuffer[2] == "HTTP/1.1")
{
version = new Version(1, 1);
}
else
{
version = new Version(1, 0);
}
if (httpCmd == null) return;
if (securehost != null)
{
remoteUri = securehost + remoteUri;
args.IsSSLRequest = true;
}
//construct the web request that we are going to issue on behalf of the client.
args.ProxyRequest = (HttpWebRequest)HttpWebRequest.Create(remoteUri.Trim());
args.ProxyRequest.Proxy = null;
args.ProxyRequest.UseDefaultCredentials = true;
args.ProxyRequest.Method = method;
args.ProxyRequest.ProtocolVersion = version;
args.ClientStream = clientStream;
args.ClientStreamReader = clientStreamReader;
var args = new SessionEventArgs(BUFFER_SIZE);
args.Client = Client;
args.tunnelHostName = tunnelHostName;
args.securehost = securehost;
try
{
var splitBuffer = httpCmd.Split(spaceSplit, 3);
for (int i = 1; i < requestLines.Count; i++)
{
var rawHeader = requestLines[i];
String[] header = rawHeader.ToLower().Trim().Split(colonSpaceSplit, 2, StringSplitOptions.None);
if (splitBuffer.Length != 3)
{
TcpHelper.SendRaw(httpCmd, tunnelHostName, ref requestLines, args.IsSSLRequest, clientStreamReader.BaseStream);
if ((header[0] == "upgrade") && (header[1] == "websocket"))
{
if (clientStream != null)
clientStream.Close();
return;
}
var method = splitBuffer[0];
var remoteUri = splitBuffer[1];
Version version;
if (splitBuffer[2] == "HTTP/1.1")
{
version = new Version(1, 1);
}
else
{
version = new Version(1, 0);
}
TcpHelper.SendRaw(httpCmd, tunnelHostName, ref requestLines, args.IsSSLRequest, clientStreamReader.BaseStream);
if (securehost != null)
{
remoteUri = securehost + remoteUri;
args.IsSSLRequest = true;
}
if (clientStream != null)
clientStream.Close();
//construct the web request that we are going to issue on behalf of the client.
args.ProxyRequest = (HttpWebRequest)HttpWebRequest.Create(remoteUri.Trim());
args.ProxyRequest.Proxy = null;
args.ProxyRequest.UseDefaultCredentials = true;
args.ProxyRequest.Method = method;
args.ProxyRequest.ProtocolVersion = version;
args.ClientStream = clientStream;
args.ClientStreamReader = clientStreamReader;
return;
}
}
for (int i = 1; i < requestLines.Count; i++)
{
var rawHeader = requestLines[i];
String[] header = rawHeader.ToLower().Trim().Split(colonSpaceSplit, 2, StringSplitOptions.None);
ReadRequestHeaders(ref requestLines, args.ProxyRequest);
if ((header[0] == "upgrade") && (header[1] == "websocket"))
{
int contentLen = (int)args.ProxyRequest.ContentLength;
TcpHelper.SendRaw(httpCmd, tunnelHostName, ref requestLines, args.IsSSLRequest, clientStreamReader.BaseStream);
args.ProxyRequest.AllowAutoRedirect = false;
args.ProxyRequest.AutomaticDecompression = DecompressionMethods.None;
if (clientStream != null)
clientStream.Close();
if (BeforeRequest != null)
{
args.RequestHostname = args.ProxyRequest.RequestUri.Host;
args.RequestURL = args.ProxyRequest.RequestUri.OriginalString;
return;
}
}
args.RequestLength = contentLen;
ReadRequestHeaders(ref requestLines, args.ProxyRequest);
args.RequestHttpVersion = version;
args.ClientPort = ((IPEndPoint)Client.Client.RemoteEndPoint).Port;
args.ClientIpAddress = ((IPEndPoint)Client.Client.RemoteEndPoint).Address;
args.RequestIsAlive = args.ProxyRequest.KeepAlive;
BeforeRequest(null, args);
}
if (args.CancelRequest)
{
if (args.RequestIsAlive)
{
requestLines.Clear();
while (!String.IsNullOrEmpty(tmpLine = clientStreamReader.ReadLine()))
{
requestLines.Add(tmpLine);
}
int contentLen = (int)args.ProxyRequest.ContentLength;
httpCmd = requestLines.Count > 0 ? requestLines[0] : null;
continue;
}
else
break;
}
args.ProxyRequest.AllowAutoRedirect = false;
args.ProxyRequest.AutomaticDecompression = DecompressionMethods.None;
args.ProxyRequest.ConnectionGroupName = connectionGroup;
args.ProxyRequest.AllowWriteStreamBuffering = true;
if (BeforeRequest != null)
{
args.RequestHostname = args.ProxyRequest.RequestUri.Host;
args.RequestURL = args.ProxyRequest.RequestUri.OriginalString;
args.FinishedRequestEvent = new ManualResetEvent(false);
args.RequestLength = contentLen;
args.RequestHttpVersion = version;
args.ClientPort = ((IPEndPoint)Client.Client.RemoteEndPoint).Port;
args.ClientIpAddress = ((IPEndPoint)Client.Client.RemoteEndPoint).Address;
args.RequestIsAlive = args.ProxyRequest.KeepAlive;
if (method.ToUpper() == "POST" || method.ToUpper() == "PUT")
{
args.ProxyRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), args);
}
else
BeforeRequest(null, args);
}
string tmpLine;
if (args.CancelRequest)
{
if (args.RequestIsAlive)
{
requestLines.Clear();
while (!String.IsNullOrEmpty(tmpLine = clientStreamReader.ReadLine()))
{
args.ProxyRequest.BeginGetResponse(new AsyncCallback(HandleServerResponse), args);
requestLines.Add(tmpLine);
}
httpCmd = requestLines.Count > 0 ? requestLines[0] : null;
return;
}
else
return;
}
if (args.IsSSLRequest)
{
if (args.ProxyRequest.Method == "POST" || args.ProxyRequest.Method == "PUT")
args.FinishedRequestEvent.WaitOne();
else
args.FinishedRequestEvent.Set();
}
else
args.FinishedRequestEvent.WaitOne();
httpCmd = null;
if (args.ProxyRequest.KeepAlive)
{
requestLines.Clear();
while (!String.IsNullOrEmpty(tmpLine = clientStreamReader.ReadLine()))
{
requestLines.Add(tmpLine);
}
httpCmd = requestLines.Count() > 0 ? requestLines[0] : null;
args.ProxyRequest.ConnectionGroupName = connectionGroup;
args.ProxyRequest.AllowWriteStreamBuffering = true;
}
if (args.RequestWasModified)
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] requestBytes = encoding.GetBytes(args.RequestHtmlBody);
args.ProxyRequest.ContentLength = requestBytes.Length;
Stream newStream = args.ProxyRequest.GetRequestStream();
newStream.Write(requestBytes, 0, requestBytes.Length);
args.ProxyRequest.BeginGetResponse(new AsyncCallback(HandleHttpSessionResponse), args);
if (args.ServerResponse != null)
args.ServerResponse.Close();
}
catch (IOException ex)
{
throw ex;
}
catch (UriFormatException ex)
}
else
{
if (method.ToUpper() == "POST" || method.ToUpper() == "PUT")
{
throw ex;
args.ProxyRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), args);
}
catch (WebException ex)
else
{
throw ex;
args.ProxyRequest.BeginGetResponse(new AsyncCallback(HandleHttpSessionResponse), args);
}
finally
{
if (sw != null) sw.Close();
if (mw != null) mw.Close();
if (args.ProxyRequest != null) args.ProxyRequest.Abort();
if (args.ServerResponseStream != null) args.ServerResponseStream.Close();
}
}
}
catch (AuthenticationException ex)
{
Debug.WriteLine(ex.Message);
}
catch (EndOfStreamException ex)
{
Debug.WriteLine(ex.Message);
}
catch (IOException ex)
{
Debug.WriteLine(ex.Message);
return;
}
catch (UriFormatException ex)
{
Debug.WriteLine(ex.Message);
return;
}
catch (WebException ex)
{
Debug.WriteLine(ex.Message);
return;
}
finally
{
if (connectStreamWriter != null)
connectStreamWriter.Close();
if (clientStreamReader != null)
clientStreamReader.Close();
if (clientStream != null)
clientStream.Close();
}
}
private static void ReadRequestHeaders(ref List<string> RequestLines, HttpWebRequest WebRequest)
{
......@@ -467,7 +447,7 @@ namespace Titanium.Web.Proxy
break;
default:
if (header.Length > 0)
if (header.Length >= 2)
WebRequest.Headers.Add(header[0], header[1]);
else
WebRequest.Headers.Add(header[0], "");
......@@ -527,7 +507,6 @@ namespace Titanium.Web.Proxy
args.ProxyRequest.KeepAlive = false;
args.FinishedRequestEvent.Set();
Debug.WriteLine(ex.Message);
return;
}
......@@ -536,7 +515,6 @@ namespace Titanium.Web.Proxy
args.ProxyRequest.KeepAlive = false;
args.FinishedRequestEvent.Set();
Debug.WriteLine(ex.Message);
return;
......@@ -609,7 +587,6 @@ namespace Titanium.Web.Proxy
postStream.Close();
args.ProxyRequest.KeepAlive = false;
args.FinishedRequestEvent.Set();
Debug.WriteLine(ex.Message);
return;
}
......@@ -619,14 +596,13 @@ namespace Titanium.Web.Proxy
postStream.Close();
args.ProxyRequest.KeepAlive = false;
args.FinishedRequestEvent.Set();
Debug.WriteLine(ex.Message);
return;
}
}
args.ProxyRequest.BeginGetResponse(new AsyncCallback(HandleServerResponse), args);
args.ProxyRequest.BeginGetResponse(new AsyncCallback(HandleHttpSessionResponse), args);
}
......
......@@ -11,12 +11,13 @@ using System.Security.Authentication;
using System.Diagnostics;
using Titanium.Web.Proxy.Models;
using Titanium.Web.Proxy.Helpers;
using System.Threading.Tasks;
namespace Titanium.Web.Proxy
{
partial class ProxyServer
{
private static void HandleServerResponse(IAsyncResult AsynchronousResult)
private static void HandleHttpSessionResponse(IAsyncResult AsynchronousResult)
{
SessionEventArgs args = (SessionEventArgs)AsynchronousResult.AsyncState;
......@@ -55,7 +56,7 @@ namespace Titanium.Web.Proxy
if (BeforeResponse != null)
BeforeResponse(null, args);
if (args.WasModified)
if (args.ResponseWasModified)
{
byte[] data;
......@@ -137,21 +138,36 @@ namespace Titanium.Web.Proxy
finally
{
if (args.ProxyRequest.KeepAlive == false)
{
if (responseWriter != null)
responseWriter.Close();
if (clientWriteStream != null)
clientWriteStream.Close();
}
if (args.ProxyRequest != null) args.ProxyRequest.Abort();
if (args.ServerResponseStream != null) args.ServerResponseStream.Close();
if (args.ServerResponse != null)
args.ServerResponse.Close();
args.FinishedRequestEvent.Set();
}
if (args.ProxyRequest.KeepAlive == false)
{
if (responseWriter != null)
responseWriter.Close();
if (clientWriteStream != null)
clientWriteStream.Close();
args.Client.Close();
}
else
{
string httpCmd, tmpLine;
List<string> requestLines = new List<string>();
requestLines.Clear();
while (!String.IsNullOrEmpty(tmpLine = args.ClientStreamReader.ReadLine()))
{
requestLines.Add(tmpLine);
}
httpCmd = requestLines.Count() > 0 ? requestLines[0] : null;
TcpClient Client = args.Client;
HandleHttpSessionRequest(Client, httpCmd, args.ProxyRequest.ConnectionGroupName, args.ClientStream, args.tunnelHostName, requestLines, args.ClientStreamReader, args.securehost);
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment