Commit 4c3121ed authored by titanium007's avatar titanium007

Replace HttpWebRequest with Custom Request Class

parent 606fe644
<?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" />
......
Titanium Titanium
======== ========
A light weight http(s) proxy server written in C# 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) ![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"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<configSections> <startup>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </startup>
</configSections> <runtime>
<connectionStrings> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<add name="SqlCELogConnectionString" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=Log.sdf" /> <dependentAssembly>
<add name="SqlCEEventsConnectionString" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=Events.sdf" /> <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<add name="SqlCEFilesConnectionString" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=Files.sdf" /> <bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
<add name="SqlServerLogConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ASXLog;Integrated Security=True;Enlist=False;" providerName="System.Data.SqlClient" /> </dependentAssembly>
<add name="SqlServerEventsConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ASXEvents;Integrated Security=True;Enlist=False;" providerName="System.Data.SqlClient" /> <dependentAssembly>
<add name="SqlServerFilesConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ASXFiles;Integrated Security=True;Enlist=False;" providerName="System.Data.SqlClient" /> <assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<add name="SqlServerSettingsConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ASXSettings;Integrated Security=True;Enlist=False;" providerName="System.Data.SqlClient" /> <bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</connectionStrings> </dependentAssembly>
<entityFramework> </assemblyBinding>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework"> </runtime>
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" /> </configuration>
</parameters> \ No newline at end of file
</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>
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;
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
handler = new ConsoleEventDelegate(ConsoleEventCallback); NativeMethods.Handler = ConsoleEventCallback;
SetConsoleCtrlHandler(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;
} }
controller.Visited += PageVisited;
//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();
} }
private static void PageVisited(VisitedEventArgs e)
{ private static bool ConsoleEventCallback(int eventType)
Console.WriteLine(string.Concat("Visited: ", e.URL));
}
static bool ConsoleEventCallback(int eventType)
{ {
if (eventType == 2) if (eventType != 2) return false;
try
{ {
try Controller.Stop();
{ }
controller.Stop(); catch
{
} // ignored
catch { }
} }
return false; return false;
} }
}
internal static class NativeMethods
{
// Keeps it from getting garbage collected // Keeps it from getting garbage collected
private static ConsoleEventDelegate handler; internal static ConsoleEventDelegate Handler;
// Pinvoke
private delegate bool ConsoleEventDelegate(int eventType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
[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.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 Titanium.Web.Proxy.EventArguments;
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;
namespace Titanium.Web.Proxy.Test 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 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.BeforeResponse += OnResponse;
if(Visited!=null) ProxyServer.EnableSsl = EnableSsl;
{
ProxyServer.BeforeRequest += OnRequest;
ProxyServer.BeforeResponse += OnResponse;
}
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.Start();
ProxyServer.ListeningPort = ProxyServer.ListeningPort;
ListeningPort = ProxyServer.ListeningPort; Console.WriteLine("Proxy listening on local machine port: {0} ", ProxyServer.ListeningPort);
Console.WriteLine(String.Format("Proxy listening on local machine port: {0} ", ProxyServer.ListeningPort));
} }
public void Stop() public void Stop()
{ {
if (Visited!=null) ProxyServer.BeforeRequest -= OnRequest;
{ ProxyServer.BeforeResponse -= OnResponse;
ProxyServer.BeforeRequest -= OnRequest;
ProxyServer.BeforeResponse -= OnResponse;
}
ProxyServer.Stop();
}
public delegate void SiteVisitedEventHandler(VisitedEventArgs e); ProxyServer.Stop();
public event SiteVisitedEventHandler Visited; }
// Invoke the Changed event; called whenever list changes
protected virtual void OnChanged(VisitedEventArgs e)
{
if (Visited != null)
Visited(e);
}
//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)
{ {
string Random = e.RequestURL.Substring(e.RequestURL.LastIndexOf(@"/") + 1); Console.WriteLine(e.RequestUrl);
int index = _URLList.IndexOf(Random);
if (index >= 0) ////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); //if (e.RequestURL.Contains("google.com"))
_lastURL = URL; //{
} // 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
//Insert script to read the Browser URL and send it back to proxy //Insert script to read the Browser URL and send it back to proxy
public void OnResponse(object sender, SessionEventArgs e) public void OnResponse(object sender, SessionEventArgs e)
{ {
try ////read response headers
{ //var responseHeaders = e.ResponseHeaders;
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 { }
} //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); // //Modify e.ServerResponse
private string RandomString(int size) // 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);
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();
}
// //Set modifed response Html Body
// e.SetResponseBodyString(modified);
} // }
public class VisitedEventArgs : EventArgs //}
{ }
public string URL;
public string hostname;
public IPAddress remoteIP { get; set; }
public int remotePort { get; set; }
} }
} }
\ No newline at end of file
...@@ -16,6 +16,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{6FD3B8 ...@@ -16,6 +16,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{6FD3B8
.nuget\NuGet.targets = .nuget\NuGet.targets .nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection EndProjectSection
EndProject 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 Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
...@@ -46,12 +52,30 @@ Global ...@@ -46,12 +52,30 @@ Global
{8D73A1BE-868C-42D2-9ECE-F32CC1A02906}.Release|x64.Build.0 = Release|x64 {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.ActiveCfg = Release|x86
{8D73A1BE-868C-42D2-9ECE-F32CC1A02906}.Release|x86.Build.0 = 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 EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution GlobalSection(NestedProjects) = preSolution
{F3B7E553-1904-4E80-BDC7-212342B5C952} = {B6DBABDC-C985-4872-9C38-B4E5079CBC4B} {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 EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
EnterpriseLibraryConfigurationToolBinariesPath = .1.505.2\lib\NET35 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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
using System.Text;
namespace Titanium.Web.Proxy.Helpers 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 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)
{ {
var bytes = Encoding.ASCII.GetBytes(initialData); var bytes = Encoding.ASCII.GetBytes(initialData);
output.Write(bytes,0, bytes.Length); output.Write(bytes, 0, bytes.Length);
CopyTo(input, output, bufferSize); 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 try
{ {
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);
...@@ -66,7 +57,6 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -66,7 +57,6 @@ namespace Titanium.Web.Proxy.Helpers
// 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
...@@ -79,9 +69,11 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -79,9 +69,11 @@ namespace Titanium.Web.Proxy.Helpers
output.Flush(); output.Flush();
} }
catch { } catch
{
// ignored
}
// return to the caller ; // return to the caller ;
return;
} }
} }
} }
\ No newline at end of file
...@@ -6,10 +6,10 @@ using System.Security.Cryptography.X509Certificates; ...@@ -6,10 +6,10 @@ using System.Security.Cryptography.X509Certificates;
namespace Titanium.Web.Proxy.Helpers namespace Titanium.Web.Proxy.Helpers
{ {
public class CertificateManager 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 {5}";
private readonly IDictionary<string, X509Certificate2> _certificateCache; private readonly IDictionary<string, X509Certificate2> _certificateCache;
...@@ -69,6 +69,7 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -69,6 +69,7 @@ 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)) if (_certificateCache.ContainsKey(certificateName))
return _certificateCache[certificateName]; return _certificateCache[certificateName];
...@@ -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)
...@@ -164,13 +165,22 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -164,13 +165,22 @@ 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",
isRootCertificate ? "-h 1 -r" : string.Format("-pe -in \"{0}\" -is Root", RootCertificateName)); isRootCertificate ? "-h 1 -r" : string.Format("-pe -in \"{0}\" -is Root", RootCertificateName));
return certCreatArgs; 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.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
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;
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static string DecompressGzip(Stream input, Encoding e) 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())
{ {
using (var zip = new ZlibStream(ms, CompressionMode.Compress, true))
int read = 0;
var buffer = new byte[BUFFER_SIZE];
using (MemoryStream output = new MemoryStream())
{ {
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0) zip.Write(bytes, 0, bytes.Length);
{
output.Write(buffer, 0, read);
}
return e.GetString(output.ToArray());
} }
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)
{ {
using (var ms = new MemoryStream())
Byte[] bytes = e.GetBytes(ResponseData);
using (MemoryStream ms = new MemoryStream())
{ {
using (var zip = new DeflateStream(ms, CompressionMode.Compress, true))
using (Ionic.Zlib.ZlibStream zip = new Ionic.Zlib.ZlibStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
{ {
zip.Write(bytes, 0, bytes.Length); zip.Write(bytes, 0, bytes.Length);
} }
return ms.ToArray(); 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 (var ms = new MemoryStream())
using (MemoryStream ms = new MemoryStream())
{ {
using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
using (Ionic.Zlib.DeflateStream zip = new Ionic.Zlib.DeflateStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
{ {
zip.Write(bytes, 0, bytes.Length); zip.Write(bytes, 0, bytes.Length);
} }
return ms.ToArray(); return ms.ToArray();
} }
} }
public static byte[] CompressGzip(string ResponseData, Encoding e) public static byte[] DecompressGzip(Stream input)
{ {
Byte[] bytes = e.GetBytes(ResponseData); using (
var decompressor = new System.IO.Compression.GZipStream(input,
using (MemoryStream ms = new MemoryStream()) 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[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);
} }
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; 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);
} }
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;
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.Net.Configuration;
using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text;
namespace Titanium.Web.Proxy.Helpers namespace Titanium.Web.Proxy.Helpers
{ {
public class NetFrameworkHelper 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); 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.
// 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;
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
{ {
public static class SystemProxyHelper internal static class NativeMethods
{ {
[DllImport("wininet.dll")] [DllImport("wininet.dll")]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength); internal static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer,
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39; int dwBufferLength);
public const int INTERNET_OPTION_REFRESH = 37; }
static bool settingsReturn, refreshReturn;
static object prevProxyServer; public static class SystemProxyHelper
static object prevProxyEnable; {
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); 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 = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0); NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionSettingsChanged, IntPtr.Zero,0);
refreshReturn = 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.Sockets;
using System.Net; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Titanium.Web.Http;
using Titanium.Web.Proxy.Extensions;
namespace Titanium.Web.Proxy.Helpers 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(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(); public static void SendRaw(Stream clientStream, string httpCmd, List<HttpHeader> requestHeaders, string hostName,
receiveRelay.Start(); int tunnelPort, bool isHttps)
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)
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = null;
sb.Append(HttpCmd); if (httpCmd != null || requestHeaders != null)
sb.Append(Environment.NewLine);
string hostname = SecureHostName;
for (int i = 1; i < RequestLines.Count; i++)
{ {
var header = RequestLines[i]; sb = new StringBuilder();
if (httpCmd != null)
if (SecureHostName == null)
{ {
String[] headerParsed = HttpCmd.Split(colonSpaceSplit, 2, StringSplitOptions.None); sb.Append(httpCmd);
switch (headerParsed[0].ToLower()) sb.Append(Environment.NewLine);
}
if (requestHeaders != null)
foreach (var header in requestHeaders.Select(t => t.ToString()))
{ {
case "host": sb.Append(header);
var hostdetail = headerParsed[1]; sb.Append(Environment.NewLine);
if (hostdetail.Contains(":"))
hostname = hostdetail.Split(':')[0].Trim();
else
hostname = hostdetail.Trim();
break;
default:
break;
} }
}
sb.Append(header);
sb.Append(Environment.NewLine); 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); if (isHttps)
var tunnelStream = tunnelClient.GetStream() as System.IO.Stream; {
SslStream sslStream = null;
try
{
sslStream = new SslStream(tunnelStream);
sslStream.AuthenticateAsClient(hostName);
tunnelStream = sslStream;
}
catch
{
if (sslStream != null)
sslStream.Dispose();
if (IsHttps) throw;
{ }
var sslStream = new SslStream(tunnelStream); }
sslStream.AuthenticateAsClient(hostname);
tunnelStream = sslStream;
}
var sendRelay = new Task(() => StreamHelper.CopyTo(sb.ToString(), ClientStream, tunnelStream, BUFFER_SIZE)); var sendRelay = Task.Factory.StartNew(() =>
var receiveRelay = new Task(() => StreamHelper.CopyTo(tunnelStream, ClientStream, BUFFER_SIZE)); {
if (sb != null)
clientStream.CopyToAsync(sb.ToString(), tunnelStream, BUFFER_SIZE);
else
clientStream.CopyToAsync(tunnelStream, BUFFER_SIZE);
});
sendRelay.Start(); var receiveRelay = Task.Factory.StartNew(() => tunnelStream.CopyToAsync(clientStream, BUFFER_SIZE));
receiveRelay.Start();
Task.WaitAll(sendRelay, receiveRelay); Task.WaitAll(sendRelay, receiveRelay);
}
catch
{
if (tunnelStream != null)
{
tunnelStream.Close();
tunnelStream.Dispose();
}
if (tunnelStream != null) if (tunnelClient != null)
tunnelStream.Close(); tunnelClient.Close();
if (tunnelClient != null) throw;
tunnelClient.Close(); }
} }
} }
} }
\ 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;
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.Models; using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy.Helpers; using Titanium.Web.Proxy.Helpers;
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 object certificateAccessLock = new object(); private static readonly byte[] ChunkTrail = Encoding.ASCII.GetBytes(Environment.NewLine);
private static List<string> pinnedCertificateClients = new List<string>();
private static readonly byte[] ChunkEnd =
Encoding.ASCII.GetBytes(0.ToString("x2") + Environment.NewLine + Environment.NewLine);
private static TcpListener _listener;
private static TcpListener listener; public static List<string> ExcludedHttpsHostNameRegex = new List<string>();
private static Thread listenerThread;
public static event EventHandler<SessionEventArgs> BeforeRequest; static ProxyServer()
public static event EventHandler<SessionEventArgs> BeforeResponse; {
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 string RootCertificateName { get; set; }
public static bool EnableSSL { get; set; } public static bool EnableSsl { get; set; }
public static bool SetAsSystemProxy { get; set; } public static bool SetAsSystemProxy { get; set; }
public static Int32 ListeningPort public static int ListeningPort { get; set; }
{ public static IPAddress ListeningIpAddress { get; set; }
get
{
return ((IPEndPoint)listener.LocalEndpoint).Port;
}
}
public static CertificateManager CertManager { get; set; } public static event EventHandler<SessionEventArgs> BeforeRequest;
public static event EventHandler<SessionEventArgs> BeforeResponse;
static ProxyServer() public static void Initialize()
{
CertManager = new CertificateManager("Titanium",
"Titanium Root Certificate Authority");
}
public ProxyServer()
{ {
ServicePointManager.Expect100Continue = false;
WebRequest.DefaultWebProxy = null;
System.Net.ServicePointManager.Expect100Continue = false; ServicePointManager.DefaultConnectionLimit = 10;
System.Net.WebRequest.DefaultWebProxy = null; ServicePointManager.DnsRefreshTimeout = 3 * 60 * 1000; //3 minutes
System.Net.ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.DnsRefreshTimeout = 3 * 60 * 1000;//3 minutes
ServicePointManager.MaxServicePointIdleTime = 3 * 60 * 1000; ServicePointManager.MaxServicePointIdleTime = 3 * 60 * 1000;
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) //HttpWebRequest certificate validation callback
{ ServicePointManager.ServerCertificateValidationCallback =
if (sslPolicyErrors == SslPolicyErrors.None) return true; delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
else {
if (sslPolicyErrors == SslPolicyErrors.None) return true;
return false; 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() public static bool Start()
{ {
_listener = new TcpListener(ListeningIpAddress, ListeningPort);
listener = new TcpListener(IPAddress.Any, 0); _listener.Start();
listener.Start();
listenerThread = new Thread(new ParameterizedThreadStart(Listen)); ListeningPort = ((IPEndPoint)_listener.LocalEndpoint).Port;
listenerThread.IsBackground = true; // accept clients asynchronously
ShouldListen = true; _listener.BeginAcceptTcpClient(OnAcceptConnection, _listener);
listenerThread.Start(listener);
var certTrusted = false;
if (EnableSsl)
certTrusted = CertManager.CreateTrustedRootCertificate();
if (SetAsSystemProxy) if (SetAsSystemProxy)
{ {
SystemProxyHelper.EnableProxyHTTP("localhost", 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(); //If certificate was trusted by the machine
if (!certTrusted) 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; return true;
} }
private static void OnAcceptConnection(IAsyncResult asyn)
public static void Stop()
{
if (SetAsSystemProxy)
{
SystemProxyHelper.DisableAllProxy();
FireFoxHelper.RemoveFirefox();
}
ShouldListen = false;
listener.Stop();
listenerThread.Interrupt();
}
private static void Listen(Object obj)
{ {
TcpListener listener = (TcpListener)obj;
try try
{ {
while (ShouldListen) // Get the listener that handles the client request.
{ _listener.BeginAcceptTcpClient(OnAcceptConnection, _listener);
var client = listener.AcceptTcpClient(); var client = _listener.EndAcceptTcpClient(asyn);
Task.Factory.StartNew(() => HandleClient(client)); var Task = HandleClient(client);
}
} }
catch (ThreadInterruptedException) { } catch
catch (SocketException)
{ {
// 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 @@ ...@@ -66,9 +66,29 @@
<Reference Include="Ionic.Zip"> <Reference Include="Ionic.Zip">
<HintPath>..\packages\DotNetZip.1.9.3\lib\net20\Ionic.Zip.dll</HintPath> <HintPath>..\packages\DotNetZip.1.9.3\lib\net20\Ionic.Zip.dll</HintPath>
</Reference> </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" />
<Reference Include="System.configuration" /> <Reference Include="System.configuration" />
<Reference Include="System.Core" /> <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.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
...@@ -76,23 +96,30 @@ ...@@ -76,23 +96,30 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<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\CertificateManager.cs" />
<Compile Include="Helpers\Firefox.cs" /> <Compile Include="Helpers\Firefox.cs" />
<Compile Include="Helpers\SystemProxy.cs" /> <Compile Include="Helpers\SystemProxy.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RequestHandler.cs" /> <Compile Include="RequestHandler.cs" />
<Compile Include="ResponseHandler.cs" /> <Compile Include="ResponseHandler.cs" />
<Compile Include="Helpers\CustomBinaryReader.cs" />
<Compile Include="Helpers\NetFramework.cs" /> <Compile Include="Helpers\NetFramework.cs" />
<Compile Include="Helpers\Compression.cs" /> <Compile Include="Helpers\Compression.cs" />
<Compile Include="ProxyServer.cs" /> <Compile Include="ProxyServer.cs" />
<Compile Include="Models\SessionEventArgs.cs" /> <Compile Include="EventArguments\SessionEventArgs.cs" />
<Compile Include="Helpers\Tcp.cs" /> <Compile Include="Helpers\Tcp.cs" />
<Compile Include="Helpers\Stream.cs" /> <Compile Include="Extensions\StreamExtensions.cs" />
</ItemGroup> </ItemGroup>
<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>
<ItemGroup> <ItemGroup>
<None Include="app.config" />
<None Include="packages.config" /> <None Include="packages.config" />
<None Include="Titanium_Proxy_Test_Root.cer"> <None Include="Titanium_Proxy_Test_Root.cer">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
...@@ -111,6 +138,11 @@ ...@@ -111,6 +138,11 @@
</PropertyGroup> </PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" /> <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target> </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. <!-- 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. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <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"?> <?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" />
<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> </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