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

Commit 183f960

Browse files
authored
Merge pull request #655 from justcoding121/master
beta
2 parents c6150bf + 7325e32 commit 183f960

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+786
-889
lines changed

examples/Titanium.Web.Proxy.Examples.Basic/ProxyTestController.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,6 @@ private async Task writeToConsole(string message, bool useRedColor = false)
278278
}
279279

280280
@lock.Release();
281-
282281
}
283282

284283
///// <summary>

src/Titanium.Web.Proxy/CertificateHandler.cs

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,10 @@ internal bool ValidateServerCertificate(object sender, X509Certificate certifica
2222
// if user callback is registered then do it
2323
if (ServerCertificateValidationCallback != null)
2424
{
25-
var args = new CertificateValidationEventArgs
26-
{
27-
Certificate = certificate,
28-
Chain = chain,
29-
SslPolicyErrors = sslPolicyErrors
30-
};
25+
var args = new CertificateValidationEventArgs(certificate, chain, sslPolicyErrors);
3126

3227
// why is the sender null?
33-
ServerCertificateValidationCallback.InvokeAsync(this, args, exceptionFunc).Wait();
28+
ServerCertificateValidationCallback.InvokeAsync(this, args, ExceptionFunc).Wait();
3429
return args.IsValid;
3530
}
3631

@@ -90,7 +85,7 @@ internal bool ValidateServerCertificate(object sender, X509Certificate certifica
9085
};
9186

9287
// why is the sender null?
93-
ClientCertificateSelectionCallback.InvokeAsync(this, args, exceptionFunc).Wait();
88+
ClientCertificateSelectionCallback.InvokeAsync(this, args, ExceptionFunc).Wait();
9489
return args.ClientCertificate;
9590
}
9691

src/Titanium.Web.Proxy/EventArguments/CertificateValidationEventArgs.cs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,27 @@ namespace Titanium.Web.Proxy.EventArguments
1010
/// </summary>
1111
public class CertificateValidationEventArgs : EventArgs
1212
{
13+
public CertificateValidationEventArgs(X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
14+
{
15+
Certificate = certificate;
16+
Chain = chain;
17+
SslPolicyErrors = sslPolicyErrors;
18+
}
19+
1320
/// <summary>
1421
/// Server certificate.
1522
/// </summary>
16-
public X509Certificate Certificate { get; internal set; }
23+
public X509Certificate Certificate { get; }
1724

1825
/// <summary>
1926
/// Certificate chain.
2027
/// </summary>
21-
public X509Chain Chain { get; internal set; }
28+
public X509Chain Chain { get; }
2229

2330
/// <summary>
2431
/// SSL policy errors.
2532
/// </summary>
26-
public SslPolicyErrors SslPolicyErrors { get; internal set; }
33+
public SslPolicyErrors SslPolicyErrors { get; }
2734

2835
/// <summary>
2936
/// Is the given server certificate valid?

src/Titanium.Web.Proxy/EventArguments/LimitedStream.cs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@ namespace Titanium.Web.Proxy.EventArguments
1111
internal class LimitedStream : Stream
1212
{
1313
private readonly IBufferPool bufferPool;
14-
private readonly ICustomStreamReader baseStream;
14+
private readonly CustomBufferedStream baseStream;
1515
private readonly bool isChunked;
1616
private long bytesRemaining;
1717

1818
private bool readChunkTrail;
1919

20-
internal LimitedStream(ICustomStreamReader baseStream, IBufferPool bufferPool, bool isChunked,
20+
internal LimitedStream(CustomBufferedStream baseStream, IBufferPool bufferPool, bool isChunked,
2121
long contentLength)
2222
{
2323
this.baseStream = baseStream;
@@ -49,12 +49,12 @@ private void getNextChunk()
4949
if (readChunkTrail)
5050
{
5151
// read the chunk trail of the previous chunk
52-
string s = baseStream.ReadLineAsync().Result;
52+
string? s = baseStream.ReadLineAsync().Result;
5353
}
5454

5555
readChunkTrail = true;
5656

57-
string chunkHead = baseStream.ReadLineAsync().Result;
57+
string? chunkHead = baseStream.ReadLineAsync().Result;
5858
int idx = chunkHead.IndexOf(";", StringComparison.Ordinal);
5959
if (idx >= 0)
6060
{
@@ -73,7 +73,9 @@ private void getNextChunk()
7373
bytesRemaining = -1;
7474

7575
// chunk trail
76-
baseStream.ReadLineAsync().Wait();
76+
var task = baseStream.ReadLineAsync();
77+
if (!task.IsCompleted)
78+
task.AsTask().Wait();
7779
}
7880
}
7981

src/Titanium.Web.Proxy/EventArguments/SessionEventArgs.cs

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using Titanium.Web.Proxy.Http;
1010
using Titanium.Web.Proxy.Http.Responses;
1111
using Titanium.Web.Proxy.Models;
12+
using Titanium.Web.Proxy.Network;
1213
using Titanium.Web.Proxy.StreamExtended.Network;
1314

1415
namespace Titanium.Web.Proxy.EventArguments
@@ -36,15 +37,8 @@ public class SessionEventArgs : SessionEventArgsBase
3637
/// <summary>
3738
/// Constructor to initialize the proxy
3839
/// </summary>
39-
internal SessionEventArgs(ProxyServer server, ProxyEndPoint endPoint,
40-
CancellationTokenSource cancellationTokenSource)
41-
: this(server, endPoint, null, cancellationTokenSource)
42-
{
43-
}
44-
45-
protected SessionEventArgs(ProxyServer server, ProxyEndPoint endPoint,
46-
Request? request, CancellationTokenSource cancellationTokenSource)
47-
: base(server, endPoint, cancellationTokenSource, request)
40+
internal SessionEventArgs(ProxyServer server, ProxyEndPoint endPoint, ProxyClient proxyClient, ConnectRequest? connectRequest, CancellationTokenSource cancellationTokenSource)
41+
: base(server, endPoint, proxyClient, connectRequest, null, cancellationTokenSource)
4842
{
4943
}
5044

@@ -72,7 +66,7 @@ public bool ReRequest
7266
/// </summary>
7367
public event EventHandler<MultipartRequestPartSentEventArgs>? MultipartRequestPartSent;
7468

75-
private ICustomStreamReader getStreamReader(bool isRequest)
69+
private CustomBufferedStream getStreamReader(bool isRequest)
7670
{
7771
return isRequest ? ProxyClient.ClientStream : HttpClient.Connection.Stream;
7872
}
@@ -333,7 +327,7 @@ private async Task copyBodyAsync(bool isRequest, bool useOriginalHeaderValues, H
333327
/// Read a line from the byte stream
334328
/// </summary>
335329
/// <returns></returns>
336-
private async Task<long> readUntilBoundaryAsync(ICustomStreamReader reader, long totalBytesToRead, ReadOnlyMemory<char> boundary, CancellationToken cancellationToken)
330+
private async Task<long> readUntilBoundaryAsync(ILineStream reader, long totalBytesToRead, ReadOnlyMemory<char> boundary, CancellationToken cancellationToken)
337331
{
338332
int bufferDataLength = 0;
339333

src/Titanium.Web.Proxy/EventArguments/SessionEventArgsBase.cs

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ public abstract class SessionEventArgsBase : EventArgs, IDisposable
2222
{
2323
private static bool isWindowsAuthenticationSupported => RunTime.IsWindows;
2424

25-
internal readonly CancellationTokenSource? CancellationTokenSource;
25+
internal readonly CancellationTokenSource CancellationTokenSource;
2626

2727
internal TcpServerConnection ServerConnection => HttpClient.Connection;
2828

@@ -40,25 +40,19 @@ public abstract class SessionEventArgsBase : EventArgs, IDisposable
4040
/// <summary>
4141
/// Initializes a new instance of the <see cref="SessionEventArgsBase" /> class.
4242
/// </summary>
43-
private SessionEventArgsBase(ProxyServer server)
43+
private protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint,
44+
ProxyClient proxyClient, ConnectRequest? connectRequest, Request? request, CancellationTokenSource cancellationTokenSource)
4445
{
4546
BufferPool = server.BufferPool;
4647
ExceptionFunc = server.ExceptionFunc;
4748
TimeLine["Session Created"] = DateTime.Now;
48-
}
4949

50-
protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint,
51-
CancellationTokenSource cancellationTokenSource,
52-
Request? request) : this(server)
53-
{
5450
CancellationTokenSource = cancellationTokenSource;
5551

56-
ProxyClient = new ProxyClient();
57-
HttpClient = new HttpWebClient(request);
52+
ProxyClient = proxyClient;
53+
HttpClient = new HttpWebClient(connectRequest, request, new Lazy<int>(() => ProxyClient.Connection.GetProcessId(endPoint)));
5854
LocalEndPoint = endPoint;
5955
EnableWinAuth = server.EnableWinAuth && isWindowsAuthenticationSupported;
60-
61-
HttpClient.ProcessId = new Lazy<int>(() => ProxyClient.Connection.GetProcessId(endPoint));
6256
}
6357

6458
/// <summary>
@@ -84,7 +78,7 @@ public bool EnableWinAuth
8478
get => enableWinAuth;
8579
set
8680
{
87-
if (!isWindowsAuthenticationSupported)
81+
if (value && !isWindowsAuthenticationSupported)
8882
throw new Exception("Windows Authentication is not supported");
8983

9084
enableWinAuth = value;

src/Titanium.Web.Proxy/EventArguments/TunnelConnectEventArgs.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System.Threading;
33
using Titanium.Web.Proxy.Http;
44
using Titanium.Web.Proxy.Models;
5+
using Titanium.Web.Proxy.Network;
56
using Titanium.Web.Proxy.StreamExtended.Network;
67

78
namespace Titanium.Web.Proxy.EventArguments
@@ -14,10 +15,9 @@ public class TunnelConnectSessionEventArgs : SessionEventArgsBase
1415
private bool? isHttpsConnect;
1516

1617
internal TunnelConnectSessionEventArgs(ProxyServer server, ProxyEndPoint endPoint, ConnectRequest connectRequest,
17-
CancellationTokenSource cancellationTokenSource)
18-
: base(server, endPoint, cancellationTokenSource, connectRequest)
18+
ProxyClient proxyClient, CancellationTokenSource cancellationTokenSource)
19+
: base(server, endPoint, proxyClient, connectRequest, connectRequest, cancellationTokenSource)
1920
{
20-
HttpClient.ConnectRequest = connectRequest;
2121
}
2222

2323
/// <summary>

src/Titanium.Web.Proxy/ExplicitClientHandler.cs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
using Titanium.Web.Proxy.Http;
1515
using Titanium.Web.Proxy.Http2;
1616
using Titanium.Web.Proxy.Models;
17+
using Titanium.Web.Proxy.Network;
1718
using Titanium.Web.Proxy.Network.Tcp;
1819
using Titanium.Web.Proxy.StreamExtended;
1920
using Titanium.Web.Proxy.StreamExtended.Network;
@@ -53,32 +54,30 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect
5354
if (await HttpHelper.IsConnectMethod(clientStream, BufferPool, cancellationToken) == 1)
5455
{
5556
// read the first line HTTP command
56-
string httpCmd = await clientStream.ReadLineAsync(cancellationToken);
57+
string? httpCmd = await clientStream.ReadLineAsync(cancellationToken);
5758
if (string.IsNullOrEmpty(httpCmd))
5859
{
5960
return;
6061
}
6162

62-
Request.ParseRequestLine(httpCmd, out string _, out string httpUrl, out var version);
63+
Request.ParseRequestLine(httpCmd!, out string _, out string httpUrl, out var version);
6364

6465
var httpRemoteUri = new Uri("http://" + httpUrl);
6566
connectHostname = httpRemoteUri.Host;
6667

6768
var connectRequest = new ConnectRequest
6869
{
6970
RequestUri = httpRemoteUri,
70-
OriginalUrl = httpUrl,
71+
OriginalUrlData = HttpHeader.Encoding.GetBytes(httpUrl),
7172
HttpVersion = version
7273
};
7374

7475
await HeaderParser.ReadHeaders(clientStream, connectRequest.Headers, cancellationToken);
7576

7677
connectArgs = new TunnelConnectSessionEventArgs(this, endPoint, connectRequest,
77-
cancellationTokenSource);
78+
new ProxyClient(clientConnection, clientStream, clientStreamWriter), cancellationTokenSource);
7879
clientStream.DataRead += (o, args) => connectArgs.OnDataSent(args.Buffer, args.Offset, args.Count);
7980
clientStream.DataWrite += (o, args) => connectArgs.OnDataReceived(args.Buffer, args.Offset, args.Count);
80-
connectArgs.ProxyClient.Connection = clientConnection;
81-
connectArgs.ProxyClient.ClientStream = clientStream;
8281

8382
await endPoint.InvokeBeforeTunnelConnectRequest(this, connectArgs, ExceptionFunc);
8483

@@ -303,7 +302,7 @@ await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool,
303302
if (connectArgs != null && await HttpHelper.IsPriMethod(clientStream, BufferPool, cancellationToken) == 1)
304303
{
305304
// todo
306-
string httpCmd = await clientStream.ReadLineAsync(cancellationToken);
305+
string? httpCmd = await clientStream.ReadLineAsync(cancellationToken);
307306
if (httpCmd == "PRI * HTTP/2.0")
308307
{
309308
connectArgs.HttpClient.ConnectRequest!.TunnelType = TunnelType.Http2;
@@ -336,10 +335,8 @@ await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool,
336335
var connectionPreface = new ReadOnlyMemory<byte>(Http2Helper.ConnectionPreface);
337336
await connection.StreamWriter.WriteAsync(connectionPreface, cancellationToken);
338337
await Http2Helper.SendHttp2(clientStream, connection.Stream,
339-
() => new SessionEventArgs(this, endPoint, cancellationTokenSource)
338+
() => new SessionEventArgs(this, endPoint, new ProxyClient(clientConnection, clientStream, clientStreamWriter), connectArgs?.HttpClient.ConnectRequest, cancellationTokenSource)
340339
{
341-
ProxyClient = { Connection = clientConnection },
342-
HttpClient = { ConnectRequest = connectArgs?.HttpClient.ConnectRequest },
343340
UserData = connectArgs?.UserData
344341
},
345342
async args => { await onBeforeRequest(args); },
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System;
2+
using Titanium.Web.Proxy.Models;
3+
4+
namespace Titanium.Web.Proxy.Extensions
5+
{
6+
internal static class HttpHeaderExtensions
7+
{
8+
internal static string GetString(this ByteString str)
9+
{
10+
return GetString(str.Span);
11+
}
12+
13+
internal static string GetString(this ReadOnlySpan<byte> bytes)
14+
{
15+
#if NETSTANDARD2_1
16+
return HttpHeader.Encoding.GetString(bytes);
17+
#else
18+
return HttpHeader.Encoding.GetString(bytes.ToArray());
19+
#endif
20+
}
21+
22+
internal static ByteString GetByteString(this string str)
23+
{
24+
return HttpHeader.Encoding.GetBytes(str);
25+
}
26+
}
27+
}

src/Titanium.Web.Proxy/Extensions/SslExtensions.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,19 +94,19 @@ internal class SslClientAuthenticationOptions
9494
{
9595
internal bool AllowRenegotiation { get; set; }
9696

97-
internal string TargetHost { get; set; }
97+
internal string? TargetHost { get; set; }
9898

99-
internal X509CertificateCollection ClientCertificates { get; set; }
99+
internal X509CertificateCollection? ClientCertificates { get; set; }
100100

101-
internal LocalCertificateSelectionCallback LocalCertificateSelectionCallback { get; set; }
101+
internal LocalCertificateSelectionCallback? LocalCertificateSelectionCallback { get; set; }
102102

103103
internal SslProtocols EnabledSslProtocols { get; set; }
104104

105105
internal X509RevocationMode CertificateRevocationCheckMode { get; set; }
106106

107-
internal List<SslApplicationProtocol> ApplicationProtocols { get; set; }
107+
internal List<SslApplicationProtocol>? ApplicationProtocols { get; set; }
108108

109-
internal RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; set; }
109+
internal RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get; set; }
110110

111111
internal EncryptionPolicy EncryptionPolicy { get; set; }
112112
}

src/Titanium.Web.Proxy/Extensions/StringExtensions.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Globalization;
3+
using Titanium.Web.Proxy.Models;
34

45
namespace Titanium.Web.Proxy.Extensions
56
{

src/Titanium.Web.Proxy/Extensions/UriExtensions.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Text;
23

34
namespace Titanium.Web.Proxy.Extensions
45
{
@@ -12,5 +13,5 @@ internal static string GetOriginalPathAndQuery(this Uri uri)
1213

1314
return uri.IsWellFormedOriginalString() ? uri.PathAndQuery : uri.GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);
1415
}
15-
}
16+
}
1617
}

0 commit comments

Comments
 (0)