Commit 4c3121ed authored by titanium007's avatar titanium007

Replace HttpWebRequest with Custom Request Class

parent 606fe644
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
......
Titanium
========
A light weight http(s) proxy server written in C#
[![titanium MyGet Build Status](https://www.myget.org/BuildSource/Badge/titanium?identifier=36bd545d-87aa-4c0c-ae98-6de9a078b016)](https://www.myget.org/)
Kindly report only issues/bugs here . For programming help or questions use [StackOverflow](http://stackoverflow.com/questions/tagged/titanium-web-proxy) with the tag Titanium-Web-Proxy.
![alt tag](https://raw.githubusercontent.com/titanium007/Titanium/master/Titanium.Web.Proxy.Test/Capture.PNG)
Features
========
* Supports Http(s) and all features of HTTP 1.1
* Supports relaying of WebSockets
* Supports script injection
* Async using HttpWebRequest class for better performance
Usage
=====
Refer the HTTP Proxy Server library in your project, look up Test project to learn usage.
Install by nuget:
Install-Package Titanium.Web.Proxy
After installing nuget package mark following files to be copied to app directory
* makecert.exe
* Titanium_Proxy_Test_Root.cer
Setup HTTP proxy:
```csharp
// listen to client request & server response events
ProxyServer.BeforeRequest += OnRequest;
ProxyServer.BeforeResponse += OnResponse;
ProxyServer.EnableSSL = true;
ProxyServer.SetAsSystemProxy = true;
ProxyServer.Start();
//wait here (You can use something else as a wait function, I am using this as a demo)
Console.Read();
//Unsubscribe & Quit
ProxyServer.BeforeRequest -= OnRequest;
ProxyServer.BeforeResponse -= OnResponse;
ProxyServer.Stop();
```
Sample request and response event handlers
```csharp
//Test On Request, intercept requests
public void OnRequest(object sender, SessionEventArgs e)
{
Console.WriteLine(e.RequestURL);
//read request headers
var requestHeaders = e.RequestHeaders;
if ((e.RequestMethod.ToUpper() == "POST" || e.RequestMethod.ToUpper() == "PUT") && e.RequestContentLength > 0)
{
//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
if (e.RequestURL.Contains("google.com"))
{
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)
{
//read response headers
var responseHeaders = e.ResponseHeaders;
if (e.ResponseStatusCode == HttpStatusCode.OK)
{
if (e.ResponseContentType.Trim().ToLower().Contains("text/html"))
{
//Get/Set response body bytes
byte[] responseBodyBytes = e.GetResponseBody();
e.SetResponseBody(responseBodyBytes);
//Get response body as string
string responseBody = e.GetResponseBodyAsString();
//Modify e.ServerResponse
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);
This project is still in progress. This will be updated once the project is stable.
//Set modifed response Html Body
e.SetResponseBodyString(modified);
}
}
}
```
Future updates
============
* Support mutual authentication
* Support HTTP 2.0
* Support modification of web socket requests
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Titanium.Web.Http.Tests
{
class Program
{
static void Main(string[] args)
{
var t = Task.Factory.StartNew(Test);
t.Wait();
Console.Read();
}
public static async void Test()
{
var s = new HttpClient
{
Method = "GET",
Uri = new Uri("https://google.com"),
Version = "HTTP/1.1"
};
s.RequestHeaders.Add(new HttpHeader("Host", s.Uri.Host));
await s.SendRequest();
await s.ReceiveResponse();
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Titanium.Web.Http.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Titanium.Web.Http.Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ef2b516c-1cc2-4688-af05-0758b40bb9df")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{95550A47-B2D2-43C4-8E79-17BDF09B797F}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Titanium.Web.Http.Tests</RootNamespace>
<AssemblyName>Titanium.Web.Http.Tests</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions.Desktop">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.IO">
<HintPath>..\packages\Microsoft.Bcl.1.1.8\lib\net40\System.IO.dll</HintPath>
</Reference>
<Reference Include="System.Net" />
<Reference Include="System.Runtime">
<HintPath>..\packages\Microsoft.Bcl.1.1.8\lib\net40\System.Runtime.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.1.1.8\lib\net40\System.Threading.Tasks.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Titanium.Web.Http\Titanium.Web.Http.csproj">
<Project>{51f8273a-39e4-4c9f-9972-bc78f8b3b32e}</Project>
<Name>Titanium.Web.Http</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
<Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
<Error Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" /></startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl" version="1.1.8" targetFramework="net40" />
<package id="Microsoft.Bcl.Async" version="1.0.168" targetFramework="net40" />
<package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net40" />
</packages>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Titanium.Web.Http
{
public class HttpStreamReader
{
public async static Task<string> ReadLine(Stream stream)
{
var buf = new byte[2];
var readBuffer = new StringBuilder();
try
{
while ((await stream.ReadAsync(buf, 0, 2)) > 0)
{
var charRead = System.Text.Encoding.ASCII.GetString(buf);
if (charRead == Environment.NewLine)
{
return readBuffer.ToString();
}
readBuffer.Append(charRead);
}
return readBuffer.ToString();
}
catch (IOException)
{
return readBuffer.ToString();
}
}
public async static Task<List<string>> ReadAllLines(Stream stream)
{
string tmpLine;
var requestLines = new List<string>();
while (!string.IsNullOrEmpty(tmpLine = await ReadLine(stream)))
{
requestLines.Add(tmpLine);
}
return requestLines;
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Instrumentation;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Titanium.Web.Http
{
public class HttpClient
{
const string Space = " ";
public string Method { get; set; }
public Uri Uri { get; set; }
public string Version { get; set; }
public List<HttpHeader> RequestHeaders { get; set; }
public bool IsSecure
{
get { return this.Uri.Scheme == Uri.UriSchemeHttps; }
}
public TcpClient Client { get; set; }
public Stream Stream { get; set; }
public HttpClient()
{
RequestHeaders = new List<HttpHeader>();
ResponseHeaders = new List<HttpHeader>();
}
public async Task<Stream> GetStream()
{
if (Stream == null)
{
Client = new TcpClient(Uri.Host, Uri.Port);
Stream = Client.GetStream();
if (IsSecure)
{
SslStream sslStream = null;
try
{
sslStream = new SslStream(Stream);
await sslStream.AuthenticateAsClientAsync(Uri.Host);
Stream = sslStream;
}
catch
{
if (sslStream != null)
sslStream.Dispose();
throw;
}
}
}
return Stream;
}
public async Task SendRequest()
{
await GetStream();
var requestLines = new StringBuilder();
requestLines.Append(string.Join(Space, Method, Uri.AbsolutePath, Version));
requestLines.AppendLine();
foreach (var header in RequestHeaders)
{
requestLines.Append(header.Name + ':' + header.Value);
requestLines.AppendLine();
requestLines.AppendLine();
}
var request = requestLines.ToString();
var requestBytes = Encoding.ASCII.GetBytes(request);
await Stream.WriteAsync(requestBytes, 0, requestBytes.Length);
await Stream.FlushAsync();
}
public string Status { get; set; }
public List<HttpHeader> ResponseHeaders { get; set; }
public async Task ReceiveResponse()
{
var responseLines = await HttpStreamReader.ReadAllLines(Stream);
var responseStatus = responseLines[0].Split(' ');
Status = responseStatus[1] + Space + responseStatus[2];
for (int i = 1; i < responseLines.Count; i++)
{
var header = responseLines[i].Split(':');
ResponseHeaders.Add(new HttpHeader(header[0], header[1]));
}
}
public void Abort()
{
throw new NotImplementedException();
}
public int ContentLength { get; set; }
public bool SendChunked { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Titanium.Web.Http
{
public class HttpHeader
{
public HttpHeader(string name, string value)
{
if (string.IsNullOrEmpty(name)) throw new Exception("Name cannot be null");
Name = name.Trim();
Value = value.Trim();
}
public string Name { get; set; }
public string Value { get; set; }
public override string ToString()
{
return string.Format("{0}: {1}", Name, Value);
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Titanium.Web.Http")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Titanium.Web.Http")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e951d607-dfa6-43b2-ad9a-8dcdea29a0f1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{51F8273A-39E4-4C9F-9972-BC78F8B3B32E}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Titanium.Web.Http</RootNamespace>
<AssemblyName>Titanium.Web.Http</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions.Desktop">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.IO">
<HintPath>..\packages\Microsoft.Bcl.1.1.8\lib\net40\System.IO.dll</HintPath>
</Reference>
<Reference Include="System.Net" />
<Reference Include="System.Runtime">
<HintPath>..\packages\Microsoft.Bcl.1.1.8\lib\net40\System.Runtime.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.1.1.8\lib\net40\System.Threading.Tasks.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CustomBinaryReader.cs" />
<Compile Include="HttpHeader.cs" />
<Compile Include="HttpClient.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
<Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
<Error Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl" version="1.1.8" targetFramework="net40" />
<package id="Microsoft.Bcl.Async" version="1.0.168" targetFramework="net40" />
<package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net40" />
</packages>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="SqlCELogConnectionString" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=Log.sdf" />
<add name="SqlCEEventsConnectionString" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=Events.sdf" />
<add name="SqlCEFilesConnectionString" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=Files.sdf" />
<add name="SqlServerLogConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ASXLog;Integrated Security=True;Enlist=False;" providerName="System.Data.SqlClient" />
<add name="SqlServerEventsConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ASXEvents;Integrated Security=True;Enlist=False;" providerName="System.Data.SqlClient" />
<add name="SqlServerFilesConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ASXFiles;Integrated Security=True;Enlist=False;" providerName="System.Data.SqlClient" />
<add name="SqlServerSettingsConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ASXSettings;Integrated Security=True;Enlist=False;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
<unity configSource="unity.debug.xml" />
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" /></startup></configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
\ No newline at end of file
Titanium.Web.Proxy.Test/Capture.PNG

23.8 KB | W: | H:

Titanium.Web.Proxy.Test/Capture.PNG

51.5 KB | W: | H:

Titanium.Web.Proxy.Test/Capture.PNG
Titanium.Web.Proxy.Test/Capture.PNG
Titanium.Web.Proxy.Test/Capture.PNG
Titanium.Web.Proxy.Test/Capture.PNG
  • 2-up
  • Swipe
  • Onion skin
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Titanium.Web.Proxy.Helpers;
namespace Titanium.Web.Proxy.Test
{
public class Program
{
static ProxyTestController controller = new ProxyTestController();
private static readonly ProxyTestController Controller = new ProxyTestController();
public static void Main(string[] args)
{
//On Console exit make sure we also exit the proxy
handler = new ConsoleEventDelegate(ConsoleEventCallback);
SetConsoleCtrlHandler(handler, true);
NativeMethods.Handler = ConsoleEventCallback;
NativeMethods.SetConsoleCtrlHandler(NativeMethods.Handler, true);
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):");
if (Console.ReadLine().Trim().ToLower() == "y")
var line = Console.ReadLine();
if (line != null && line.Trim().ToLower() == "y")
{
controller.SetAsSystemProxy = true;
Controller.SetAsSystemProxy = true;
}
controller.Visited += PageVisited;
//Start proxy controller
controller.StartProxy();
Controller.StartProxy();
Console.WriteLine("Hit any key to exit..");
Console.WriteLine();
Console.WriteLine();
Console.Read();
controller.Stop();
Controller.Stop();
}
private static void PageVisited(VisitedEventArgs e)
{
Console.WriteLine(string.Concat("Visited: ", e.URL));
}
static bool ConsoleEventCallback(int eventType)
private static bool ConsoleEventCallback(int eventType)
{
if (eventType == 2)
if (eventType != 2) return false;
try
{
try
{
controller.Stop();
}
catch { }
Controller.Stop();
}
catch
{
// ignored
}
return false;
}
}
internal static class NativeMethods
{
// Keeps it from getting garbage collected
private static ConsoleEventDelegate handler;
// Pinvoke
private delegate bool ConsoleEventDelegate(int eventType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
internal static ConsoleEventDelegate Handler;
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
// Pinvoke
internal delegate bool ConsoleEventDelegate(int eventType);
}
}
}
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Demo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
......@@ -17,9 +17,11 @@ using System.Runtime.InteropServices;
// 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
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("33a2109d-0312-4c94-aa51-fbb2a83e63ab")]
// Version information for an assembly consists of the following four values:
......@@ -32,5 +34,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.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.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.Models;
using Titanium.Web.Proxy;
using Titanium.Web.Proxy.Helpers;
using Titanium.Web.Proxy.EventArguments;
namespace Titanium.Web.Proxy.Test
{
public partial class ProxyTestController
public class ProxyTestController
{
private List<string> _URLList = new List<string>();
private string _lastURL = string.Empty;
public int ListeningPort { get; set; }
public bool EnableSSL { get; set; }
public bool EnableSsl { get; set; }
public bool SetAsSystemProxy { get; set; }
public void StartProxy()
{
ProxyServer.BeforeRequest += OnRequest;
ProxyServer.BeforeResponse += OnResponse;
if(Visited!=null)
{
ProxyServer.BeforeRequest += OnRequest;
ProxyServer.BeforeResponse += OnResponse;
}
ProxyServer.EnableSsl = EnableSsl;
ProxyServer.EnableSSL = EnableSSL;
ProxyServer.SetAsSystemProxy = SetAsSystemProxy;
ProxyServer.SetAsSystemProxy = SetAsSystemProxy;
//Exclude Https addresses you don't want to proxy
//Usefull for clients that use certificate pinning
//for example dropbox.com
ProxyServer.ExcludedHttpsHostNameRegex.Add(".dropbox.com");
ProxyServer.Start();
ProxyServer.ListeningPort = ProxyServer.ListeningPort;
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()
{
if (Visited!=null)
{
ProxyServer.BeforeRequest -= OnRequest;
ProxyServer.BeforeResponse -= OnResponse;
}
ProxyServer.Stop();
}
ProxyServer.BeforeRequest -= OnRequest;
ProxyServer.BeforeResponse -= OnResponse;
public delegate void SiteVisitedEventHandler(VisitedEventArgs e);
public event SiteVisitedEventHandler Visited;
ProxyServer.Stop();
}
// Invoke the Changed event; called whenever list changes
protected virtual void OnChanged(VisitedEventArgs e)
{
if (Visited != null)
Visited(e);
}
//Test On Request, intecept requests
//Read browser URL send back to proxy by the injection script in OnResponse event
public void OnRequest(object sender, SessionEventArgs e)
{
string Random = e.RequestURL.Substring(e.RequestURL.LastIndexOf(@"/") + 1);
int index = _URLList.IndexOf(Random);
if (index >= 0)
{
Console.WriteLine(e.RequestUrl);
////read request headers
//var requestHeaders = e.RequestHeaders;
//if ((e.RequestMethod.ToUpper() == "POST" || e.RequestMethod.ToUpper() == "PUT"))
//{
// //Get/Set request body bytes
// byte[] bodyBytes = e.GetRequestBody();
// e.SetRequestBody(bodyBytes);
string URL = e.GetRequestHtmlBody();
// //Get/Set request body as string
// string bodyString = e.GetRequestBodyAsString();
// e.SetRequestBodyString(bodyString);
if (_lastURL != URL)
{
OnChanged(new VisitedEventArgs() { hostname = e.RequestHostname, URL = URL, remoteIP = e.ClientIpAddress, remotePort = e.ClientPort });
//}
}
////To cancel a request with a custom HTML content
////Filter URL
e.Ok(null);
_lastURL = URL;
}
//if (e.RequestURL.Contains("google.com"))
//{
// e.Ok("<!DOCTYPE html><html><body><h1>Website Blocked</h1><p>Blocked by titanium web proxy.</p></body></html>");
//}
}
//Test script injection
//Insert script to read the Browser URL and send it back to proxy
public void OnResponse(object sender, SessionEventArgs e)
{
try
{
if (e.ProxyRequest.Method == "GET" || e.ProxyRequest.Method == "POST")
{
if (e.ServerResponse.StatusCode == HttpStatusCode.OK)
{
if (e.ServerResponse.ContentType.Trim().ToLower().Contains("text/html"))
{
string c = e.ServerResponse.GetResponseHeader("X-Requested-With");
if (e.ServerResponse.GetResponseHeader("X-Requested-With") == "")
{
string responseHtmlBody = e.GetResponseHtmlBody();
string functioname = "fr" + RandomString(10);
string VisitedURL = RandomString(5);
string RequestVariable = "c" + RandomString(5);
string RandomURLEnding = RandomString(25);
string RandomLastRequest = RandomString(10);
string LocalRequest;
if (e.IsSSLRequest)
LocalRequest = "https://" + e.RequestHostname + "/" + RandomURLEnding;
else
LocalRequest = "http://" + e.RequestHostname + "/" + RandomURLEnding;
string script = "var " + RandomLastRequest + " = null;" +
"if(window.top==self) { " + "\n" +
" " + functioname + "();" +
"setInterval(" + functioname + ",500); " + "\n" + "}" +
"function " + functioname + "(){ " + "\n" +
"var " + RequestVariable + " = new XMLHttpRequest(); " + "\n" +
"var " + VisitedURL + " = null;" + "\n" +
"if(window.top.location.href!=null) " + "\n" +
"" + VisitedURL + " = window.top.location.href; else " + "\n" +
"" + VisitedURL + " = document.referrer; " +
"if(" + RandomLastRequest + "!= " + VisitedURL + ") {" +
RequestVariable + ".open(\"POST\",\"" + LocalRequest + "\", true); " + "\n" +
RequestVariable + ".send(" + VisitedURL + ");} " + RandomLastRequest + " = " + VisitedURL + "}";
Regex RE = new Regex("</body>", RegexOptions.RightToLeft | RegexOptions.IgnoreCase | RegexOptions.Multiline);
string modifiedResponseHtmlBody = RE.Replace(responseHtmlBody, "<script type =\"text/javascript\">" + script + "</script></body>", 1);
if (modifiedResponseHtmlBody.Length != responseHtmlBody.Length)
{
e.SetResponseHtmlBody(modifiedResponseHtmlBody);
_URLList.Add(RandomURLEnding);
}
}
}
}
}
}
catch { }
////read response headers
//var responseHeaders = e.ResponseHeaders;
}
//if (e.ResponseStatusCode == HttpStatusCode.OK)
//{
// if (e.ResponseContentType.Trim().ToLower().Contains("text/html"))
// {
// //Get/Set response body bytes
// byte[] responseBodyBytes = e.GetResponseBody();
// e.SetResponseBody(responseBodyBytes);
// //Get response body as string
// string responseBody = e.GetResponseBodyAsString();
private Random random = new Random((int)DateTime.Now.Ticks);
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
// //Modify e.ServerResponse
// 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);
}
public class VisitedEventArgs : EventArgs
{
public string URL;
public string hostname;
public IPAddress remoteIP { get; set; }
public int remotePort { get; set; }
// //Set modifed response Html Body
// e.SetResponseBodyString(modified);
// }
//}
}
}
}
}
\ No newline at end of file
......@@ -16,6 +16,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{6FD3B8
.nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "HttpClient", "HttpClient", "{867333C8-3C44-41F4-913C-63802970CF82}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Titanium.Web.Http", "Titanium.Web.Http\Titanium.Web.Http.csproj", "{51F8273A-39E4-4C9F-9972-BC78F8B3B32E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Titanium.Web.Http.Tests", "Titanium.Web.Http.Tests\Titanium.Web.Http.Tests.csproj", "{95550A47-B2D2-43C4-8E79-17BDF09B797F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -46,12 +52,30 @@ Global
{8D73A1BE-868C-42D2-9ECE-F32CC1A02906}.Release|x64.Build.0 = Release|x64
{8D73A1BE-868C-42D2-9ECE-F32CC1A02906}.Release|x86.ActiveCfg = Release|x86
{8D73A1BE-868C-42D2-9ECE-F32CC1A02906}.Release|x86.Build.0 = Release|x86
{51F8273A-39E4-4C9F-9972-BC78F8B3B32E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{51F8273A-39E4-4C9F-9972-BC78F8B3B32E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{51F8273A-39E4-4C9F-9972-BC78F8B3B32E}.Debug|x64.ActiveCfg = Debug|Any CPU
{51F8273A-39E4-4C9F-9972-BC78F8B3B32E}.Debug|x86.ActiveCfg = Debug|Any CPU
{51F8273A-39E4-4C9F-9972-BC78F8B3B32E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{51F8273A-39E4-4C9F-9972-BC78F8B3B32E}.Release|Any CPU.Build.0 = Release|Any CPU
{51F8273A-39E4-4C9F-9972-BC78F8B3B32E}.Release|x64.ActiveCfg = Release|Any CPU
{51F8273A-39E4-4C9F-9972-BC78F8B3B32E}.Release|x86.ActiveCfg = Release|Any CPU
{95550A47-B2D2-43C4-8E79-17BDF09B797F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{95550A47-B2D2-43C4-8E79-17BDF09B797F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{95550A47-B2D2-43C4-8E79-17BDF09B797F}.Debug|x64.ActiveCfg = Debug|Any CPU
{95550A47-B2D2-43C4-8E79-17BDF09B797F}.Debug|x86.ActiveCfg = Debug|Any CPU
{95550A47-B2D2-43C4-8E79-17BDF09B797F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{95550A47-B2D2-43C4-8E79-17BDF09B797F}.Release|Any CPU.Build.0 = Release|Any CPU
{95550A47-B2D2-43C4-8E79-17BDF09B797F}.Release|x64.ActiveCfg = Release|Any CPU
{95550A47-B2D2-43C4-8E79-17BDF09B797F}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{F3B7E553-1904-4E80-BDC7-212342B5C952} = {B6DBABDC-C985-4872-9C38-B4E5079CBC4B}
{51F8273A-39E4-4C9F-9972-BC78F8B3B32E} = {867333C8-3C44-41F4-913C-63802970CF82}
{95550A47-B2D2-43C4-8E79-17BDF09B797F} = {867333C8-3C44-41F4-913C-63802970CF82}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EnterpriseLibraryConfigurationToolBinariesPath = .1.505.2\lib\NET35
......
This diff is collapsed.
using System;
namespace Titanium.Web.Proxy.Exceptions
{
public class BodyNotFoundException : Exception
{
public BodyNotFoundException(string message)
: base(message)
{
}
}
}
\ No newline at end of file
using System.Net;
using System.Text;
namespace Titanium.Web.Proxy.Extensions
{
public static class HttpWebRequestExtensions
{
public static Encoding GetEncoding(this HttpWebRequest request)
{
try
{
if (request.ContentType == null) return Encoding.GetEncoding("ISO-8859-1");
var contentTypes = request.ContentType.Split(';');
foreach (var contentType in contentTypes)
{
var encodingSplit = contentType.Split('=');
if (encodingSplit.Length == 2 && encodingSplit[0].ToLower().Trim() == "charset")
{
return Encoding.GetEncoding(encodingSplit[1]);
}
}
}
catch
{
// ignored
}
return Encoding.GetEncoding("ISO-8859-1");
}
}
}
\ No newline at end of file
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");
return Encoding.GetEncoding(response.CharacterSet.Replace(@"""",string.Empty));
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text;
namespace Titanium.Web.Proxy.Helpers
namespace Titanium.Web.Proxy.Extensions
{
public static class StreamHelper
{
private const int DEFAULT_BUFFER_SIZE = 8192; // +32767
public static void CopyTo(this Stream input, Stream output)
{
input.CopyTo(output, DEFAULT_BUFFER_SIZE);
return;
}
public static void CopyTo(string initialData, Stream input, Stream output, int bufferSize)
public static void CopyToAsync(this Stream input, string initialData, Stream output, int bufferSize)
{
var bytes = Encoding.ASCII.GetBytes(initialData);
output.Write(bytes,0, bytes.Length);
CopyTo(input, output, bufferSize);
output.Write(bytes, 0, bytes.Length);
CopyToAsync(input, output, bufferSize);
}
public static void CopyTo(this Stream input, Stream output, int bufferSize)
//http://stackoverflow.com/questions/1540658/net-asynchronous-stream-read-write
public static void CopyToAsync(this Stream input, Stream output, int bufferSize)
{
try
{
if (!input.CanRead) throw new InvalidOperationException("input must be open for reading");
if (!output.CanWrite) throw new InvalidOperationException("output must be open for writing");
byte[][] buf = { new byte[bufferSize], new byte[bufferSize] };
int[] bufl = { 0, 0 };
int bufno = 0;
IAsyncResult read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null);
byte[][] buf = {new byte[bufferSize], new byte[bufferSize]};
int[] bufl = {0, 0};
var bufno = 0;
var read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null);
IAsyncResult write = null;
while (true)
{
// wait for the read operation to complete
read.AsyncWaitHandle.WaitOne();
bufl[bufno] = input.EndRead(read);
......@@ -66,7 +57,6 @@ namespace Titanium.Web.Proxy.Helpers
// A little speedier than using a ternary expression.
bufno ^= 1; // bufno = ( bufno == 0 ? 1 : 0 ) ;
read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null);
}
// wait for the final in-flight write operation, if one exists, to complete
......@@ -79,9 +69,11 @@ namespace Titanium.Web.Proxy.Helpers
output.Flush();
}
catch { }
catch
{
// ignored
}
// return to the caller ;
return;
}
}
}
}
\ No newline at end of file
......@@ -6,10 +6,10 @@ using System.Security.Cryptography.X509Certificates;
namespace Titanium.Web.Proxy.Helpers
{
public class CertificateManager
public class CertificateManager : IDisposable
{
private const string CERT_CREATE_FORMAT =
"-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 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 {5}";
private readonly IDictionary<string, X509Certificate2> _certificateCache;
......@@ -69,6 +69,7 @@ namespace Titanium.Web.Proxy.Helpers
}
protected virtual X509Certificate2 CreateCertificate(X509Store store, string certificateName)
{
if (_certificateCache.ContainsKey(certificateName))
return _certificateCache[certificateName];
......@@ -80,7 +81,7 @@ namespace Titanium.Web.Proxy.Helpers
store.Open(OpenFlags.ReadWrite);
string certificateSubject = string.Format("CN={0}, O={1}", certificateName, Issuer);
X509Certificate2Collection certificates =
var certificates =
FindCertificates(store, certificateSubject);
if (certificates != null)
......@@ -164,13 +165,22 @@ namespace Titanium.Web.Proxy.Helpers
bool isRootCertificate =
(certificateName == RootCertificateName);
string certCreatArgs = string.Format(CERT_CREATE_FORMAT,
string certCreatArgs = string.Format(CertCreateFormat,
store.Name, certificateName, Issuer,
isRootCertificate ? "signature" : "exchange",
isRootCertificate ? "authority" : "end", DateTime.Now,
isRootCertificate ? "authority" : "end",
isRootCertificate ? "-h 1 -r" : string.Format("-pe -in \"{0}\" -is Root", RootCertificateName));
return certCreatArgs;
}
public void Dispose()
{
if (MyStore != null)
MyStore.Close();
if (RootStore != null)
RootStore.Close();
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Ionic.Zlib;
namespace Titanium.Web.Proxy.Helpers
{
public class CompressionHelper
{
private static readonly int BUFFER_SIZE = 8192;
private const int BufferSize = 8192;
public static string DecompressGzip(Stream input, Encoding e)
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressZlib(byte[] bytes)
{
using (System.IO.Compression.GZipStream decompressor = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
using (var ms = new MemoryStream())
{
int read = 0;
var buffer = new byte[BUFFER_SIZE];
using (MemoryStream output = new MemoryStream())
using (var zip = new ZlibStream(ms, CompressionMode.Compress, true))
{
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
return e.GetString(output.ToArray());
zip.Write(bytes, 0, bytes.Length);
}
return ms.ToArray();
}
}
public static byte[] CompressZlib(string ResponseData, Encoding e)
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressDeflate(byte[] bytes)
{
Byte[] bytes = e.GetBytes(ResponseData);
using (MemoryStream ms = new MemoryStream())
using (var ms = new MemoryStream())
{
using (Ionic.Zlib.ZlibStream zip = new Ionic.Zlib.ZlibStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
using (var zip = new DeflateStream(ms, CompressionMode.Compress, true))
{
zip.Write(bytes, 0, bytes.Length);
}
return ms.ToArray();
}
}
public static byte[] CompressDeflate(string ResponseData, Encoding e)
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressGzip(byte[] bytes)
{
Byte[] bytes = e.GetBytes(ResponseData);
using (MemoryStream ms = new MemoryStream())
using (var ms = new MemoryStream())
{
using (Ionic.Zlib.DeflateStream zip = new Ionic.Zlib.DeflateStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(bytes, 0, bytes.Length);
}
return ms.ToArray();
}
}
public static byte[] CompressGzip(string ResponseData, Encoding e)
public static byte[] DecompressGzip(Stream input)
{
Byte[] bytes = e.GetBytes(ResponseData);
using (MemoryStream ms = new MemoryStream())
using (
var decompressor = new System.IO.Compression.GZipStream(input,
System.IO.Compression.CompressionMode.Decompress))
{
using (Ionic.Zlib.GZipStream zip = new Ionic.Zlib.GZipStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
var buffer = new byte[BufferSize];
using (var output = new MemoryStream())
{
zip.Write(bytes, 0, bytes.Length);
int read;
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
return output.ToArray();
}
return ms.ToArray();
}
}
public static string DecompressDeflate(Stream input, Encoding e)
{
using (Ionic.Zlib.DeflateStream decompressor = new Ionic.Zlib.DeflateStream(input, Ionic.Zlib.CompressionMode.Decompress))
public static byte[] DecompressDeflate(Stream input)
{
using (var decompressor = new DeflateStream(input, CompressionMode.Decompress))
{
int read = 0;
var buffer = new byte[BUFFER_SIZE];
var buffer = new byte[BufferSize];
using (MemoryStream output = new MemoryStream())
using (var output = new MemoryStream())
{
int read;
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
return e.GetString(output.ToArray());
return output.ToArray();
}
}
}
public static string DecompressZlib(Stream input, Encoding e)
{
using (Ionic.Zlib.ZlibStream decompressor = new Ionic.Zlib.ZlibStream(input, Ionic.Zlib.CompressionMode.Decompress))
public static byte[] DecompressZlib(Stream input)
{
using (var decompressor = new ZlibStream(input, CompressionMode.Decompress))
{
var buffer = new byte[BufferSize];
int read = 0;
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)
{
output.Write(buffer, 0, read);
}
return e.GetString(output.ToArray());
return output.ToArray();
}
}
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace Titanium.Web.Proxy.Helpers
{
public class CustomBinaryReader : BinaryReader
{
public CustomBinaryReader(Stream stream, Encoding encoding)
: base(stream, encoding)
{
}
public string ReadLine()
{
char[] buf = new char[1];
StringBuilder _readBuffer = new StringBuilder();
try
{
var charsRead = 0;
char lastChar = new char();
while ((charsRead = base.Read(buf, 0, 1)) > 0)
{
if (lastChar == '\r' && buf[0] == '\n')
{
return _readBuffer.Remove(_readBuffer.Length - 1, 1).ToString();
}
else
if (buf[0] == '\0')
{
return _readBuffer.ToString();
}
else
_readBuffer.Append(buf[0]);
lastChar = buf[0];
}
return _readBuffer.ToString();
}
catch (IOException)
{ return _readBuffer.ToString(); }
catch (Exception e)
{ throw e; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Titanium.Web.Proxy.Helpers
......@@ -12,21 +9,23 @@ namespace Titanium.Web.Proxy.Helpers
{
try
{
DirectoryInfo[] myProfileDirectory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Mozilla\\Firefox\\Profiles\\").GetDirectories("*.default");
string myFFPrefFile = myProfileDirectory[0].FullName + "\\prefs.js";
if (File.Exists(myFFPrefFile))
var myProfileDirectory =
new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
"\\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
StreamReader myReader = new StreamReader(myFFPrefFile);
string myPrefContents = myReader.ReadToEnd();
var myReader = new StreamReader(myFfPrefFile);
var myPrefContents = myReader.ReadToEnd();
myReader.Close();
if (myPrefContents.Contains("user_pref(\"network.proxy.type\", 0);"))
{
// Add the proxy enable line and write it back to the file
myPrefContents = myPrefContents.Replace("user_pref(\"network.proxy.type\", 0);", "");
File.Delete(myFFPrefFile);
File.WriteAllText(myFFPrefFile, myPrefContents);
File.Delete(myFfPrefFile);
File.WriteAllText(myFfPrefFile, myPrefContents);
}
}
}
......@@ -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.
}
}
public static void RemoveFirefox()
{
try
{
DirectoryInfo[] myProfileDirectory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Mozilla\\Firefox\\Profiles\\").GetDirectories("*.default");
string myFFPrefFile = myProfileDirectory[0].FullName + "\\prefs.js";
if (File.Exists(myFFPrefFile))
var myProfileDirectory =
new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
"\\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
StreamReader myReader = new StreamReader(myFFPrefFile);
string myPrefContents = myReader.ReadToEnd();
var myReader = new StreamReader(myFfPrefFile);
var myPrefContents = myReader.ReadToEnd();
myReader.Close();
if (!myPrefContents.Contains("user_pref(\"network.proxy.type\", 0);"))
{
// Add the proxy enable line and write it back to the file
myPrefContents = myPrefContents + "\n\r" + "user_pref(\"network.proxy.type\", 0);";
File.Delete(myFFPrefFile);
File.WriteAllText(myFFPrefFile, myPrefContents);
File.Delete(myFfPrefFile);
File.WriteAllText(myFfPrefFile, myPrefContents);
}
}
}
......@@ -63,4 +65,4 @@ namespace Titanium.Web.Proxy.Helpers
}
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Configuration;
using System.Reflection;
using System.Text;
namespace Titanium.Web.Proxy.Helpers
{
public class NetFrameworkHelper
{
public static void URLPeriodFix()
//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
public static void UrlPeriodFix()
{
MethodInfo getSyntax = typeof(UriParser).GetMethod("GetSyntax", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
FieldInfo flagsField = typeof(UriParser).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
var getSyntax = typeof (UriParser).GetMethod("GetSyntax", BindingFlags.Static | BindingFlags.NonPublic);
var flagsField = typeof (UriParser).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
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)
{
int flagsValue = (int)flagsField.GetValue(parser);
var flagsValue = (int) flagsField.GetValue(parser);
if ((flagsValue & 0x1000000) != 0)
flagsField.SetValue(parser, flagsValue & ~0x1000000);
}
}
}
}
// Enable/disable useUnsafeHeaderParsing.
// See http://o2platform.wordpress.com/2010/10/20/dealing-with-the-server-committed-a-protocol-violation-sectionresponsestatusline/
public static bool ToggleAllowUnsafeHeaderParsing(bool enable)
{
//Get the assembly that contains the internal class
var assembly = Assembly.GetAssembly(typeof (SettingsSection));
if (assembly != null)
{
//Use the assembly in order to get the internal type for the internal class
var settingsSectionType = assembly.GetType("System.Net.Configuration.SettingsSectionInternal");
if (settingsSectionType != null)
{
//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.
var anInstance = settingsSectionType.InvokeMember("Section",
BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null,
new object[] {});
if (anInstance != null)
{
//Locate the private bool field that tells the framework if unsafe header parsing is allowed
var aUseUnsafeHeaderParsing = settingsSectionType.GetField("useUnsafeHeaderParsing",
BindingFlags.NonPublic | BindingFlags.Instance);
if (aUseUnsafeHeaderParsing != null)
{
aUseUnsafeHeaderParsing.SetValue(anInstance, enable);
return true;
}
}
}
}
return false;
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Titanium.Web.Proxy.Helpers
{
public static class SystemProxyHelper
internal static class NativeMethods
{
[DllImport("wininet.dll")]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
public const int INTERNET_OPTION_REFRESH = 37;
static bool settingsReturn, refreshReturn;
static object prevProxyServer;
static object prevProxyEnable;
internal static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer,
int dwBufferLength);
}
public static class SystemProxyHelper
{
public const int InternetOptionSettingsChanged = 39;
public const int InternetOptionRefresh = 37;
private static object _prevProxyServer;
private static object _prevProxyEnable;
public static void EnableProxyHTTP(string hostname, int port)
public static void EnableProxyHttp(string hostname, int port)
{
RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
prevProxyEnable = reg.GetValue("ProxyEnable");
prevProxyServer = reg.GetValue("ProxyServer");
reg.SetValue("ProxyEnable", 1);
reg.SetValue("ProxyServer", "http="+hostname+":" + port + ";");
refresh();
var reg = Registry.CurrentUser.OpenSubKey(
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
if (reg != null)
{
_prevProxyEnable = reg.GetValue("ProxyEnable");
_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);
reg.SetValue("ProxyEnable", 1);
reg.SetValue("ProxyServer", "http=" + hostname + ":" + port + ";https=" + hostname + ":" + port);
refresh();
var reg = Registry.CurrentUser.OpenSubKey(
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
if (reg != null)
{
reg.SetValue("ProxyEnable", 1);
reg.SetValue("ProxyServer", "http=" + hostname + ":" + port + ";https=" + hostname + ":" + port);
}
Refresh();
}
public static void DisableAllProxy()
{
RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
reg.SetValue("ProxyEnable", prevProxyEnable);
if (prevProxyServer != null)
reg.SetValue("ProxyServer", prevProxyServer);
refresh();
var reg = Registry.CurrentUser.OpenSubKey(
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
if (reg != null)
{
reg.SetValue("ProxyEnable", _prevProxyEnable);
if (_prevProxyServer != null)
reg.SetValue("ProxyServer", _prevProxyServer);
}
Refresh();
}
private static void refresh()
private static void Refresh()
{
settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionSettingsChanged, IntPtr.Zero,0);
NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionRefresh, IntPtr.Zero, 0);
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Net.Security;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Titanium.Web.Http;
using Titanium.Web.Proxy.Extensions;
namespace Titanium.Web.Proxy.Helpers
{
public class TcpHelper
{
private static readonly int BUFFER_SIZE = 8192;
private static readonly String[] colonSpaceSplit = new string[] { ": " };
public static void SendRaw(string Hostname, int TunnelPort, System.IO.Stream ClientStream)
{
System.Net.Sockets.TcpClient tunnelClient = new System.Net.Sockets.TcpClient(Hostname, TunnelPort);
var tunnelStream = tunnelClient.GetStream();
var tunnelReadBuffer = new byte[BUFFER_SIZE];
Task sendRelay = new Task(() => StreamHelper.CopyTo(ClientStream, tunnelStream, BUFFER_SIZE));
Task receiveRelay = new Task(() => StreamHelper.CopyTo(tunnelStream, ClientStream, BUFFER_SIZE));
sendRelay.Start();
receiveRelay.Start();
Task.WaitAll(sendRelay, receiveRelay);
if (tunnelStream != null)
tunnelStream.Close();
if (tunnelClient != null)
tunnelClient.Close();
}
public static void SendRaw(string HttpCmd, string SecureHostName, ref List<string> RequestLines, bool IsHttps, Stream ClientStream)
public static void SendRaw(Stream clientStream, string httpCmd, List<HttpHeader> requestHeaders, string hostName,
int tunnelPort, bool isHttps)
{
StringBuilder sb = new StringBuilder();
sb.Append(HttpCmd);
sb.Append(Environment.NewLine);
string hostname = SecureHostName;
for (int i = 1; i < RequestLines.Count; i++)
StringBuilder sb = null;
if (httpCmd != null || requestHeaders != null)
{
var header = RequestLines[i];
if (SecureHostName == null)
sb = new StringBuilder();
if (httpCmd != null)
{
String[] headerParsed = HttpCmd.Split(colonSpaceSplit, 2, StringSplitOptions.None);
switch (headerParsed[0].ToLower())
sb.Append(httpCmd);
sb.Append(Environment.NewLine);
}
if (requestHeaders != null)
foreach (var header in requestHeaders.Select(t => t.ToString()))
{
case "host":
var hostdetail = headerParsed[1];
if (hostdetail.Contains(":"))
hostname = hostdetail.Split(':')[0].Trim();
else
hostname = hostdetail.Trim();
break;
default:
break;
sb.Append(header);
sb.Append(Environment.NewLine);
}
}
sb.Append(header);
sb.Append(Environment.NewLine);
}
sb.Append(Environment.NewLine);
int tunnelPort = 80;
if (IsHttps)
{
tunnelPort = 443;
TcpClient tunnelClient = null;
Stream tunnelStream = null;
}
try
{
tunnelClient = new TcpClient(hostName, tunnelPort);
tunnelStream = tunnelClient.GetStream();
System.Net.Sockets.TcpClient tunnelClient = new System.Net.Sockets.TcpClient(hostname, tunnelPort);
var tunnelStream = tunnelClient.GetStream() as System.IO.Stream;
if (isHttps)
{
SslStream sslStream = null;
try
{
sslStream = new SslStream(tunnelStream);
sslStream.AuthenticateAsClient(hostName);
tunnelStream = sslStream;
}
catch
{
if (sslStream != null)
sslStream.Dispose();
if (IsHttps)
{
var sslStream = new SslStream(tunnelStream);
sslStream.AuthenticateAsClient(hostname);
tunnelStream = sslStream;
}
throw;
}
}
var sendRelay = new Task(() => StreamHelper.CopyTo(sb.ToString(), ClientStream, tunnelStream, BUFFER_SIZE));
var receiveRelay = new Task(() => StreamHelper.CopyTo(tunnelStream, ClientStream, BUFFER_SIZE));
var sendRelay = Task.Factory.StartNew(() =>
{
if (sb != null)
clientStream.CopyToAsync(sb.ToString(), tunnelStream, BUFFER_SIZE);
else
clientStream.CopyToAsync(tunnelStream, BUFFER_SIZE);
});
sendRelay.Start();
receiveRelay.Start();
var receiveRelay = Task.Factory.StartNew(() => tunnelStream.CopyToAsync(clientStream, BUFFER_SIZE));
Task.WaitAll(sendRelay, receiveRelay);
Task.WaitAll(sendRelay, receiveRelay);
}
catch
{
if (tunnelStream != null)
{
tunnelStream.Close();
tunnelStream.Dispose();
}
if (tunnelStream != null)
tunnelStream.Close();
if (tunnelClient != null)
tunnelClient.Close();
if (tunnelClient != null)
tunnelClient.Close();
throw;
}
}
}
}
\ No newline at end of file
using System;
using System.Text;
using System.IO;
using System.Net;
using Titanium.Web.Proxy.Helpers;
namespace Titanium.Web.Proxy.Models
{
public class SessionEventArgs : EventArgs
{
public string RequestURL { get; set; }
public string RequestHostname { get; set; }
public bool IsSSLRequest { get; set; }
public int ClientPort { get; set; }
public IPAddress ClientIpAddress { get; set; }
public HttpWebRequest ProxyRequest { get; set; }
public HttpWebResponse ServerResponse { get; set; }
internal int BUFFER_SIZE;
internal int RequestLength { get; set; }
internal Version RequestHttpVersion { get; set; }
internal bool RequestIsAlive { get; set; }
internal bool CancelRequest { get; set; }
internal CustomBinaryReader ClientStreamReader { get; set; }
internal Stream ClientStream { get; set; }
internal Stream ServerResponseStream { get; set; }
internal Encoding Encoding { get; set; }
internal bool RequestWasModified { get; set; }
internal bool ResponseWasModified { get; set; }
internal string UpgradeProtocol { get; set; }
internal string RequestHtmlBody { get; set; }
internal string ResponseHtmlBody { get; set; }
public SessionEventArgs(int BufferSize)
{
BUFFER_SIZE = BufferSize;
}
public string GetRequestHtmlBody()
{
if (RequestHtmlBody == null)
{
int bytesRead;
int totalBytesRead = 0;
MemoryStream mw = new MemoryStream();
var buffer = ClientStreamReader.ReadBytes(RequestLength);
while (totalBytesRead < RequestLength && (bytesRead = buffer.Length) > 0)
{
totalBytesRead += bytesRead;
mw.Write(buffer, 0, bytesRead);
}
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()
{
if (ResponseHtmlBody == null)
{
Encoding = Encoding.GetEncoding(ServerResponse.CharacterSet);
if (Encoding == null) Encoding = Encoding.Default;
string ResponseData = "";
switch (ServerResponse.ContentEncoding)
{
case "gzip":
ResponseData = CompressionHelper.DecompressGzip(ServerResponseStream, Encoding);
break;
case "deflate":
ResponseData = CompressionHelper.DecompressDeflate(ServerResponseStream, Encoding);
break;
case "zlib":
ResponseData = CompressionHelper.DecompressZlib(ServerResponseStream, Encoding);
break;
default:
ResponseData = DecodeData(ServerResponseStream, Encoding);
break;
}
ResponseHtmlBody = ResponseData;
ResponseWasModified = true;
}
return ResponseHtmlBody;
}
public void SetResponseHtmlBody(string Body)
{
this.ResponseHtmlBody = Body;
}
//stream reader not recomended for images
private string DecodeData(Stream ResponseStream, Encoding e)
{
StreamReader reader = new StreamReader(ResponseStream, e);
return reader.ReadToEnd();
}
public void Ok(string Html)
{
if (Html == null)
Html = string.Empty;
var result = Encoding.Default.GetBytes(Html);
StreamWriter connectStreamWriter = new StreamWriter(ClientStream);
var s = String.Format("HTTP/{0}.{1} {2} {3}", RequestHttpVersion.Major, RequestHttpVersion.Minor, 200, "Ok");
connectStreamWriter.WriteLine(s);
connectStreamWriter.WriteLine(String.Format("Timestamp: {0}", DateTime.Now.ToString()));
connectStreamWriter.WriteLine("content-length: " + result.Length);
connectStreamWriter.WriteLine("Cache-Control: no-cache, no-store, must-revalidate");
connectStreamWriter.WriteLine("Pragma: no-cache");
connectStreamWriter.WriteLine("Expires: 0");
if (RequestIsAlive)
{
connectStreamWriter.WriteLine("Connection: Keep-Alive");
}
else
connectStreamWriter.WriteLine("Connection: close");
connectStreamWriter.WriteLine();
connectStreamWriter.Flush();
ClientStream.Write(result, 0, result.Length);
CancelRequest = true;
}
public System.Net.Sockets.TcpClient Client { get; set; }
public string tunnelHostName { get; set; }
public string securehost { get; set; }
}
}
\ No newline at end of file
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Titanium.Web.Proxy.Properties")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Titanium.Web.Proxy.Properties")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5036e0b7-a0d0-4070-8eb0-72c129dee9b3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Titanium.Web.Proxy.Models;
using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy.Helpers;
namespace Titanium.Web.Proxy
{
/// <summary>
/// Proxy Server Main class
/// Proxy Server Main class
/// </summary>
public partial class ProxyServer
{
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 char[] spaceSplit = new char[] { ' ' };
private static readonly string[] ColonSpaceSplit = { ": " };
private static readonly char[] SpaceSplit = { ' ' };
private static readonly Regex cookieSplitRegEx = new Regex(@",(?! )");
private static readonly Regex CookieSplitRegEx = new Regex(@",(?! )");
private static object certificateAccessLock = new object();
private static List<string> pinnedCertificateClients = new List<string>();
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 TcpListener _listener;
private static TcpListener listener;
private static Thread listenerThread;
public static List<string> ExcludedHttpsHostNameRegex = new List<string>();
public static event EventHandler<SessionEventArgs> BeforeRequest;
public static event EventHandler<SessionEventArgs> BeforeResponse;
static ProxyServer()
{
CertManager = new CertificateManager("Titanium",
"Titanium Root Certificate Authority");
ListeningIpAddress = IPAddress.Any;
ListeningPort = 0;
Initialize();
}
public static IPAddress ListeningIPInterface { get; set; }
private static CertificateManager CertManager { get; set; }
public static string RootCertificateName { get; set; }
public static bool EnableSSL { get; set; }
public static bool EnableSsl { get; set; }
public static bool SetAsSystemProxy { get; set; }
public static Int32 ListeningPort
{
get
{
return ((IPEndPoint)listener.LocalEndpoint).Port;
}
}
public static int ListeningPort { get; set; }
public static IPAddress ListeningIpAddress { get; set; }
public static CertificateManager CertManager { get; set; }
public static event EventHandler<SessionEventArgs> BeforeRequest;
public static event EventHandler<SessionEventArgs> BeforeResponse;
static ProxyServer()
{
CertManager = new CertificateManager("Titanium",
"Titanium Root Certificate Authority");
}
public ProxyServer()
public static void Initialize()
{
System.Net.ServicePointManager.Expect100Continue = false;
System.Net.WebRequest.DefaultWebProxy = null;
System.Net.ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.DnsRefreshTimeout = 3 * 60 * 1000;//3 minutes
ServicePointManager.Expect100Continue = false;
WebRequest.DefaultWebProxy = null;
ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.DnsRefreshTimeout = 3 * 60 * 1000; //3 minutes
ServicePointManager.MaxServicePointIdleTime = 3 * 60 * 1000;
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None) return true;
else
//HttpWebRequest certificate validation callback
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None) return true;
return false;
};
NetFrameworkHelper.URLPeriodFix();
};
//Fix a bug in .NET 4.0
NetFrameworkHelper.UrlPeriodFix();
//useUnsafeHeaderParsing
NetFrameworkHelper.ToggleAllowUnsafeHeaderParsing(true);
}
private static bool ShouldListen { get; set; }
public static bool Start()
{
listener = new TcpListener(IPAddress.Any, 0);
listener.Start();
listenerThread = new Thread(new ParameterizedThreadStart(Listen));
listenerThread.IsBackground = true;
ShouldListen = true;
listenerThread.Start(listener);
_listener = new TcpListener(ListeningIpAddress, ListeningPort);
_listener.Start();
ListeningPort = ((IPEndPoint)_listener.LocalEndpoint).Port;
// accept clients asynchronously
_listener.BeginAcceptTcpClient(OnAcceptConnection, _listener);
var certTrusted = false;
if (EnableSsl)
certTrusted = CertManager.CreateTrustedRootCertificate();
if (SetAsSystemProxy)
{
SystemProxyHelper.EnableProxyHTTP("localhost", ListeningPort);
SystemProxyHelper.EnableProxyHttp(
Equals(ListeningIpAddress, IPAddress.Any) ? "127.0.0.1" : ListeningIpAddress.ToString(), ListeningPort);
FireFoxHelper.AddFirefox();
if (EnableSSL)
if (EnableSsl)
{
RootCertificateName = RootCertificateName == null ? "Titanium_Proxy_Test_Root" : RootCertificateName;
RootCertificateName = RootCertificateName ?? "Titanium_Proxy_Test_Root";
bool certTrusted = CertManager.CreateTrustedRootCertificate();
if (!certTrusted)
//If certificate was trusted by the machine
if (certTrusted)
{
// The user didn't want to install the self-signed certificate to the root store.
SystemProxyHelper.EnableProxyHttps(
Equals(ListeningIpAddress, IPAddress.Any) ? "127.0.0.1" : ListeningIpAddress.ToString(),
ListeningPort);
}
SystemProxyHelper.EnableProxyHTTPS("localhost", ListeningPort);
}
}
return true;
}
public static void Stop()
{
if (SetAsSystemProxy)
{
SystemProxyHelper.DisableAllProxy();
FireFoxHelper.RemoveFirefox();
}
ShouldListen = false;
listener.Stop();
listenerThread.Interrupt();
}
private static void Listen(Object obj)
private static void OnAcceptConnection(IAsyncResult asyn)
{
TcpListener listener = (TcpListener)obj;
try
{
while (ShouldListen)
{
var client = listener.AcceptTcpClient();
Task.Factory.StartNew(() => HandleClient(client));
}
// Get the listener that handles the client request.
_listener.BeginAcceptTcpClient(OnAcceptConnection, _listener);
var client = _listener.EndAcceptTcpClient(asyn);
var Task = HandleClient(client);
}
catch (ThreadInterruptedException) { }
catch (SocketException)
catch
{
// ignored
}
}
public static void Stop()
{
if (SetAsSystemProxy)
{
SystemProxyHelper.DisableAllProxy();
FireFoxHelper.RemoveFirefox();
}
_listener.Stop();
CertManager.Dispose();
}
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
......@@ -66,9 +66,29 @@
<Reference Include="Ionic.Zip">
<HintPath>..\packages\DotNetZip.1.9.3\lib\net20\Ionic.Zip.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions.Desktop">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO">
<HintPath>..\packages\Microsoft.Bcl.1.1.8\lib\net40\System.IO.dll</HintPath>
</Reference>
<Reference Include="System.Net" />
<Reference Include="System.Runtime">
<HintPath>..\packages\Microsoft.Bcl.1.1.8\lib\net40\System.Runtime.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.1.1.8\lib\net40\System.Threading.Tasks.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
......@@ -76,23 +96,30 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Exceptions\BodyNotFoundException.cs" />
<Compile Include="Extensions\HttpWebResponseExtensions.cs" />
<Compile Include="Extensions\HttpWebRequestExtensions.cs" />
<Compile Include="Helpers\CertificateManager.cs" />
<Compile Include="Helpers\Firefox.cs" />
<Compile Include="Helpers\SystemProxy.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RequestHandler.cs" />
<Compile Include="ResponseHandler.cs" />
<Compile Include="Helpers\CustomBinaryReader.cs" />
<Compile Include="Helpers\NetFramework.cs" />
<Compile Include="Helpers\Compression.cs" />
<Compile Include="ProxyServer.cs" />
<Compile Include="Models\SessionEventArgs.cs" />
<Compile Include="EventArguments\SessionEventArgs.cs" />
<Compile Include="Helpers\Tcp.cs" />
<Compile Include="Helpers\Stream.cs" />
<Compile Include="Extensions\StreamExtensions.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
<ProjectReference Include="..\Titanium.Web.Http\Titanium.Web.Http.csproj">
<Project>{51f8273a-39e4-4c9f-9972-bc78f8b3b32e}</Project>
<Name>Titanium.Web.Http</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
<None Include="Titanium_Proxy_Test_Root.cer">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
......@@ -111,6 +138,11 @@
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
<Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
<Error Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
......
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DotNetZip" version="1.9.3" targetFramework="net40-Client" />
<package id="Microsoft.Bcl" version="1.1.8" targetFramework="net40-Client" />
<package id="Microsoft.Bcl.Async" version="1.0.168" targetFramework="net40-Client" />
<package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net40-Client" />
</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