Skip to content
This repository was archived by the owner on Jul 9, 2023. It is now read-only.

beta #639

Merged
merged 7 commits into from
Oct 5, 2019
Merged

beta #639

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .build/build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ if($Branch -eq "beta" ) { $Version = "$Version-beta" }

$NuGet = Join-Path $RepoRoot ".nuget\nuget.exe"

$MSBuild = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\msbuild.exe"
$MSBuild = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\msbuild.exe"
$MSBuild -replace ' ', '` '

FormatTaskName (("-"*25) + "[{0}]" + ("-"*25))
Expand Down
2 changes: 1 addition & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

# version format
version: 3.1.{build}
image: Visual Studio 2017
image: Visual Studio 2019

shallow_clone: false

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
<UseWPF>true</UseWPF>
</PropertyGroup>

<!--<ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net461'">
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="WindowsBase" />
</ItemGroup>-->
</ItemGroup>

<ItemGroup>
<Compile Remove="Properties\AssemblyInfo.cs" />
Expand All @@ -20,23 +20,6 @@
<ProjectReference Include="..\..\src\Titanium.Web.Proxy\Titanium.Web.Proxy.csproj" />
</ItemGroup>

<!--<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Update="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>
<Compile Update="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
</Compile>
</ItemGroup>

<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
Expand All @@ -52,16 +35,6 @@
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Update="App.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>-->
</ItemGroup>

</Project>
3 changes: 2 additions & 1 deletion src/Titanium.Web.Proxy.sln
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ Global
{4406CE17-9A39-4F28-8363-6169A4F799C1}.Debug|x64.ActiveCfg = Debug|Any CPU
{4406CE17-9A39-4F28-8363-6169A4F799C1}.Debug|x64.Build.0 = Debug|Any CPU
{4406CE17-9A39-4F28-8363-6169A4F799C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4406CE17-9A39-4F28-8363-6169A4F799C1}.Release|Any CPU.Build.0 = Release|Any CPU
{4406CE17-9A39-4F28-8363-6169A4F799C1}.Release|x64.ActiveCfg = Release|Any CPU
{4406CE17-9A39-4F28-8363-6169A4F799C1}.Release|x64.Build.0 = Release|Any CPU
{1D053D72-DCB4-4517-ACDD-D35ADC186950}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
Expand All @@ -89,7 +90,7 @@ Global
{1D053D72-DCB4-4517-ACDD-D35ADC186950} = {BC1E0789-D348-49CF-8B67-5E99D50EDF64}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {625C1EB5-44CF-47DE-A85A-B4C8C40ED90A}
EnterpriseLibraryConfigurationToolBinariesPath = .1.505.2\lib\NET35
SolutionGuid = {625C1EB5-44CF-47DE-A85A-B4C8C40ED90A}
EndGlobalSection
EndGlobal
11 changes: 4 additions & 7 deletions src/Titanium.Web.Proxy/ExplicitClientHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -288,8 +288,7 @@ await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response,
if (!clientStream.IsClosed && !connection.Stream.IsClosed)
{
await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool,
null, null,
connectArgs.CancellationTokenSource, ExceptionFunc);
null, null, connectArgs.CancellationTokenSource, ExceptionFunc);
}
}
finally
Expand Down Expand Up @@ -338,17 +337,15 @@ await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool,
await connection.StreamWriter.WriteLineAsync("SM", cancellationToken);
await connection.StreamWriter.WriteLineAsync(cancellationToken);
#if NETCOREAPP2_1
await Http2Helper.SendHttp2(clientStream, connection.Stream, BufferPool.BufferSize,
(buffer, offset, count) => { connectArgs.OnDecryptedDataSent(buffer, offset, count); },
(buffer, offset, count) => { connectArgs.OnDecryptedDataReceived(buffer, offset, count); },
await Http2Helper.SendHttp2(clientStream, connection.Stream,
() => new SessionEventArgs(this, endPoint, cancellationTokenSource)
{
ProxyClient = { Connection = clientConnection },
HttpClient = { ConnectRequest = connectArgs?.HttpClient.ConnectRequest },
UserData = connectArgs?.UserData
},
async args => { await invokeBeforeRequest(args); },
async args => { await invokeBeforeResponse(args); },
async args => { await onBeforeRequest(args); },
async args => { await onBeforeResponse(args); },
connectArgs.CancellationTokenSource, clientConnection.Id, ExceptionFunc);
#endif
}
Expand Down
4 changes: 2 additions & 2 deletions src/Titanium.Web.Proxy/Extensions/SslExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ internal static string GetServerName(this ClientHelloInfo clientHelloInfo)
return null;
}

#if NETCOREAPP2_1
#if NETCOREAPP2_1 || NETSTANDARD2_1
internal static List<SslApplicationProtocol> GetAlpn(this ClientHelloInfo clientHelloInfo)
{
if (clientHelloInfo.Extensions != null && clientHelloInfo.Extensions.TryGetValue("ALPN", out var alpnExtension))
Expand Down Expand Up @@ -78,7 +78,7 @@ internal static Task AuthenticateAsServerAsync(this SslStream sslStream, SslServ
#endif
}

#if !NETCOREAPP2_1
#if !NETCOREAPP2_1 && !NETSTANDARD2_1
internal enum SslApplicationProtocol
{
Http11,
Expand Down
34 changes: 21 additions & 13 deletions src/Titanium.Web.Proxy/Helpers/HttpHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,20 +151,28 @@ internal static Task<int> IsPriMethod(ICustomStreamReader clientStreamReader, IB
/// </returns>
private static async Task<int> startsWith(ICustomStreamReader clientStreamReader, IBufferPool bufferPool, string expectedStart, CancellationToken cancellationToken = default)
{
int iRet = -1;
const int lengthToCheck = 10;
byte[] buffer = null;
try
{
buffer = bufferPool.GetBuffer(Math.Max(bufferPool.BufferSize, lengthToCheck));
if (bufferPool.BufferSize < lengthToCheck)
{
throw new Exception($"Buffer is too small. Minimum size is {lengthToCheck} bytes");
}

int peeked = await clientStreamReader.PeekBytesAsync(buffer, 0, 0, lengthToCheck, cancellationToken);
buffer = bufferPool.GetBuffer(bufferPool.BufferSize);

if (peeked > 0)
bool isExpected = true;
int i = 0;
while (i < lengthToCheck)
{
bool isExpected = true;
int peeked = await clientStreamReader.PeekBytesAsync(buffer, i, i, lengthToCheck - i, cancellationToken);
if (peeked == 0)
return - 1;

peeked += i;

for (int i = 0; i < lengthToCheck; i++)
while (i < peeked)
{
int b = buffer[i];

Expand All @@ -173,23 +181,23 @@ private static async Task<int> startsWith(ICustomStreamReader clientStreamReader
else
{
char ch = (char)b;
if (!char.IsLetter(ch))
if (ch < 'A' || ch > 'z' || (ch > 'Z' && ch < 'a')) // ASCII letter
return -1;
else if (i >= expectedStart.Length || ch != expectedStart[i])
isExpected = false;
isExpected = false;
}
}

// only letters
iRet = isExpected ? 1 : 0;
i++;
}
}

// only letters
return 0;
}
finally
{
bufferPool.ReturnBuffer(buffer);
buffer = null;
}
return iRet;
}
}
}
33 changes: 19 additions & 14 deletions src/Titanium.Web.Proxy/Http2/Http2Helper.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#if NETCOREAPP2_1
#if NETCOREAPP2_1 || NETSTANDARD2_1
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
Expand All @@ -24,8 +24,7 @@ internal class Http2Helper
/// Task-based Asynchronous Pattern
/// </summary>
/// <returns></returns>
internal static async Task SendHttp2(Stream clientStream, Stream serverStream, int bufferSize,
Action<byte[], int, int> onDataSend, Action<byte[], int, int> onDataReceive,
internal static async Task SendHttp2(Stream clientStream, Stream serverStream,
Func<SessionEventArgs> sessionFactory,
Func<SessionEventArgs, Task> onBeforeRequest, Func<SessionEventArgs, Task> onBeforeResponse,
CancellationTokenSource cancellationTokenSource, Guid connectionId,
Expand All @@ -38,25 +37,25 @@ internal static async Task SendHttp2(Stream clientStream, Stream serverStream, i

// Now async relay all server=>client & client=>server data
var sendRelay =
copyHttp2FrameAsync(clientStream, serverStream, onDataSend, clientSettings, serverSettings,
copyHttp2FrameAsync(clientStream, serverStream, clientSettings, serverSettings,
sessionFactory, sessions, onBeforeRequest,
bufferSize, connectionId, true, cancellationTokenSource.Token, exceptionFunc);
connectionId, true, cancellationTokenSource.Token, exceptionFunc);
var receiveRelay =
copyHttp2FrameAsync(serverStream, clientStream, onDataReceive, serverSettings, clientSettings,
copyHttp2FrameAsync(serverStream, clientStream, serverSettings, clientSettings,
sessionFactory, sessions, onBeforeResponse,
bufferSize, connectionId, false, cancellationTokenSource.Token, exceptionFunc);
connectionId, false, cancellationTokenSource.Token, exceptionFunc);

await Task.WhenAny(sendRelay, receiveRelay);
cancellationTokenSource.Cancel();

await Task.WhenAll(sendRelay, receiveRelay);
}

private static async Task copyHttp2FrameAsync(Stream input, Stream output, Action<byte[], int, int> onCopy,
private static async Task copyHttp2FrameAsync(Stream input, Stream output,
Http2Settings localSettings, Http2Settings remoteSettings,
Func<SessionEventArgs> sessionFactory, ConcurrentDictionary<int, SessionEventArgs> sessions,
Func<SessionEventArgs, Task> onBeforeRequestResponse,
int bufferSize, Guid connectionId, bool isClient, CancellationToken cancellationToken,
Guid connectionId, bool isClient, CancellationToken cancellationToken,
ExceptionHandler exceptionFunc)
{
int headerTableSize = 0;
Expand All @@ -69,7 +68,6 @@ private static async Task copyHttp2FrameAsync(Stream input, Stream output, Actio
{
var frameHeaderBuffer = frameHeader.Buffer;
int read = await forceRead(input, frameHeaderBuffer, 0, 9, cancellationToken);
onCopy(frameHeaderBuffer, 0, read);
if (read != 9)
{
return;
Expand All @@ -92,7 +90,6 @@ private static async Task copyHttp2FrameAsync(Stream input, Stream output, Actio
}

read = await forceRead(input, buffer, 0, length, cancellationToken);
onCopy(buffer, 0, read);
if (read != length)
{
return;
Expand Down Expand Up @@ -127,6 +124,11 @@ private static async Task copyHttp2FrameAsync(Stream input, Stream output, Actio
//System.Diagnostics.Debug.WriteLine("CONN: " + connectionId + ", CLIENT: " + isClient + ", STREAM: " + streamId + ", TYPE: " + type);
if (type == Http2FrameType.Data && args != null)
{
if (isClient)
args.OnDataSent(buffer, 0, read);
else
args.OnDataReceived(buffer, 0, read);

rr = isClient ? (RequestResponseBase)args.HttpClient.Request : args.HttpClient.Response;

bool padded = (flags & Http2FrameFlag.Padded) != 0;
Expand Down Expand Up @@ -182,8 +184,10 @@ private static async Task copyHttp2FrameAsync(Stream input, Stream output, Actio
{
args = sessionFactory();
args.IsPromise = true;
sessions.TryAdd(streamId, args);
sessions.TryAdd(promisedStreamId, args);
if (!sessions.TryAdd(streamId, args))
;
if (!sessions.TryAdd(promisedStreamId, args))
;
}

System.Diagnostics.Debug.WriteLine("PROMISE STREAM: " + streamId + ", " + promisedStreamId +
Expand All @@ -201,7 +205,8 @@ private static async Task copyHttp2FrameAsync(Stream input, Stream output, Actio
if (!sessions.TryGetValue(streamId, out args))
{
args = sessionFactory();
sessions.TryAdd(streamId, args);
if (!sessions.TryAdd(streamId, args))
;
}

rr = isClient ? (RequestResponseBase)args.HttpClient.Request : args.HttpClient.Response;
Expand Down
2 changes: 1 addition & 1 deletion src/Titanium.Web.Proxy/Network/Tcp/TcpClientConnection.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System;
using System.IO;
using System.Net;
#if NETCOREAPP2_1
#if NETCOREAPP2_1 || NETSTANDARD2_1
using System.Net.Security;
#endif
using System.Net.Sockets;
Expand Down
2 changes: 1 addition & 1 deletion src/Titanium.Web.Proxy/Network/Tcp/TcpConnectionFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ private async Task<TcpServerConnection> createServerConnection(string remoteHost
CertificateRevocationCheckMode = proxyServer.CheckCertificateRevocation
};
await sslStream.AuthenticateAsClientAsync(options, cancellationToken);
#if NETCOREAPP2_1
#if NETCOREAPP2_1 || NETSTANDARD2_1
negotiatedApplicationProtocol = sslStream.NegotiatedApplicationProtocol;
#endif

Expand Down
2 changes: 1 addition & 1 deletion src/Titanium.Web.Proxy/Network/Tcp/TcpServerConnection.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System;
using System.Net;
#if NETCOREAPP2_1
#if NETCOREAPP2_1 || NETSTANDARD2_1
using System.Net.Security;
#endif
using System.Net.Sockets;
Expand Down
1 change: 1 addition & 0 deletions src/Titanium.Web.Proxy/ProxyServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ public ProxyServer(string rootCertificateName, string rootCertificateIssuerName,
/// The buffer pool used throughout this proxy instance.
/// Set custom implementations by implementing this interface.
/// By default this uses DefaultBufferPool implementation available in StreamExtended library package.
/// Buffer size should be at least 10 bytes.
/// </summary>
public IBufferPool BufferPool { get; set; }

Expand Down
14 changes: 7 additions & 7 deletions src/Titanium.Web.Proxy/RequestHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using System.Linq;
using System.Net;
using System.Net.Sockets;
#if NETCOREAPP2_1
#if NETCOREAPP2_1 || NETSTANDARD2_1
using System.Net.Security;
#endif
using System.Text.RegularExpressions;
Expand Down Expand Up @@ -143,7 +143,7 @@ await HeaderParser.ReadHeaders(clientStream, args.HttpClient.Request.Headers,
// proxy authorization check
if (httpsConnectHostname == null && await checkAuthorization(args) == false)
{
await invokeBeforeResponse(args);
await onBeforeResponse(args);

// send the response
await clientStreamWriter.WriteResponseAsync(args.HttpClient.Response,
Expand All @@ -166,10 +166,8 @@ await clientStreamWriter.WriteResponseAsync(args.HttpClient.Response,
// we need this to syphon out data from connection if API user changes them.
request.SetOriginalHeaders();

args.TimeLine["Request Received"] = DateTime.Now;

// If user requested interception do it
await invokeBeforeRequest(args);
await onBeforeRequest(args);

var response = args.HttpClient.Response;

Expand Down Expand Up @@ -286,7 +284,7 @@ await clientStreamWriter.WriteResponseAsync(args.HttpClient.Response,
}
finally
{
await invokeAfterResponse(args);
await onAfterResponse(args);
args.Dispose();
}
}
Expand Down Expand Up @@ -410,8 +408,10 @@ private void prepareRequestHeaders(HeaderCollection requestHeaders)
/// </summary>
/// <param name="args">The session event arguments.</param>
/// <returns></returns>
private async Task invokeBeforeRequest(SessionEventArgs args)
private async Task onBeforeRequest(SessionEventArgs args)
{
args.TimeLine["Request Received"] = DateTime.Now;

if (BeforeRequest != null)
{
await BeforeRequest.InvokeAsync(this, args, ExceptionFunc);
Expand Down
Loading