Commit 0bb4a554 authored by titanium007's avatar titanium007

Fix set/get request/response/headers

parent ce0a71fb
...@@ -57,43 +57,57 @@ Sample request and response event handlers ...@@ -57,43 +57,57 @@ Sample request and response event handlers
public void OnRequest(object sender, SessionEventArgs e) public void OnRequest(object sender, SessionEventArgs e)
{ {
Console.WriteLine(e.RequestURL); Console.WriteLine(e.RequestURL);
if (e.RequestURL.Contains("somewebsite.com")) //modify request headers
var requestHeaders = e.RequestHeaders;
if ((e.RequestMethod.ToUpper() == "POST" || e.RequestMethod.ToUpper() == "PUT") && e.RequestContentLength > 0) if ((e.RequestMethod.ToUpper() == "POST" || e.RequestMethod.ToUpper() == "PUT") && e.RequestContentLength > 0)
{ {
//Get/Set request body bytes
byte[] bodyBytes = e.GetRequestBody();
e.SetRequestBody(bodyBytes);
var m = e.GetRequestBody().Replace("a", "b"); //Get/Set request body as string
e.SetRequestBody(m); string bodyString = e.GetRequestBodyAsString();
e.SetRequestBodyString(bodyString);
} }
//To cancel a request with a custom HTML content //To cancel a request with a custom HTML content
//Filter URL //Filter URL
if (e.RequestURL.Contains("somewebsite.com")) if (e.RequestURL.Contains("google.com"))
{ {
e.Ok("<!DOCTYPE html><html><body><h1>Blocked</h1><p>Website blocked.</p></body></html>"); e.Ok("<!DOCTYPE html><html><body><h1>Website Blocked</h1><p>Blocked by titanium web proxy.</p></body></html>");
} }
} }
public void OnResponse(object sender, SessionEventArgs e) public void OnResponse(object sender, SessionEventArgs e)
{ {
if (e.RequestURL.Contains("somewebsite.com"))
//To modify a response headers
var responseHeaders = e.ResponseHeaders;
if (e.ResponseStatusCode == HttpStatusCode.OK) if (e.ResponseStatusCode == HttpStatusCode.OK)
{ {
if (e.ResponseContentType.Trim().ToLower().Contains("text/html")) if (e.ResponseContentType.Trim().ToLower().Contains("text/html"))
{ {
//Get response body //Get/Set response body bytes
string responseBody = e.GetResponseBody(); byte[] responseBodyBytes = e.GetResponseBody();
e.SetResponseBody(responseBodyBytes);
//Get response body as string
string responseBody = e.GetResponseBodyAsString();
//Modify e.ServerResponse //Modify e.ServerResponse
Regex rex = new Regex("</body>", RegexOptions.RightToLeft | RegexOptions.IgnoreCase | RegexOptions.Multiline); Regex rex = new Regex("</body>", RegexOptions.RightToLeft | RegexOptions.IgnoreCase | RegexOptions.Multiline);
string modified = rex.Replace(responseBody, "<script type =\"text/javascript\">alert('Response was modified by this script!');</script></body>", 1); string modified = rex.Replace(responseBody, "<script type =\"text/javascript\">alert('Response was modified by this script!');</script></body>", 1);
//Set modifed response Html Body //Set modifed response Html Body
e.SetResponseBody(modified); e.SetResponseBodyString(modified);
} }
} }
} }
......
...@@ -6,7 +6,7 @@ using System.Net; ...@@ -6,7 +6,7 @@ using System.Net;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.DirectoryServices.AccountManagement; using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory; using System.DirectoryServices.ActiveDirectory;
using Titanium.Web.Proxy.Models; using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy; using Titanium.Web.Proxy;
using Titanium.Web.Proxy.Helpers; using Titanium.Web.Proxy.Helpers;
...@@ -60,21 +60,27 @@ namespace Titanium.Web.Proxy.Test ...@@ -60,21 +60,27 @@ namespace Titanium.Web.Proxy.Test
Console.WriteLine(e.RequestURL); Console.WriteLine(e.RequestURL);
//if (e.RequestURL.Contains("somewebsite.com")) ////modify request headers
// if ((e.RequestMethod.ToUpper() == "POST" || e.RequestMethod.ToUpper() == "PUT") && e.RequestContentLength > 0) //var requestHeaders = e.RequestHeaders;
// {
// var m = e.GetRequestBody().Replace("a", "b"); //if ((e.RequestMethod.ToUpper() == "POST" || e.RequestMethod.ToUpper() == "PUT") && e.RequestContentLength > 0)
// e.SetRequestBody(m); //{
// //Get/Set request body bytes
// byte[] bodyBytes = e.GetRequestBody();
// e.SetRequestBody(bodyBytes);
// } // //Get/Set request body as string
// string bodyString = e.GetRequestBodyAsString();
// e.SetRequestBodyString(bodyString);
//To cancel a request with a custom HTML content //}
//Filter URL
////To cancel a request with a custom HTML content
////Filter URL
//if (e.RequestURL.Contains("somewebsite.com")) //if (e.RequestURL.Contains("google.com"))
//{ //{
// e.Ok("<!DOCTYPE html><html><body><h1>Blocked</h1><p>Website blocked.</p></body></html>"); // e.Ok("<!DOCTYPE html><html><body><h1>Website Blocked</h1><p>Blocked by titanium web proxy.</p></body></html>");
//} //}
} }
...@@ -83,22 +89,26 @@ namespace Titanium.Web.Proxy.Test ...@@ -83,22 +89,26 @@ namespace Titanium.Web.Proxy.Test
//Insert script to read the Browser URL and send it back to proxy //Insert script to read the Browser URL and send it back to proxy
public void OnResponse(object sender, SessionEventArgs e) public void OnResponse(object sender, SessionEventArgs e)
{ {
//To modify a response //modify response headers
//var responseHeaders = e.ResponseHeaders;
//if (e.RequestURL.Contains("somewebsite.com"))
//if (e.ResponseStatusCode == HttpStatusCode.OK) //if (e.ResponseStatusCode == HttpStatusCode.OK)
//{ //{
// if (e.ResponseContentType.Trim().ToLower().Contains("text/html")) // if (e.ResponseContentType.Trim().ToLower().Contains("text/html"))
// { // {
// //Get response body // //Get/Set response body bytes
// string responseBody = e.GetResponseBody(); // byte[] responseBodyBytes = e.GetResponseBody();
// e.SetResponseBody(responseBodyBytes);
// //Get response body as string
// string responseBody = e.GetResponseBodyAsString();
// //Modify e.ServerResponse // //Modify e.ServerResponse
// Regex rex = new Regex("</body>", RegexOptions.RightToLeft | RegexOptions.IgnoreCase | RegexOptions.Multiline); // Regex rex = new Regex("</body>", RegexOptions.RightToLeft | RegexOptions.IgnoreCase | RegexOptions.Multiline);
// string modified = rex.Replace(responseBody, "<script type =\"text/javascript\">alert('Response was modified by this script!');</script></body>", 1); // string modified = rex.Replace(responseBody, "<script type =\"text/javascript\">alert('Response was modified by this script!');</script></body>", 1);
// //Set modifed response Html Body // //Set modifed response Html Body
// e.SetResponseBody(modified); // e.SetResponseBodyString(modified);
// } // }
//} //}
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace Titanium.Web.Proxy.Extensions
{
public static class HttpWebResponseExtensions
{
public static Encoding GetEncoding(this HttpWebResponse response)
{
if (string.IsNullOrEmpty(response.CharacterSet)) return Encoding.GetEncoding("ISO-8859-1");
else
return Encoding.GetEncoding(response.CharacterSet);
}
}
}
...@@ -11,31 +11,10 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -11,31 +11,10 @@ namespace Titanium.Web.Proxy.Helpers
{ {
private static readonly int BUFFER_SIZE = 8192; private static readonly int BUFFER_SIZE = 8192;
public static string DecompressGzip(Stream input, Encoding e)
{
using (System.IO.Compression.GZipStream decompressor = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
{
int read = 0;
var buffer = new byte[BUFFER_SIZE];
using (MemoryStream output = new MemoryStream())
{
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
return e.GetString(output.ToArray());
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressZlib(string responseData, Encoding e) public static byte[] CompressZlib(byte[] bytes)
{ {
Byte[] bytes = e.GetBytes(responseData);
using (MemoryStream ms = new MemoryStream()) using (MemoryStream ms = new MemoryStream())
{ {
using (Ionic.Zlib.ZlibStream zip = new Ionic.Zlib.ZlibStream(ms, Ionic.Zlib.CompressionMode.Compress, true)) using (Ionic.Zlib.ZlibStream zip = new Ionic.Zlib.ZlibStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
...@@ -48,9 +27,8 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -48,9 +27,8 @@ namespace Titanium.Web.Proxy.Helpers
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressDeflate(string responseData, Encoding e) public static byte[] CompressDeflate(byte[] bytes)
{ {
Byte[] bytes = e.GetBytes(responseData);
using (MemoryStream ms = new MemoryStream()) using (MemoryStream ms = new MemoryStream())
{ {
...@@ -64,9 +42,8 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -64,9 +42,8 @@ namespace Titanium.Web.Proxy.Helpers
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressGzip(string responseData, Encoding e) public static byte[] CompressGzip(byte[] bytes)
{ {
Byte[] bytes = e.GetBytes(responseData);
using (MemoryStream ms = new MemoryStream()) using (MemoryStream ms = new MemoryStream())
{ {
...@@ -79,7 +56,27 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -79,7 +56,27 @@ namespace Titanium.Web.Proxy.Helpers
} }
} }
public static string DecompressDeflate(Stream input, Encoding e)
public static byte[] DecompressGzip(Stream input)
{
using (System.IO.Compression.GZipStream decompressor = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
{
int read = 0;
var buffer = new byte[BUFFER_SIZE];
using (MemoryStream output = new MemoryStream())
{
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
return output.ToArray();
}
}
}
public static byte[] DecompressDeflate(Stream input)
{ {
using (Ionic.Zlib.DeflateStream decompressor = new Ionic.Zlib.DeflateStream(input, Ionic.Zlib.CompressionMode.Decompress)) using (Ionic.Zlib.DeflateStream decompressor = new Ionic.Zlib.DeflateStream(input, Ionic.Zlib.CompressionMode.Decompress))
{ {
...@@ -92,11 +89,11 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -92,11 +89,11 @@ namespace Titanium.Web.Proxy.Helpers
{ {
output.Write(buffer, 0, read); output.Write(buffer, 0, read);
} }
return e.GetString(output.ToArray()); return output.ToArray();
} }
} }
} }
public static string DecompressZlib(Stream input, Encoding e) public static byte[] DecompressZlib(Stream input)
{ {
using (Ionic.Zlib.ZlibStream decompressor = new Ionic.Zlib.ZlibStream(input, Ionic.Zlib.CompressionMode.Decompress)) using (Ionic.Zlib.ZlibStream decompressor = new Ionic.Zlib.ZlibStream(input, Ionic.Zlib.CompressionMode.Decompress))
{ {
...@@ -109,7 +106,7 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -109,7 +106,7 @@ namespace Titanium.Web.Proxy.Helpers
{ {
output.Write(buffer, 0, read); output.Write(buffer, 0, read);
} }
return e.GetString(output.ToArray()); return output.ToArray();
} }
} }
} }
......
...@@ -8,6 +8,7 @@ using System.Net; ...@@ -8,6 +8,7 @@ using System.Net;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Net.Sockets; using System.Net.Sockets;
using Titanium.Web.Proxy.Extensions; using Titanium.Web.Proxy.Extensions;
using Titanium.Web.Proxy.Models;
namespace Titanium.Web.Proxy.Helpers namespace Titanium.Web.Proxy.Helpers
{ {
...@@ -16,10 +17,10 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -16,10 +17,10 @@ namespace Titanium.Web.Proxy.Helpers
private static readonly int BUFFER_SIZE = 8192; private static readonly int BUFFER_SIZE = 8192;
private static readonly String[] colonSpaceSplit = new string[] { ": " }; private static readonly String[] colonSpaceSplit = new string[] { ": " };
public static void SendRaw(Stream clientStream, string httpCmd, List<string> requestLines, string hostName, int tunnelPort, bool isHttps) public static void SendRaw(Stream clientStream, string httpCmd, List<HttpHeader> requestHeaders, string hostName, int tunnelPort, bool isHttps)
{ {
StringBuilder sb = null; StringBuilder sb = null;
if (httpCmd != null || requestLines != null) if (httpCmd != null || requestHeaders != null)
{ {
sb = new StringBuilder(); sb = new StringBuilder();
if (httpCmd != null) if (httpCmd != null)
...@@ -27,9 +28,9 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -27,9 +28,9 @@ namespace Titanium.Web.Proxy.Helpers
sb.Append(httpCmd); sb.Append(httpCmd);
sb.Append(Environment.NewLine); sb.Append(Environment.NewLine);
} }
for (int i = 0; i < requestLines.Count; i++) for (int i = 0; i < requestHeaders.Count; i++)
{ {
var header = requestLines[i]; var header = requestHeaders[i].ToString();
sb.Append(header); sb.Append(header);
sb.Append(Environment.NewLine); sb.Append(Environment.NewLine);
} }
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Titanium.Web.Proxy.Models
{
public class HttpHeader
{
public string Name { get; set; }
public string Value { get; set; }
public HttpHeader(string name, string value)
{
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value)) throw new Exception("Name or value cannot be null");
this.Name = name.Trim();
this.Value = value.Trim();
}
public string ToString()
{
return String.Format("{0}: {1}", this.Name, this.Value);
}
}
}
...@@ -10,8 +10,9 @@ using System.Security.Authentication; ...@@ -10,8 +10,9 @@ using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Diagnostics; using System.Diagnostics;
using System.Threading.Tasks; using System.Threading.Tasks;
using Titanium.Web.Proxy.Models; using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy.Helpers; using Titanium.Web.Proxy.Helpers;
using System.Text;
namespace Titanium.Web.Proxy namespace Titanium.Web.Proxy
...@@ -29,12 +30,12 @@ namespace Titanium.Web.Proxy ...@@ -29,12 +30,12 @@ namespace Titanium.Web.Proxy
private static readonly Regex cookieSplitRegEx = new Regex(@",(?! )"); private static readonly Regex cookieSplitRegEx = new Regex(@",(?! )");
private static readonly byte[] chunkTrail = Encoding.ASCII.GetBytes(Environment.NewLine);
private static readonly byte[] ChunkEnd = Encoding.ASCII.GetBytes(0.ToString("x2") + Environment.NewLine + Environment.NewLine);
private static object certificateAccessLock = new object(); private static object certificateAccessLock = new object();
private static TcpListener listener; private static TcpListener listener;
private static Thread listenerThread;
private static bool ShouldListen { get; set; }
private static CertificateManager CertManager { get; set; } private static CertificateManager CertManager { get; set; }
public static List<string> ExcludedHttpsHostNameRegex = new List<string>(); public static List<string> ExcludedHttpsHostNameRegex = new List<string>();
...@@ -82,43 +83,20 @@ namespace Titanium.Web.Proxy ...@@ -82,43 +83,20 @@ namespace Titanium.Web.Proxy
} }
private static void Listen(Object obj)
{
TcpListener listener = (TcpListener)obj;
while (ShouldListen)
{
TcpClient client = null;
try
{
client = listener.AcceptTcpClient();
Task.Factory.StartNew(() => HandleClient(client));
}
catch
{
if (client != null)
client.Close();
}
}
}
public static bool Start() public static bool Start()
{ {
listener = new TcpListener(ListeningIpAddress, ListeningPort); listener = new TcpListener(ListeningIpAddress, ListeningPort);
listener.Start(); listener.Start();
listenerThread = new Thread(new ParameterizedThreadStart(Listen));
listenerThread.IsBackground = true;
ShouldListen = true;
listenerThread.Start(listener);
ListeningPort = ((IPEndPoint)listener.LocalEndpoint).Port; ListeningPort = ((IPEndPoint)listener.LocalEndpoint).Port;
// accept clients asynchronously
listener.BeginAcceptTcpClient(OnAcceptConnection, listener);
if (SetAsSystemProxy) if (SetAsSystemProxy)
{ {
SystemProxyHelper.EnableProxyHTTP("localhost", ListeningPort); SystemProxyHelper.EnableProxyHTTP(ListeningIpAddress == IPAddress.Any ? "127.0.0.1" : ListeningIpAddress.ToString(), ListeningPort);
FireFoxHelper.AddFirefox(); FireFoxHelper.AddFirefox();
...@@ -130,13 +108,28 @@ namespace Titanium.Web.Proxy ...@@ -130,13 +108,28 @@ namespace Titanium.Web.Proxy
//If certificate was trusted by the machine //If certificate was trusted by the machine
if (certTrusted) if (certTrusted)
{ {
SystemProxyHelper.EnableProxyHTTPS("localhost", ListeningPort); SystemProxyHelper.EnableProxyHTTPS(ListeningIpAddress == IPAddress.Any ? "127.0.0.1" : ListeningIpAddress.ToString(), ListeningPort);
} }
} }
} }
return true; return true;
} }
private static void OnAcceptConnection(IAsyncResult asyn)
{
try
{
// Get the listener that handles the client request.
listener.BeginAcceptTcpClient(OnAcceptConnection, listener);
TcpClient client = listener.EndAcceptTcpClient(asyn);
Task.Factory.StartNew(() => HandleClient(client));
}
catch { }
}
public static void Stop() public static void Stop()
{ {
...@@ -146,9 +139,7 @@ namespace Titanium.Web.Proxy ...@@ -146,9 +139,7 @@ namespace Titanium.Web.Proxy
FireFoxHelper.RemoveFirefox(); FireFoxHelper.RemoveFirefox();
} }
ShouldListen = false;
listener.Stop(); listener.Stop();
listenerThread.Interrupt();
CertManager.Dispose(); CertManager.Dispose();
} }
......
This diff is collapsed.
This diff is collapsed.
...@@ -77,10 +77,12 @@ ...@@ -77,10 +77,12 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Exceptions\BodyNotFoundException.cs" /> <Compile Include="Exceptions\BodyNotFoundException.cs" />
<Compile Include="Extensions\HttpWebResponseExtensions.cs" />
<Compile Include="Extensions\HttpWebRequestExtensions.cs" /> <Compile Include="Extensions\HttpWebRequestExtensions.cs" />
<Compile Include="Helpers\CertificateManager.cs" /> <Compile Include="Helpers\CertificateManager.cs" />
<Compile Include="Helpers\Firefox.cs" /> <Compile Include="Helpers\Firefox.cs" />
<Compile Include="Helpers\SystemProxy.cs" /> <Compile Include="Helpers\SystemProxy.cs" />
<Compile Include="Models\HttpHeader.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RequestHandler.cs" /> <Compile Include="RequestHandler.cs" />
<Compile Include="ResponseHandler.cs" /> <Compile Include="ResponseHandler.cs" />
...@@ -88,7 +90,7 @@ ...@@ -88,7 +90,7 @@
<Compile Include="Helpers\NetFramework.cs" /> <Compile Include="Helpers\NetFramework.cs" />
<Compile Include="Helpers\Compression.cs" /> <Compile Include="Helpers\Compression.cs" />
<Compile Include="ProxyServer.cs" /> <Compile Include="ProxyServer.cs" />
<Compile Include="Models\SessionEventArgs.cs" /> <Compile Include="EventArgs\SessionEventArgs.cs" />
<Compile Include="Helpers\Tcp.cs" /> <Compile Include="Helpers\Tcp.cs" />
<Compile Include="Extensions\StreamExtensions.cs" /> <Compile Include="Extensions\StreamExtensions.cs" />
</ItemGroup> </ItemGroup>
......
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