Commit 990b7412 authored by justcoding121's avatar justcoding121 Committed by justcoding121

cleanup

parent 6b42b1b4
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<solution> <solution>
<add key="disableSourceControlIntegration" value="true" /> <add key="disableSourceControlIntegration" value="true" />
......
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" /> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup> </startup>
</configuration> </configuration>
\ No newline at end of file
using System; using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Titanium.Web.Proxy.Helpers;
namespace Titanium.Web.Proxy.Test namespace Titanium.Web.Proxy.Test
{ {
public class Program public class Program
{ {
static ProxyTestController controller = new ProxyTestController(); private static readonly ProxyTestController Controller = new ProxyTestController();
public static void Main(string[] args) public static void Main(string[] args)
{ {
//On Console exit make sure we also exit the proxy //On Console exit make sure we also exit the proxy
NativeMethods.handler = new NativeMethods.ConsoleEventDelegate(ConsoleEventCallback); NativeMethods.Handler = ConsoleEventCallback;
NativeMethods.SetConsoleCtrlHandler(NativeMethods.handler, true); NativeMethods.SetConsoleCtrlHandler(NativeMethods.Handler, true);
Console.Write("Do you want to monitor HTTPS? (Y/N):"); Console.Write("Do you want to monitor HTTPS? (Y/N):");
if (Console.ReadLine().Trim().ToLower() == "y") var readLine = Console.ReadLine();
if (readLine != null && readLine.Trim().ToLower() == "y")
{ {
controller.EnableSSL = true; Controller.EnableSsl = true;
} }
Console.Write("Do you want to set this as a System Proxy? (Y/N):"); Console.Write("Do you want to set this as a System Proxy? (Y/N):");
if (Console.ReadLine().Trim().ToLower() == "y") var line = Console.ReadLine();
if (line != null && line.Trim().ToLower() == "y")
{ {
controller.SetAsSystemProxy = true; Controller.SetAsSystemProxy = true;
} }
//Start proxy controller //Start proxy controller
controller.StartProxy(); Controller.StartProxy();
Console.WriteLine("Hit any key to exit.."); Console.WriteLine("Hit any key to exit..");
Console.WriteLine(); Console.WriteLine();
Console.Read(); Console.Read();
controller.Stop(); Controller.Stop();
} }
static bool ConsoleEventCallback(int eventType) private static bool ConsoleEventCallback(int eventType)
{ {
if (eventType == 2) if (eventType == 2)
{ {
try try
{ {
controller.Stop(); Controller.Stop();
}
catch
{
// ignored
} }
catch { }
} }
return false; return false;
} }
} }
internal static class NativeMethods internal static class NativeMethods
{ {
// Keeps it from getting garbage collected
internal static ConsoleEventDelegate Handler;
[DllImport("kernel32.dll", SetLastError = true)] [DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add); internal static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
// Pinvoke // Pinvoke
internal delegate bool ConsoleEventDelegate(int eventType); internal delegate bool ConsoleEventDelegate(int eventType);
// Keeps it from getting garbage collected
internal static ConsoleEventDelegate handler;
} }
}
} \ No newline at end of file
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
// associated with an assembly. // associated with an assembly.
[assembly: AssemblyTitle("Demo")] [assembly: AssemblyTitle("Demo")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
...@@ -17,9 +17,11 @@ using System.Runtime.InteropServices; ...@@ -17,9 +17,11 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible // Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from // to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. // COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM // The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("33a2109d-0312-4c94-aa51-fbb2a83e63ab")] [assembly: Guid("33a2109d-0312-4c94-aa51-fbb2a83e63ab")]
// Version information for an assembly consists of the following four values: // Version information for an assembly consists of the following four values:
...@@ -32,5 +34,6 @@ using System.Runtime.InteropServices; ...@@ -32,5 +34,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
\ No newline at end of file
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;
using Titanium.Web.Proxy.EventArguments; using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy;
using Titanium.Web.Proxy.Helpers;
namespace Titanium.Web.Proxy.Test namespace Titanium.Web.Proxy.Test
{ {
public partial class ProxyTestController public class ProxyTestController
{ {
public int ListeningPort { get; set; } public int ListeningPort { get; set; }
public bool EnableSSL { get; set; } public bool EnableSsl { get; set; }
public bool SetAsSystemProxy { get; set; } public bool SetAsSystemProxy { get; set; }
public void StartProxy() public void StartProxy()
{ {
ProxyServer.BeforeRequest += OnRequest; ProxyServer.BeforeRequest += OnRequest;
ProxyServer.BeforeResponse += OnResponse; ProxyServer.BeforeResponse += OnResponse;
ProxyServer.EnableSSL = EnableSSL; ProxyServer.EnableSsl = EnableSsl;
ProxyServer.SetAsSystemProxy = SetAsSystemProxy; ProxyServer.SetAsSystemProxy = SetAsSystemProxy;
...@@ -40,9 +27,9 @@ namespace Titanium.Web.Proxy.Test ...@@ -40,9 +27,9 @@ namespace Titanium.Web.Proxy.Test
ProxyServer.ListeningPort = ProxyServer.ListeningPort; ProxyServer.ListeningPort = ProxyServer.ListeningPort;
Console.WriteLine(String.Format("Proxy listening on local machine port: {0} ", ProxyServer.ListeningPort)); Console.WriteLine("Proxy listening on local machine port: {0} ", ProxyServer.ListeningPort);
} }
public void Stop() public void Stop()
{ {
ProxyServer.BeforeRequest -= OnRequest; ProxyServer.BeforeRequest -= OnRequest;
...@@ -52,13 +39,11 @@ namespace Titanium.Web.Proxy.Test ...@@ -52,13 +39,11 @@ namespace Titanium.Web.Proxy.Test
} }
//Test On Request, intecept requests //Test On Request, intecept requests
//Read browser URL send back to proxy by the injection script in OnResponse event //Read browser URL send back to proxy by the injection script in OnResponse event
public void OnRequest(object sender, SessionEventArgs e) public void OnRequest(object sender, SessionEventArgs e)
{ {
Console.WriteLine(e.RequestUrl);
Console.WriteLine(e.RequestURL);
////read request headers ////read request headers
//var requestHeaders = e.RequestHeaders; //var requestHeaders = e.RequestHeaders;
...@@ -82,7 +67,6 @@ namespace Titanium.Web.Proxy.Test ...@@ -82,7 +67,6 @@ namespace Titanium.Web.Proxy.Test
//{ //{
// e.Ok("<!DOCTYPE html><html><body><h1>Website Blocked</h1><p>Blocked by titanium web proxy.</p></body></html>"); // e.Ok("<!DOCTYPE html><html><body><h1>Website Blocked</h1><p>Blocked by titanium web proxy.</p></body></html>");
//} //}
} }
//Test script injection //Test script injection
...@@ -112,9 +96,6 @@ namespace Titanium.Web.Proxy.Test ...@@ -112,9 +96,6 @@ namespace Titanium.Web.Proxy.Test
// e.SetResponseBodyString(modified); // e.SetResponseBodyString(modified);
// } // }
//} //}
} }
} }
}
} \ No newline at end of file
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Titanium.Web.Proxy.Exceptions namespace Titanium.Web.Proxy.Exceptions
{ {
public class BodyNotFoundException : Exception public class BodyNotFoundException : Exception
{ {
public BodyNotFoundException(string message) public BodyNotFoundException(string message)
:base(message) : base(message)
{ {
} }
} }
} }
\ No newline at end of file
using System; using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text; using System.Text;
namespace Titanium.Web.Proxy.Extensions namespace Titanium.Web.Proxy.Extensions
...@@ -24,9 +21,12 @@ namespace Titanium.Web.Proxy.Extensions ...@@ -24,9 +21,12 @@ namespace Titanium.Web.Proxy.Extensions
} }
} }
} }
catch { } catch
{
// ignored
}
return Encoding.GetEncoding("ISO-8859-1"); return Encoding.GetEncoding("ISO-8859-1");
} }
} }
} }
\ No newline at end of file
using System; using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text; using System.Text;
namespace Titanium.Web.Proxy.Extensions namespace Titanium.Web.Proxy.Extensions
...@@ -11,8 +8,7 @@ namespace Titanium.Web.Proxy.Extensions ...@@ -11,8 +8,7 @@ namespace Titanium.Web.Proxy.Extensions
public static Encoding GetEncoding(this HttpWebResponse response) public static Encoding GetEncoding(this HttpWebResponse response)
{ {
if (string.IsNullOrEmpty(response.CharacterSet)) return Encoding.GetEncoding("ISO-8859-1"); if (string.IsNullOrEmpty(response.CharacterSet)) return Encoding.GetEncoding("ISO-8859-1");
else return Encoding.GetEncoding(response.CharacterSet);
return Encoding.GetEncoding(response.CharacterSet);
} }
} }
} }
\ No newline at end of file
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
using System.Text;
namespace Titanium.Web.Proxy.Extensions namespace Titanium.Web.Proxy.Extensions
{ {
public static class StreamHelper public static class StreamHelper
{ {
private const int DEFAULT_BUFFER_SIZE = 8192; // +32767
public static void CopyToAsync(this Stream input, string initialData, Stream output, int bufferSize) public static void CopyToAsync(this Stream input, string initialData, Stream output, int bufferSize)
{ {
var bytes = Encoding.ASCII.GetBytes(initialData); var bytes = Encoding.ASCII.GetBytes(initialData);
output.Write(bytes,0, bytes.Length); output.Write(bytes, 0, bytes.Length);
CopyToAsync(input, output, bufferSize); CopyToAsync(input, output, bufferSize);
} }
//http://stackoverflow.com/questions/1540658/net-asynchronous-stream-read-write //http://stackoverflow.com/questions/1540658/net-asynchronous-stream-read-write
...@@ -25,15 +21,14 @@ namespace Titanium.Web.Proxy.Extensions ...@@ -25,15 +21,14 @@ namespace Titanium.Web.Proxy.Extensions
if (!input.CanRead) throw new InvalidOperationException("input must be open for reading"); if (!input.CanRead) throw new InvalidOperationException("input must be open for reading");
if (!output.CanWrite) throw new InvalidOperationException("output must be open for writing"); if (!output.CanWrite) throw new InvalidOperationException("output must be open for writing");
byte[][] buf = { new byte[bufferSize], new byte[bufferSize] }; byte[][] buf = {new byte[bufferSize], new byte[bufferSize]};
int[] bufl = { 0, 0 }; int[] bufl = {0, 0};
int bufno = 0; var bufno = 0;
IAsyncResult read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null); var read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null);
IAsyncResult write = null; IAsyncResult write = null;
while (true) while (true)
{ {
// wait for the read operation to complete // wait for the read operation to complete
read.AsyncWaitHandle.WaitOne(); read.AsyncWaitHandle.WaitOne();
bufl[bufno] = input.EndRead(read); bufl[bufno] = input.EndRead(read);
...@@ -62,7 +57,6 @@ namespace Titanium.Web.Proxy.Extensions ...@@ -62,7 +57,6 @@ namespace Titanium.Web.Proxy.Extensions
// A little speedier than using a ternary expression. // A little speedier than using a ternary expression.
bufno ^= 1; // bufno = ( bufno == 0 ? 1 : 0 ) ; bufno ^= 1; // bufno = ( bufno == 0 ? 1 : 0 ) ;
read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null); read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null);
} }
// wait for the final in-flight write operation, if one exists, to complete // wait for the final in-flight write operation, if one exists, to complete
...@@ -75,9 +69,11 @@ namespace Titanium.Web.Proxy.Extensions ...@@ -75,9 +69,11 @@ namespace Titanium.Web.Proxy.Extensions
output.Flush(); output.Flush();
} }
catch { } catch
{
// ignored
}
// return to the caller ; // return to the caller ;
return;
} }
} }
} }
\ No newline at end of file
...@@ -8,10 +8,10 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -8,10 +8,10 @@ namespace Titanium.Web.Proxy.Helpers
{ {
public class CertificateManager : IDisposable public class CertificateManager : IDisposable
{ {
private const string CERT_CREATE_FORMAT = private const string CertCreateFormat =
"-ss {0} -n \"CN={1}, O={2}\" -sky {3} -cy {4} -m 120 -a sha256 -eku 1.3.6.1.5.5.7.3.1 -b {5:MM/dd/yyyy} {6}"; "-ss {0} -n \"CN={1}, O={2}\" -sky {3} -cy {4} -m 120 -a sha256 -eku 1.3.6.1.5.5.7.3.1 -b {5:MM/dd/yyyy} {6}";
private readonly IDictionary<string, X509Certificate2> certificateCache; private readonly IDictionary<string, X509Certificate2> _certificateCache;
public string Issuer { get; private set; } public string Issuer { get; private set; }
public string RootCertificateName { get; private set; } public string RootCertificateName { get; private set; }
...@@ -27,7 +27,7 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -27,7 +27,7 @@ namespace Titanium.Web.Proxy.Helpers
MyStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); MyStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
RootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser); RootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
certificateCache = new Dictionary<string, X509Certificate2>(); _certificateCache = new Dictionary<string, X509Certificate2>();
} }
/// <summary> /// <summary>
...@@ -69,8 +69,9 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -69,8 +69,9 @@ namespace Titanium.Web.Proxy.Helpers
} }
protected virtual X509Certificate2 CreateCertificate(X509Store store, string certificateName) protected virtual X509Certificate2 CreateCertificate(X509Store store, string certificateName)
{ {
if (certificateCache.ContainsKey(certificateName))
return certificateCache[certificateName]; if (_certificateCache.ContainsKey(certificateName))
return _certificateCache[certificateName];
lock (store) lock (store)
{ {
...@@ -80,7 +81,7 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -80,7 +81,7 @@ namespace Titanium.Web.Proxy.Helpers
store.Open(OpenFlags.ReadWrite); store.Open(OpenFlags.ReadWrite);
string certificateSubject = string.Format("CN={0}, O={1}", certificateName, Issuer); string certificateSubject = string.Format("CN={0}, O={1}", certificateName, Issuer);
X509Certificate2Collection certificates = var certificates =
FindCertificates(store, certificateSubject); FindCertificates(store, certificateSubject);
if (certificates != null) if (certificates != null)
...@@ -102,8 +103,8 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -102,8 +103,8 @@ namespace Titanium.Web.Proxy.Helpers
finally finally
{ {
store.Close(); store.Close();
if (certificate != null && !certificateCache.ContainsKey(certificateName)) if (certificate != null && !_certificateCache.ContainsKey(certificateName))
certificateCache.Add(certificateName, certificate); _certificateCache.Add(certificateName, certificate);
} }
} }
} }
...@@ -151,9 +152,9 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -151,9 +152,9 @@ namespace Titanium.Web.Proxy.Helpers
{ {
store.Close(); store.Close();
if (certificates == null && if (certificates == null &&
certificateCache.ContainsKey(certificateName)) _certificateCache.ContainsKey(certificateName))
{ {
certificateCache.Remove(certificateName); _certificateCache.Remove(certificateName);
} }
} }
} }
...@@ -164,7 +165,7 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -164,7 +165,7 @@ namespace Titanium.Web.Proxy.Helpers
bool isRootCertificate = bool isRootCertificate =
(certificateName == RootCertificateName); (certificateName == RootCertificateName);
string certCreatArgs = string.Format(CERT_CREATE_FORMAT, string certCreatArgs = string.Format(CertCreateFormat,
store.Name, certificateName, Issuer, store.Name, certificateName, Issuer,
isRootCertificate ? "signature" : "exchange", isRootCertificate ? "signature" : "exchange",
isRootCertificate ? "authority" : "end", DateTime.Now, isRootCertificate ? "authority" : "end", DateTime.Now,
......
using System; using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
using System.Diagnostics.CodeAnalysis; using Ionic.Zlib;
namespace Titanium.Web.Proxy.Helpers namespace Titanium.Web.Proxy.Helpers
{ {
public class CompressionHelper public class CompressionHelper
{ {
private static readonly int BUFFER_SIZE = 8192; private const int BufferSize = 8192;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressZlib(byte[] bytes) public static byte[] CompressZlib(byte[] bytes)
{ {
using (var ms = new MemoryStream())
using (MemoryStream ms = new MemoryStream())
{ {
using (Ionic.Zlib.ZlibStream zip = new Ionic.Zlib.ZlibStream(ms, Ionic.Zlib.CompressionMode.Compress, true)) using (var zip = new ZlibStream(ms, CompressionMode.Compress, true))
{ {
zip.Write(bytes, 0, bytes.Length); zip.Write(bytes, 0, bytes.Length);
} }
...@@ -26,13 +22,12 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -26,13 +22,12 @@ namespace Titanium.Web.Proxy.Helpers
} }
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressDeflate(byte[] bytes) public static byte[] CompressDeflate(byte[] bytes)
{ {
using (var ms = new MemoryStream())
using (MemoryStream ms = new MemoryStream())
{ {
using (Ionic.Zlib.DeflateStream zip = new Ionic.Zlib.DeflateStream(ms, Ionic.Zlib.CompressionMode.Compress, true)) using (var zip = new DeflateStream(ms, CompressionMode.Compress, true))
{ {
zip.Write(bytes, 0, bytes.Length); zip.Write(bytes, 0, bytes.Length);
} }
...@@ -41,32 +36,31 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -41,32 +36,31 @@ namespace Titanium.Web.Proxy.Helpers
} }
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressGzip(byte[] bytes) public static byte[] CompressGzip(byte[] bytes)
{ {
using (var ms = new MemoryStream())
using (MemoryStream ms = new MemoryStream())
{ {
using (Ionic.Zlib.GZipStream zip = new Ionic.Zlib.GZipStream(ms, Ionic.Zlib.CompressionMode.Compress, true)) using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
{ {
zip.Write(bytes, 0, bytes.Length); zip.Write(bytes, 0, bytes.Length);
} }
return ms.ToArray(); return ms.ToArray();
} }
} }
public static byte[] DecompressGzip(Stream input) public static byte[] DecompressGzip(Stream input)
{ {
using (var decompressor = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress)) using (
var decompressor = new System.IO.Compression.GZipStream(input,
System.IO.Compression.CompressionMode.Decompress))
{ {
var buffer = new byte[BufferSize];
int read = 0; using (var output = new MemoryStream())
var buffer = new byte[BUFFER_SIZE];
using (MemoryStream output = new MemoryStream())
{ {
int read;
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0) while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{ {
output.Write(buffer, 0, read); output.Write(buffer, 0, read);
...@@ -78,13 +72,13 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -78,13 +72,13 @@ namespace Titanium.Web.Proxy.Helpers
public static byte[] DecompressDeflate(Stream input) public static byte[] DecompressDeflate(Stream input)
{ {
using (Ionic.Zlib.DeflateStream decompressor = new Ionic.Zlib.DeflateStream(input, Ionic.Zlib.CompressionMode.Decompress)) using (var decompressor = new DeflateStream(input, CompressionMode.Decompress))
{ {
int read = 0; var buffer = new byte[BufferSize];
var buffer = new byte[BUFFER_SIZE];
using (MemoryStream output = new MemoryStream()) using (var output = new MemoryStream())
{ {
int read;
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0) while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{ {
output.Write(buffer, 0, read); output.Write(buffer, 0, read);
...@@ -93,15 +87,16 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -93,15 +87,16 @@ namespace Titanium.Web.Proxy.Helpers
} }
} }
} }
public static byte[] DecompressZlib(Stream input) public static byte[] DecompressZlib(Stream input)
{ {
using (Ionic.Zlib.ZlibStream decompressor = new Ionic.Zlib.ZlibStream(input, Ionic.Zlib.CompressionMode.Decompress)) using (var decompressor = new ZlibStream(input, CompressionMode.Decompress))
{ {
int read = 0; var buffer = new byte[BufferSize];
var buffer = new byte[BUFFER_SIZE];
using (MemoryStream output = new MemoryStream()) using (var output = new MemoryStream())
{ {
int read;
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0) while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{ {
output.Write(buffer, 0, read); output.Write(buffer, 0, read);
...@@ -111,4 +106,4 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -111,4 +106,4 @@ namespace Titanium.Web.Proxy.Helpers
} }
} }
} }
} }
\ No newline at end of file
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
using System.Diagnostics; using System.Text;
namespace Titanium.Web.Proxy.Helpers namespace Titanium.Web.Proxy.Helpers
{ {
internal class CustomBinaryReader : BinaryReader internal class CustomBinaryReader : BinaryReader
{ {
internal CustomBinaryReader(Stream stream, Encoding encoding) internal CustomBinaryReader(Stream stream, Encoding encoding)
: base(stream, encoding) : base(stream, encoding)
{ {
} }
internal string ReadLine() internal string ReadLine()
{ {
char[] buf = new char[1]; var buf = new char[1];
StringBuilder readBuffer = new StringBuilder(); var readBuffer = new StringBuilder();
try try
{ {
var charsRead = 0; var lastChar = new char();
char lastChar = new char();
while ((charsRead = base.Read(buf, 0, 1)) > 0) while ((Read(buf, 0, 1)) > 0)
{ {
if (lastChar == '\r' && buf[0] == '\n') if (lastChar == '\r' && buf[0] == '\n')
{ {
return readBuffer.Remove(readBuffer.Length - 1, 1).ToString(); return readBuffer.Remove(readBuffer.Length - 1, 1).ToString();
} }
else if (buf[0] == '\0')
if (buf[0] == '\0') {
{ return readBuffer.ToString();
return readBuffer.ToString(); }
} readBuffer.Append(buf[0]);
else
readBuffer.Append(buf[0]);
lastChar = buf[0]; lastChar = buf[0];
} }
return readBuffer.ToString(); return readBuffer.ToString();
} }
catch (IOException) catch (IOException)
{ {
return readBuffer.ToString(); return readBuffer.ToString();
} }
catch (Exception)
{
throw;
}
} }
internal List<string> ReadAllLines() internal List<string> ReadAllLines()
{ {
string tmpLine = null; string tmpLine;
List<string> requestLines = new List<string>(); var requestLines = new List<string>();
while (!String.IsNullOrEmpty(tmpLine = ReadLine())) while (!string.IsNullOrEmpty(tmpLine = ReadLine()))
{ {
requestLines.Add(tmpLine); requestLines.Add(tmpLine);
} }
return requestLines; return requestLines;
} }
} }
} }
\ No newline at end of file
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
namespace Titanium.Web.Proxy.Helpers namespace Titanium.Web.Proxy.Helpers
...@@ -12,21 +9,23 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -12,21 +9,23 @@ namespace Titanium.Web.Proxy.Helpers
{ {
try try
{ {
DirectoryInfo[] myProfileDirectory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Mozilla\\Firefox\\Profiles\\").GetDirectories("*.default"); var myProfileDirectory =
string myFFPrefFile = myProfileDirectory[0].FullName + "\\prefs.js"; new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
if (File.Exists(myFFPrefFile)) "\\Mozilla\\Firefox\\Profiles\\").GetDirectories("*.default");
var myFfPrefFile = myProfileDirectory[0].FullName + "\\prefs.js";
if (File.Exists(myFfPrefFile))
{ {
// We have a pref file so let''s make sure it has the proxy setting // We have a pref file so let''s make sure it has the proxy setting
StreamReader myReader = new StreamReader(myFFPrefFile); var myReader = new StreamReader(myFfPrefFile);
string myPrefContents = myReader.ReadToEnd(); var myPrefContents = myReader.ReadToEnd();
myReader.Close(); myReader.Close();
if (myPrefContents.Contains("user_pref(\"network.proxy.type\", 0);")) if (myPrefContents.Contains("user_pref(\"network.proxy.type\", 0);"))
{ {
// Add the proxy enable line and write it back to the file // Add the proxy enable line and write it back to the file
myPrefContents = myPrefContents.Replace("user_pref(\"network.proxy.type\", 0);", ""); myPrefContents = myPrefContents.Replace("user_pref(\"network.proxy.type\", 0);", "");
File.Delete(myFFPrefFile); File.Delete(myFfPrefFile);
File.WriteAllText(myFFPrefFile, myPrefContents); File.WriteAllText(myFfPrefFile, myPrefContents);
} }
} }
} }
...@@ -35,25 +34,28 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -35,25 +34,28 @@ namespace Titanium.Web.Proxy.Helpers
// Only exception should be a read/write error because the user opened up FireFox so they can be ignored. // Only exception should be a read/write error because the user opened up FireFox so they can be ignored.
} }
} }
public static void RemoveFirefox() public static void RemoveFirefox()
{ {
try try
{ {
DirectoryInfo[] myProfileDirectory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Mozilla\\Firefox\\Profiles\\").GetDirectories("*.default"); var myProfileDirectory =
string myFFPrefFile = myProfileDirectory[0].FullName + "\\prefs.js"; new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
if (File.Exists(myFFPrefFile)) "\\Mozilla\\Firefox\\Profiles\\").GetDirectories("*.default");
var myFfPrefFile = myProfileDirectory[0].FullName + "\\prefs.js";
if (File.Exists(myFfPrefFile))
{ {
// We have a pref file so let''s make sure it has the proxy setting // We have a pref file so let''s make sure it has the proxy setting
StreamReader myReader = new StreamReader(myFFPrefFile); var myReader = new StreamReader(myFfPrefFile);
string myPrefContents = myReader.ReadToEnd(); var myPrefContents = myReader.ReadToEnd();
myReader.Close(); myReader.Close();
if (!myPrefContents.Contains("user_pref(\"network.proxy.type\", 0);")) if (!myPrefContents.Contains("user_pref(\"network.proxy.type\", 0);"))
{ {
// Add the proxy enable line and write it back to the file // Add the proxy enable line and write it back to the file
myPrefContents = myPrefContents + "\n\r" + "user_pref(\"network.proxy.type\", 0);"; myPrefContents = myPrefContents + "\n\r" + "user_pref(\"network.proxy.type\", 0);";
File.Delete(myFFPrefFile); File.Delete(myFfPrefFile);
File.WriteAllText(myFFPrefFile, myPrefContents); File.WriteAllText(myFfPrefFile, myPrefContents);
} }
} }
} }
...@@ -63,4 +65,4 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -63,4 +65,4 @@ namespace Titanium.Web.Proxy.Helpers
} }
} }
} }
} }
\ No newline at end of file
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Configuration; using System.Net.Configuration;
using System.Reflection; using System.Reflection;
using System.Text;
namespace Titanium.Web.Proxy.Helpers namespace Titanium.Web.Proxy.Helpers
{ {
...@@ -11,25 +8,24 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -11,25 +8,24 @@ namespace Titanium.Web.Proxy.Helpers
{ {
//Fix bug in .Net 4.0 HttpWebRequest (don't use this for 4.5 and above) //Fix bug in .Net 4.0 HttpWebRequest (don't use this for 4.5 and above)
//http://stackoverflow.com/questions/856885/httpwebrequest-to-url-with-dot-at-the-end //http://stackoverflow.com/questions/856885/httpwebrequest-to-url-with-dot-at-the-end
public static void URLPeriodFix() public static void UrlPeriodFix()
{ {
MethodInfo getSyntax = typeof(UriParser).GetMethod("GetSyntax", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); var getSyntax = typeof (UriParser).GetMethod("GetSyntax", BindingFlags.Static | BindingFlags.NonPublic);
FieldInfo flagsField = typeof(UriParser).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); var flagsField = typeof (UriParser).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
if (getSyntax != null && flagsField != null) if (getSyntax != null && flagsField != null)
{ {
foreach (string scheme in new[] { "http", "https" }) foreach (var scheme in new[] {"http", "https"})
{ {
UriParser parser = (UriParser)getSyntax.Invoke(null, new object[] { scheme }); var parser = (UriParser) getSyntax.Invoke(null, new object[] {scheme});
if (parser != null) if (parser != null)
{ {
int flagsValue = (int)flagsField.GetValue(parser); var flagsValue = (int) flagsField.GetValue(parser);
if ((flagsValue & 0x1000000) != 0) if ((flagsValue & 0x1000000) != 0)
flagsField.SetValue(parser, flagsValue & ~0x1000000); flagsField.SetValue(parser, flagsValue & ~0x1000000);
} }
} }
} }
} }
// Enable/disable useUnsafeHeaderParsing. // Enable/disable useUnsafeHeaderParsing.
...@@ -37,31 +33,32 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -37,31 +33,32 @@ namespace Titanium.Web.Proxy.Helpers
public static bool ToggleAllowUnsafeHeaderParsing(bool enable) public static bool ToggleAllowUnsafeHeaderParsing(bool enable)
{ {
//Get the assembly that contains the internal class //Get the assembly that contains the internal class
Assembly assembly = Assembly.GetAssembly(typeof(SettingsSection)); var assembly = Assembly.GetAssembly(typeof (SettingsSection));
if (assembly != null) if (assembly != null)
{ {
//Use the assembly in order to get the internal type for the internal class //Use the assembly in order to get the internal type for the internal class
Type settingsSectionType = assembly.GetType("System.Net.Configuration.SettingsSectionInternal"); var settingsSectionType = assembly.GetType("System.Net.Configuration.SettingsSectionInternal");
if (settingsSectionType != null) if (settingsSectionType != null)
{ {
//Use the internal static property to get an instance of the internal settings class. //Use the internal static property to get an instance of the internal settings class.
//If the static instance isn't created already invoking the property will create it for us. //If the static instance isn't created already invoking the property will create it for us.
object anInstance = settingsSectionType.InvokeMember("Section", var anInstance = settingsSectionType.InvokeMember("Section",
BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { }); BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null,
new object[] {});
if (anInstance != null) if (anInstance != null)
{ {
//Locate the private bool field that tells the framework if unsafe header parsing is allowed //Locate the private bool field that tells the framework if unsafe header parsing is allowed
FieldInfo aUseUnsafeHeaderParsing = settingsSectionType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance); var aUseUnsafeHeaderParsing = settingsSectionType.GetField("useUnsafeHeaderParsing",
BindingFlags.NonPublic | BindingFlags.Instance);
if (aUseUnsafeHeaderParsing != null) if (aUseUnsafeHeaderParsing != null)
{ {
aUseUnsafeHeaderParsing.SetValue(anInstance, enable); aUseUnsafeHeaderParsing.SetValue(anInstance, enable);
return true; return true;
} }
} }
} }
} }
return false; return false;
} }
} }
} }
\ No newline at end of file
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Titanium.Web.Proxy.Helpers namespace Titanium.Web.Proxy.Helpers
{ {
internal static class NativeMethods internal static class NativeMethods
{ {
[DllImport("wininet.dll")] [DllImport("wininet.dll")]
internal static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength); internal static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer,
int dwBufferLength);
} }
public static class SystemProxyHelper public static class SystemProxyHelper
{ {
public const int InternetOptionSettingsChanged = 39;
public const int InternetOptionRefresh = 37;
private static object _prevProxyServer;
private static object _prevProxyEnable;
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39; public static void EnableProxyHttp(string hostname, int port)
public const int INTERNET_OPTION_REFRESH = 37;
static bool settingsReturn, refreshReturn;
static object prevProxyServer;
static object prevProxyEnable;
public static void EnableProxyHTTP(string hostname, int port)
{ {
RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true); var reg = Registry.CurrentUser.OpenSubKey(
prevProxyEnable = reg.GetValue("ProxyEnable"); "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
prevProxyServer = reg.GetValue("ProxyServer"); if (reg != null)
reg.SetValue("ProxyEnable", 1); {
reg.SetValue("ProxyServer", "http=" + hostname + ":" + port + ";"); _prevProxyEnable = reg.GetValue("ProxyEnable");
refresh(); _prevProxyServer = reg.GetValue("ProxyServer");
reg.SetValue("ProxyEnable", 1);
reg.SetValue("ProxyServer", "http=" + hostname + ":" + port + ";");
}
Refresh();
} }
public static void EnableProxyHTTPS(string hostname, int port)
public static void EnableProxyHttps(string hostname, int port)
{ {
RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true); var reg = Registry.CurrentUser.OpenSubKey(
reg.SetValue("ProxyEnable", 1); "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
reg.SetValue("ProxyServer", "http=" + hostname + ":" + port + ";https=" + hostname + ":" + port); if (reg != null)
refresh(); {
reg.SetValue("ProxyEnable", 1);
reg.SetValue("ProxyServer", "http=" + hostname + ":" + port + ";https=" + hostname + ":" + port);
}
Refresh();
} }
public static void DisableAllProxy() public static void DisableAllProxy()
{ {
RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true); var reg = Registry.CurrentUser.OpenSubKey(
reg.SetValue("ProxyEnable", prevProxyEnable); "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
if (prevProxyServer != null) if (reg != null)
reg.SetValue("ProxyServer", prevProxyServer); {
refresh(); reg.SetValue("ProxyEnable", _prevProxyEnable);
if (_prevProxyServer != null)
reg.SetValue("ProxyServer", _prevProxyServer);
}
Refresh();
} }
private static void refresh()
private static void Refresh()
{ {
settingsReturn = NativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0); NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionSettingsChanged, IntPtr.Zero,0);
refreshReturn = NativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0); NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionRefresh, IntPtr.Zero, 0);
} }
} }
} }
\ No newline at end of file
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Text;
using System.Net.Security; using System.Net.Security;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Titanium.Web.Proxy.Extensions; using Titanium.Web.Proxy.Extensions;
using Titanium.Web.Proxy.Models; using Titanium.Web.Proxy.Models;
...@@ -15,9 +14,9 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -15,9 +14,9 @@ namespace Titanium.Web.Proxy.Helpers
public class TcpHelper public class TcpHelper
{ {
private static readonly int BUFFER_SIZE = 8192; private static readonly int BUFFER_SIZE = 8192;
private static readonly String[] colonSpaceSplit = new string[] { ": " };
public static void SendRaw(Stream clientStream, string httpCmd, List<HttpHeader> requestHeaders, string hostName,
public static void SendRaw(Stream clientStream, string httpCmd, List<HttpHeader> requestHeaders, string hostName, int tunnelPort, bool isHttps) int tunnelPort, bool isHttps)
{ {
StringBuilder sb = null; StringBuilder sb = null;
if (httpCmd != null || requestHeaders != null) if (httpCmd != null || requestHeaders != null)
...@@ -29,23 +28,22 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -29,23 +28,22 @@ namespace Titanium.Web.Proxy.Helpers
sb.Append(Environment.NewLine); sb.Append(Environment.NewLine);
} }
if (requestHeaders != null) if (requestHeaders != null)
for (int i = 0; i < requestHeaders.Count; i++) foreach (var header in requestHeaders.Select(t => t.ToString()))
{ {
var header = requestHeaders[i].ToString(); sb.Append(header);
sb.Append(header); sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine); }
}
sb.Append(Environment.NewLine); sb.Append(Environment.NewLine);
} }
System.Net.Sockets.TcpClient tunnelClient = null;
TcpClient tunnelClient = null;
Stream tunnelStream = null; Stream tunnelStream = null;
try try
{ {
tunnelClient = new System.Net.Sockets.TcpClient(hostName, tunnelPort); tunnelClient = new TcpClient(hostName, tunnelPort);
tunnelStream = tunnelClient.GetStream() as Stream; tunnelStream = tunnelClient.GetStream();
if (isHttps) if (isHttps)
{ {
...@@ -60,12 +58,15 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -60,12 +58,15 @@ namespace Titanium.Web.Proxy.Helpers
{ {
if (sslStream != null) if (sslStream != null)
sslStream.Dispose(); sslStream.Dispose();
throw;
} }
} }
var sendRelay = Task.Factory.StartNew(() => { var sendRelay = Task.Factory.StartNew(() =>
if(sb!=null) {
if (sb != null)
clientStream.CopyToAsync(sb.ToString(), tunnelStream, BUFFER_SIZE); clientStream.CopyToAsync(sb.ToString(), tunnelStream, BUFFER_SIZE);
else else
clientStream.CopyToAsync(tunnelStream, BUFFER_SIZE); clientStream.CopyToAsync(tunnelStream, BUFFER_SIZE);
...@@ -89,7 +90,5 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -89,7 +90,5 @@ namespace Titanium.Web.Proxy.Helpers
throw; throw;
} }
} }
} }
} }
\ No newline at end of file
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Titanium.Web.Proxy.Models namespace Titanium.Web.Proxy.Models
{ {
public class HttpHeader public class HttpHeader
{ {
public string Name { get; set; }
public string Value { get; set; }
public HttpHeader(string name, string value) public HttpHeader(string name, string value)
{ {
if (string.IsNullOrEmpty(name)) throw new Exception("Name cannot be null"); if (string.IsNullOrEmpty(name)) throw new Exception("Name cannot be null");
this.Name = name.Trim(); Name = name.Trim();
this.Value = value.Trim(); Value = value.Trim();
} }
public string Name { get; set; }
public string Value { get; set; }
public override string ToString() public override string ToString()
{ {
return String.Format("{0}: {1}", this.Name, this.Value); return string.Format("{0}: {1}", Name, Value);
} }
} }
} }
\ No newline at end of file
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
// associated with an assembly. // associated with an assembly.
[assembly: AssemblyTitle("Titanium.Web.Proxy.Properties")] [assembly: AssemblyTitle("Titanium.Web.Proxy.Properties")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
...@@ -17,9 +17,11 @@ using System.Runtime.InteropServices; ...@@ -17,9 +17,11 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible // Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from // to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. // COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM // The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5036e0b7-a0d0-4070-8eb0-72c129dee9b3")] [assembly: Guid("5036e0b7-a0d0-4070-8eb0-72c129dee9b3")]
// Version information for an assembly consists of the following four values: // Version information for an assembly consists of the following four values:
...@@ -29,5 +31,6 @@ using System.Runtime.InteropServices; ...@@ -29,5 +31,6 @@ using System.Runtime.InteropServices;
// Build Number // Build Number
// Revision // Revision
// //
[assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
\ No newline at end of file
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.IO;
using System.Net; using System.Net;
using System.Net.Sockets;
using System.Net.Security; using System.Net.Security;
using System.Security.Authentication; using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Diagnostics; using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Titanium.Web.Proxy.EventArguments; 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
{ {
/// <summary> /// <summary>
/// Proxy Server Main class /// Proxy Server Main class
/// </summary> /// </summary>
public partial class ProxyServer public partial class ProxyServer
{ {
private static readonly int BUFFER_SIZE = 8192; private static readonly int BUFFER_SIZE = 8192;
private static readonly char[] semiSplit = new char[] { ';' }; private static readonly char[] SemiSplit = {';'};
private static readonly String[] colonSpaceSplit = new string[] { ": " }; private static readonly string[] ColonSpaceSplit = {": "};
private static readonly char[] spaceSplit = new char[] { ' ' }; private static readonly char[] SpaceSplit = {' '};
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[] 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 readonly byte[] ChunkEnd =
Encoding.ASCII.GetBytes(0.ToString("x2") + Environment.NewLine + Environment.NewLine);
private static TcpListener listener; private static TcpListener _listener;
private static CertificateManager CertManager { get; set; }
public static List<string> ExcludedHttpsHostNameRegex = new List<string>(); public static List<string> ExcludedHttpsHostNameRegex = new List<string>();
public static event EventHandler<SessionEventArgs> BeforeRequest;
public static event EventHandler<SessionEventArgs> BeforeResponse;
public static string RootCertificateName { get; set; }
public static bool EnableSSL { get; set; }
public static bool SetAsSystemProxy { get; set; }
public static Int32 ListeningPort { get; set; }
public static IPAddress ListeningIpAddress { get; set; }
static ProxyServer() static ProxyServer()
{ {
CertManager = new CertificateManager("Titanium", CertManager = new CertificateManager("Titanium",
...@@ -61,74 +45,89 @@ namespace Titanium.Web.Proxy ...@@ -61,74 +45,89 @@ namespace Titanium.Web.Proxy
Initialize(); Initialize();
} }
private static CertificateManager CertManager { get; set; }
public static string RootCertificateName { get; set; }
public static bool EnableSsl { get; set; }
public static bool SetAsSystemProxy { get; set; }
public static int ListeningPort { get; set; }
public static IPAddress ListeningIpAddress { get; set; }
public static event EventHandler<SessionEventArgs> BeforeRequest;
public static event EventHandler<SessionEventArgs> BeforeResponse;
public static void Initialize() public static void Initialize()
{ {
ServicePointManager.Expect100Continue = false;
System.Net.ServicePointManager.Expect100Continue = false; WebRequest.DefaultWebProxy = null;
System.Net.WebRequest.DefaultWebProxy = null; ServicePointManager.DefaultConnectionLimit = 10;
System.Net.ServicePointManager.DefaultConnectionLimit = 10; ServicePointManager.DnsRefreshTimeout = 3*60*1000; //3 minutes
ServicePointManager.DnsRefreshTimeout = 3 * 60 * 1000;//3 minutes ServicePointManager.MaxServicePointIdleTime = 3*60*1000;
ServicePointManager.MaxServicePointIdleTime = 3 * 60 * 1000;
//HttpWebRequest certificate validation callback //HttpWebRequest certificate validation callback
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) ServicePointManager.ServerCertificateValidationCallback =
{ delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
if (sslPolicyErrors == SslPolicyErrors.None) return true; {
else if (sslPolicyErrors == SslPolicyErrors.None) return true;
return false; return false;
}; };
//Fix a bug in .NET 4.0 //Fix a bug in .NET 4.0
NetFrameworkHelper.URLPeriodFix(); NetFrameworkHelper.UrlPeriodFix();
//useUnsafeHeaderParsing //useUnsafeHeaderParsing
NetFrameworkHelper.ToggleAllowUnsafeHeaderParsing(true); NetFrameworkHelper.ToggleAllowUnsafeHeaderParsing(true);
} }
public static bool Start() public static bool Start()
{ {
listener = new TcpListener(ListeningIpAddress, ListeningPort); _listener = new TcpListener(ListeningIpAddress, ListeningPort);
listener.Start(); _listener.Start();
ListeningPort = ((IPEndPoint)listener.LocalEndpoint).Port; ListeningPort = ((IPEndPoint) _listener.LocalEndpoint).Port;
// accept clients asynchronously // accept clients asynchronously
listener.BeginAcceptTcpClient(OnAcceptConnection, listener); _listener.BeginAcceptTcpClient(OnAcceptConnection, _listener);
if (SetAsSystemProxy) if (SetAsSystemProxy)
{ {
SystemProxyHelper.EnableProxyHTTP(ListeningIpAddress == IPAddress.Any ? "127.0.0.1" : ListeningIpAddress.ToString(), ListeningPort); SystemProxyHelper.EnableProxyHttp(
Equals(ListeningIpAddress, IPAddress.Any) ? "127.0.0.1" : ListeningIpAddress.ToString(), ListeningPort);
FireFoxHelper.AddFirefox(); FireFoxHelper.AddFirefox();
if (EnableSSL) if (EnableSsl)
{ {
RootCertificateName = RootCertificateName == null ? "Titanium_Proxy_Test_Root" : RootCertificateName; RootCertificateName = RootCertificateName ?? "Titanium_Proxy_Test_Root";
bool certTrusted = CertManager.CreateTrustedRootCertificate(); var certTrusted = CertManager.CreateTrustedRootCertificate();
//If certificate was trusted by the machine //If certificate was trusted by the machine
if (certTrusted) if (certTrusted)
{ {
SystemProxyHelper.EnableProxyHTTPS(ListeningIpAddress == IPAddress.Any ? "127.0.0.1" : ListeningIpAddress.ToString(), ListeningPort); SystemProxyHelper.EnableProxyHttps(
Equals(ListeningIpAddress, IPAddress.Any) ? "127.0.0.1" : ListeningIpAddress.ToString(),
ListeningPort);
} }
} }
} }
return true; return true;
} }
private static void OnAcceptConnection(IAsyncResult asyn) private static void OnAcceptConnection(IAsyncResult asyn)
{ {
try try
{ {
// Get the listener that handles the client request. // Get the listener that handles the client request.
listener.BeginAcceptTcpClient(OnAcceptConnection, listener); _listener.BeginAcceptTcpClient(OnAcceptConnection, _listener);
TcpClient client = listener.EndAcceptTcpClient(asyn); var client = _listener.EndAcceptTcpClient(asyn);
Task.Factory.StartNew(() => HandleClient(client)); Task.Factory.StartNew(() => HandleClient(client));
} }
catch { } catch
{
// ignored
}
} }
...@@ -140,9 +139,8 @@ namespace Titanium.Web.Proxy ...@@ -140,9 +139,8 @@ namespace Titanium.Web.Proxy
FireFoxHelper.RemoveFirefox(); FireFoxHelper.RemoveFirefox();
} }
listener.Stop(); _listener.Stop();
CertManager.Dispose(); CertManager.Dispose();
} }
} }
} }
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="DotNetZip" version="1.9.3" targetFramework="net40-Client" /> <package id="DotNetZip" version="1.9.3" targetFramework="net40-Client" />
</packages> </packages>
\ No newline at end of file
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