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

Commit ebed40b

Browse files
authored
Merge pull request #665 from justcoding121/beta
Stable
2 parents d8df61b + 3b807da commit ebed40b

38 files changed

+566
-704
lines changed

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

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.IO;
44
using System.Threading.Tasks;
55
using Titanium.Web.Proxy.Exceptions;
6+
using Titanium.Web.Proxy.Helpers;
67
using Titanium.Web.Proxy.StreamExtended.BufferPool;
78
using Titanium.Web.Proxy.StreamExtended.Network;
89

@@ -11,16 +12,16 @@ namespace Titanium.Web.Proxy.EventArguments
1112
internal class LimitedStream : Stream
1213
{
1314
private readonly IBufferPool bufferPool;
14-
private readonly CustomBufferedStream baseStream;
15+
private readonly IHttpStreamReader baseReader;
1516
private readonly bool isChunked;
1617
private long bytesRemaining;
1718

1819
private bool readChunkTrail;
1920

20-
internal LimitedStream(CustomBufferedStream baseStream, IBufferPool bufferPool, bool isChunked,
21+
internal LimitedStream(IHttpStreamReader baseStream, IBufferPool bufferPool, bool isChunked,
2122
long contentLength)
2223
{
23-
this.baseStream = baseStream;
24+
this.baseReader = baseStream;
2425
this.bufferPool = bufferPool;
2526
this.isChunked = isChunked;
2627
bytesRemaining = isChunked
@@ -49,12 +50,12 @@ private void getNextChunk()
4950
if (readChunkTrail)
5051
{
5152
// read the chunk trail of the previous chunk
52-
string? s = baseStream.ReadLineAsync().Result;
53+
string? s = baseReader.ReadLineAsync().Result;
5354
}
5455

5556
readChunkTrail = true;
5657

57-
string? chunkHead = baseStream.ReadLineAsync().Result!;
58+
string? chunkHead = baseReader.ReadLineAsync().Result!;
5859
int idx = chunkHead.IndexOf(";", StringComparison.Ordinal);
5960
if (idx >= 0)
6061
{
@@ -73,7 +74,7 @@ private void getNextChunk()
7374
bytesRemaining = -1;
7475

7576
// chunk trail
76-
var task = baseStream.ReadLineAsync();
77+
var task = baseReader.ReadLineAsync();
7778
if (!task.IsCompleted)
7879
task.AsTask().Wait();
7980
}
@@ -119,7 +120,7 @@ public override int Read(byte[] buffer, int offset, int count)
119120
}
120121

121122
int toRead = (int)Math.Min(count, bytesRemaining);
122-
int res = baseStream.Read(buffer, offset, toRead);
123+
int res = baseReader.Read(buffer, offset, toRead);
123124
bytesRemaining -= res;
124125

125126
if (res == 0)

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

Lines changed: 35 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using Titanium.Web.Proxy.Http.Responses;
1111
using Titanium.Web.Proxy.Models;
1212
using Titanium.Web.Proxy.Network;
13+
using Titanium.Web.Proxy.Network.Tcp;
1314
using Titanium.Web.Proxy.StreamExtended.Network;
1415

1516
namespace Titanium.Web.Proxy.EventArguments
@@ -22,8 +23,6 @@ namespace Titanium.Web.Proxy.EventArguments
2223
/// </summary>
2324
public class SessionEventArgs : SessionEventArgsBase
2425
{
25-
private static readonly byte[] emptyData = new byte[0];
26-
2726
/// <summary>
2827
/// Backing field for corresponding public property
2928
/// </summary>
@@ -37,8 +36,8 @@ public class SessionEventArgs : SessionEventArgsBase
3736
/// <summary>
3837
/// Constructor to initialize the proxy
3938
/// </summary>
40-
internal SessionEventArgs(ProxyServer server, ProxyEndPoint endPoint, ProxyClient proxyClient, ConnectRequest? connectRequest, CancellationTokenSource cancellationTokenSource)
41-
: base(server, endPoint, proxyClient, connectRequest, new Request(), cancellationTokenSource)
39+
internal SessionEventArgs(ProxyServer server, ProxyEndPoint endPoint, TcpClientConnection clientConnection, HttpClientStream clientStream, ConnectRequest? connectRequest, CancellationTokenSource cancellationTokenSource)
40+
: base(server, endPoint, clientConnection, clientStream, connectRequest, new Request(), cancellationTokenSource)
4241
{
4342
}
4443

@@ -66,14 +65,9 @@ public bool ReRequest
6665
/// </summary>
6766
public event EventHandler<MultipartRequestPartSentEventArgs>? MultipartRequestPartSent;
6867

69-
private CustomBufferedStream getStreamReader(bool isRequest)
70-
{
71-
return isRequest ? ProxyClient.ClientStream : HttpClient.Connection.Stream;
72-
}
73-
74-
private HttpWriter getStreamWriter(bool isRequest)
68+
private HttpStream getStream(bool isRequest)
7569
{
76-
return isRequest ? (HttpWriter)ProxyClient.ClientStreamWriter : HttpClient.Connection.StreamWriter;
70+
return isRequest ? (HttpStream)ClientStream : HttpClient.Connection.Stream;
7771
}
7872

7973
/// <summary>
@@ -110,7 +104,10 @@ private async Task readRequestBodyAsync(CancellationToken cancellationToken)
110104
else
111105
{
112106
var body = await readBodyAsync(true, cancellationToken);
113-
request.Body = body;
107+
if (!request.BodyAvailable)
108+
{
109+
request.Body = body;
110+
}
114111

115112
// Now set the flag to true
116113
// So that next time we can deliver body from cache
@@ -182,7 +179,10 @@ private async Task readResponseBodyAsync(CancellationToken cancellationToken)
182179
else
183180
{
184181
var body = await readBodyAsync(false, cancellationToken);
185-
response.Body = body;
182+
if (!response.BodyAvailable)
183+
{
184+
response.Body = body;
185+
}
186186

187187
// Now set the flag to true
188188
// So that next time we can deliver body from cache
@@ -193,21 +193,19 @@ private async Task readResponseBodyAsync(CancellationToken cancellationToken)
193193

194194
private async Task<byte[]> readBodyAsync(bool isRequest, CancellationToken cancellationToken)
195195
{
196-
using (var bodyStream = new MemoryStream())
197-
{
198-
var writer = new HttpWriter(bodyStream, BufferPool);
199-
200-
if (isRequest)
201-
{
202-
await CopyRequestBodyAsync(writer, TransformationMode.Uncompress, cancellationToken);
203-
}
204-
else
205-
{
206-
await CopyResponseBodyAsync(writer, TransformationMode.Uncompress, cancellationToken);
207-
}
196+
using var bodyStream = new MemoryStream();
197+
using var http = new HttpStream(bodyStream, BufferPool);
208198

209-
return bodyStream.ToArray();
199+
if (isRequest)
200+
{
201+
await CopyRequestBodyAsync(http, TransformationMode.Uncompress, cancellationToken);
202+
}
203+
else
204+
{
205+
await CopyResponseBodyAsync(http, TransformationMode.Uncompress, cancellationToken);
210206
}
207+
208+
return bodyStream.ToArray();
211209
}
212210

213211
/// <summary>
@@ -225,18 +223,16 @@ internal async Task SyphonOutBodyAsync(bool isRequest, CancellationToken cancell
225223
return;
226224
}
227225

228-
using (var bodyStream = new MemoryStream())
229-
{
230-
var writer = new HttpWriter(bodyStream, BufferPool);
231-
await copyBodyAsync(isRequest, true, writer, TransformationMode.None, null, cancellationToken);
232-
}
226+
using var bodyStream = new MemoryStream();
227+
using var http = new HttpStream(bodyStream, BufferPool);
228+
await copyBodyAsync(isRequest, true, http, TransformationMode.None, null, cancellationToken);
233229
}
234230

235231
/// <summary>
236232
/// This is called when the request is PUT/POST/PATCH to read the body
237233
/// </summary>
238234
/// <returns></returns>
239-
internal async Task CopyRequestBodyAsync(HttpWriter writer, TransformationMode transformation, CancellationToken cancellationToken)
235+
internal async Task CopyRequestBodyAsync(IHttpStreamWriter writer, TransformationMode transformation, CancellationToken cancellationToken)
240236
{
241237
var request = HttpClient.Request;
242238

@@ -245,7 +241,7 @@ internal async Task CopyRequestBodyAsync(HttpWriter writer, TransformationMode t
245241
// send the request body bytes to server
246242
if (contentLength > 0 && hasMulipartEventSubscribers && request.IsMultipartFormData)
247243
{
248-
var reader = getStreamReader(true);
244+
var reader = getStream(true);
249245
var boundary = HttpHelper.GetBoundaryFromContentType(request.ContentType);
250246

251247
using (var copyStream = new CopyStream(reader, writer, BufferPool))
@@ -275,14 +271,14 @@ internal async Task CopyRequestBodyAsync(HttpWriter writer, TransformationMode t
275271
}
276272
}
277273

278-
internal async Task CopyResponseBodyAsync(HttpWriter writer, TransformationMode transformation, CancellationToken cancellationToken)
274+
internal async Task CopyResponseBodyAsync(IHttpStreamWriter writer, TransformationMode transformation, CancellationToken cancellationToken)
279275
{
280276
await copyBodyAsync(false, false, writer, transformation, OnDataReceived, cancellationToken);
281277
}
282278

283-
private async Task copyBodyAsync(bool isRequest, bool useOriginalHeaderValues, HttpWriter writer, TransformationMode transformation, Action<byte[], int, int>? onCopy, CancellationToken cancellationToken)
279+
private async Task copyBodyAsync(bool isRequest, bool useOriginalHeaderValues, IHttpStreamWriter writer, TransformationMode transformation, Action<byte[], int, int>? onCopy, CancellationToken cancellationToken)
284280
{
285-
var stream = getStreamReader(isRequest);
281+
var stream = getStream(isRequest);
286282

287283
var requestResponse = isRequest ? (RequestResponseBase)HttpClient.Request : HttpClient.Response;
288284

@@ -309,10 +305,8 @@ private async Task copyBodyAsync(bool isRequest, bool useOriginalHeaderValues, H
309305

310306
try
311307
{
312-
using (var bufStream = new CustomBufferedStream(s, BufferPool, true))
313-
{
314-
await writer.CopyBodyAsync(bufStream, false, -1, onCopy, cancellationToken);
315-
}
308+
var http = new HttpStream(s, BufferPool, true);
309+
await writer.CopyBodyAsync(http, false, -1, onCopy, cancellationToken);
316310
}
317311
finally
318312
{
@@ -595,7 +589,7 @@ public void Redirect(string url, bool closeServerConnection = false)
595589
var response = new RedirectResponse();
596590
response.HttpVersion = HttpClient.Request.HttpVersion;
597591
response.Headers.AddHeader(KnownHeaders.Location, url);
598-
response.Body = emptyData;
592+
response.Body = Array.Empty<byte>();
599593

600594
Respond(response, closeServerConnection);
601595
}

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

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,12 @@ public abstract class SessionEventArgsBase : EventArgs, IDisposable
2626

2727
internal TcpServerConnection ServerConnection => HttpClient.Connection;
2828

29-
internal TcpClientConnection ClientConnection => ProxyClient.Connection;
29+
/// <summary>
30+
/// Holds a reference to client
31+
/// </summary>
32+
internal TcpClientConnection ClientConnection { get; }
33+
34+
internal HttpClientStream ClientStream { get; }
3035

3136
protected readonly IBufferPool BufferPool;
3237
protected readonly ExceptionHandler ExceptionFunc;
@@ -41,25 +46,21 @@ public abstract class SessionEventArgsBase : EventArgs, IDisposable
4146
/// Initializes a new instance of the <see cref="SessionEventArgsBase" /> class.
4247
/// </summary>
4348
private protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint,
44-
ProxyClient proxyClient, ConnectRequest? connectRequest, Request request, CancellationTokenSource cancellationTokenSource)
49+
TcpClientConnection clientConnection, HttpClientStream clientStream, ConnectRequest? connectRequest, Request request, CancellationTokenSource cancellationTokenSource)
4550
{
4651
BufferPool = server.BufferPool;
4752
ExceptionFunc = server.ExceptionFunc;
4853
TimeLine["Session Created"] = DateTime.Now;
4954

5055
CancellationTokenSource = cancellationTokenSource;
5156

52-
ProxyClient = proxyClient;
53-
HttpClient = new HttpWebClient(connectRequest, request, new Lazy<int>(() => ProxyClient.Connection.GetProcessId(endPoint)));
57+
ClientConnection = clientConnection;
58+
ClientStream = clientStream;
59+
HttpClient = new HttpWebClient(connectRequest, request, new Lazy<int>(() => clientConnection.GetProcessId(endPoint)));
5460
LocalEndPoint = endPoint;
5561
EnableWinAuth = server.EnableWinAuth && isWindowsAuthenticationSupported;
5662
}
5763

58-
/// <summary>
59-
/// Holds a reference to client
60-
/// </summary>
61-
internal ProxyClient ProxyClient { get; }
62-
6364
/// <summary>
6465
/// Returns a user data for this request/response session which is
6566
/// same as the user data of HttpClient.
@@ -93,7 +94,7 @@ public bool EnableWinAuth
9394
/// <summary>
9495
/// Client End Point.
9596
/// </summary>
96-
public IPEndPoint ClientEndPoint => (IPEndPoint)ProxyClient.Connection.RemoteEndPoint;
97+
public IPEndPoint ClientEndPoint => (IPEndPoint)ClientConnection.RemoteEndPoint;
9798

9899
/// <summary>
99100
/// The web client used to communicate with server for this session.
@@ -106,7 +107,7 @@ public bool EnableWinAuth
106107
/// <summary>
107108
/// Are we using a custom upstream HTTP(S) proxy?
108109
/// </summary>
109-
public ExternalProxy? CustomUpStreamProxyUsed { get; internal set; }
110+
public IExternalProxy? CustomUpStreamProxyUsed { get; internal set; }
110111

111112
/// <summary>
112113
/// Local endpoint via which we make the request.

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
using System;
22
using System.Threading;
3+
using Titanium.Web.Proxy.Helpers;
34
using Titanium.Web.Proxy.Http;
45
using Titanium.Web.Proxy.Models;
56
using Titanium.Web.Proxy.Network;
7+
using Titanium.Web.Proxy.Network.Tcp;
68
using Titanium.Web.Proxy.StreamExtended.Network;
79

810
namespace Titanium.Web.Proxy.EventArguments
@@ -15,8 +17,8 @@ public class TunnelConnectSessionEventArgs : SessionEventArgsBase
1517
private bool? isHttpsConnect;
1618

1719
internal TunnelConnectSessionEventArgs(ProxyServer server, ProxyEndPoint endPoint, ConnectRequest connectRequest,
18-
ProxyClient proxyClient, CancellationTokenSource cancellationTokenSource)
19-
: base(server, endPoint, proxyClient, connectRequest, connectRequest, cancellationTokenSource)
20+
TcpClientConnection clientConnection, HttpClientStream clientStream, CancellationTokenSource cancellationTokenSource)
21+
: base(server, endPoint, clientConnection, clientStream, connectRequest, connectRequest, cancellationTokenSource)
2022
{
2123
}
2224

0 commit comments

Comments
 (0)