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

Commit 6535724

Browse files
committed
small fixes and improvements
1 parent ba42819 commit 6535724

30 files changed

+121
-147
lines changed

examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
<GridViewColumn Header="Process" DisplayMemberBinding="{Binding Process}" />
3232
<GridViewColumn Header="SentBytes" DisplayMemberBinding="{Binding SentDataCount}" />
3333
<GridViewColumn Header="ReceivedBytes" DisplayMemberBinding="{Binding ReceivedDataCount}" />
34+
<GridViewColumn Header="ClientEndPoint" DisplayMemberBinding="{Binding ClientEndPoint}" />
3435
</GridView>
3536
</ListView.View>
3637
</ListView>

examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,10 +226,11 @@ private SessionListItem createSessionListItem(SessionEventArgsBase e)
226226
{
227227
Number = lastSessionNumber,
228228
HttpClient = e.HttpClient,
229+
ClientEndPoint = e.ClientEndPoint,
229230
IsTunnelConnect = isTunnelConnect
230231
};
231232

232-
if (isTunnelConnect || e.HttpClient.Request.UpgradeToWebSocket)
233+
//if (isTunnelConnect || e.HttpClient.Request.UpgradeToWebSocket)
233234
{
234235
e.DataReceived += (sender, args) =>
235236
{

examples/Titanium.Web.Proxy.Examples.Wpf/SessionListItem.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.ComponentModel;
3+
using System.Net;
34
using System.Runtime.CompilerServices;
45
using Titanium.Web.Proxy.Examples.Wpf.Annotations;
56
using Titanium.Web.Proxy.Http;
@@ -22,6 +23,8 @@ public class SessionListItem : INotifyPropertyChanged
2223

2324
public HttpWebClient HttpClient { get; set; }
2425

26+
public IPEndPoint ClientEndPoint { get; set; }
27+
2528
public bool IsTunnelConnect { get; set; }
2629

2730
public string StatusCode

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ public async Task Finish()
132132
{
133133
if (bytesRemaining != -1)
134134
{
135-
var buffer = bufferPool.GetBuffer(baseStream.BufferSize);
135+
var buffer = bufferPool.GetBuffer();
136136
try
137137
{
138138
int res = await ReadAsync(buffer, 0, buffer.Length);

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

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,6 @@ private async Task readRequestBodyAsync(CancellationToken cancellationToken)
121121
// Now set the flag to true
122122
// So that next time we can deliver body from cache
123123
request.IsBodyRead = true;
124-
OnDataSent(body, 0, body.Length);
125124
}
126125
}
127126
}
@@ -194,7 +193,6 @@ private async Task readResponseBodyAsync(CancellationToken cancellationToken)
194193
// Now set the flag to true
195194
// So that next time we can deliver body from cache
196195
response.IsBodyRead = true;
197-
OnDataReceived(body, 0, body.Length);
198196
}
199197
}
200198
}
@@ -203,7 +201,7 @@ private async Task<byte[]> readBodyAsync(bool isRequest, CancellationToken cance
203201
{
204202
using (var bodyStream = new MemoryStream())
205203
{
206-
var writer = new HttpWriter(bodyStream, BufferPool, BufferSize);
204+
var writer = new HttpWriter(bodyStream, BufferPool);
207205

208206
if (isRequest)
209207
{
@@ -235,7 +233,7 @@ internal async Task SyphonOutBodyAsync(bool isRequest, CancellationToken cancell
235233

236234
using (var bodyStream = new MemoryStream())
237235
{
238-
var writer = new HttpWriter(bodyStream, BufferPool, BufferSize);
236+
var writer = new HttpWriter(bodyStream, BufferPool);
239237
await copyBodyAsync(isRequest, true, writer, TransformationMode.None, null, cancellationToken);
240238
}
241239
}
@@ -256,7 +254,7 @@ internal async Task CopyRequestBodyAsync(HttpWriter writer, TransformationMode t
256254
var reader = getStreamReader(true);
257255
string boundary = HttpHelper.GetBoundaryFromContentType(request.ContentType);
258256

259-
using (var copyStream = new CopyStream(reader, writer, BufferPool, BufferSize))
257+
using (var copyStream = new CopyStream(reader, writer, BufferPool))
260258
{
261259
while (contentLength > copyStream.ReadBytes)
262260
{
@@ -317,7 +315,7 @@ private async Task copyBodyAsync(bool isRequest, bool useOriginalHeaderValues, H
317315

318316
try
319317
{
320-
using (var bufStream = new CustomBufferedStream(s, BufferPool, BufferSize, true))
318+
using (var bufStream = new CustomBufferedStream(s, BufferPool, true))
321319
{
322320
await writer.CopyBodyAsync(bufStream, false, -1, onCopy, cancellationToken);
323321
}
@@ -339,7 +337,7 @@ private async Task<long> readUntilBoundaryAsync(ICustomStreamReader reader, long
339337
{
340338
int bufferDataLength = 0;
341339

342-
var buffer = BufferPool.GetBuffer(BufferSize);
340+
var buffer = BufferPool.GetBuffer();
343341
try
344342
{
345343
int boundaryLength = boundary.Length + 4;

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

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,11 @@ namespace Titanium.Web.Proxy.EventArguments
2121
public abstract class SessionEventArgsBase : EventArgs, IDisposable
2222
{
2323
internal readonly CancellationTokenSource CancellationTokenSource;
24+
2425
internal TcpServerConnection ServerConnection => HttpClient.Connection;
26+
2527
internal TcpClientConnection ClientConnection => ProxyClient.Connection;
2628

27-
protected readonly int BufferSize;
2829
protected readonly IBufferPool BufferPool;
2930
protected readonly ExceptionHandler ExceptionFunc;
3031

@@ -36,18 +37,16 @@ public abstract class SessionEventArgsBase : EventArgs, IDisposable
3637
/// <summary>
3738
/// Initializes a new instance of the <see cref="SessionEventArgsBase" /> class.
3839
/// </summary>
39-
private SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint,
40-
CancellationTokenSource cancellationTokenSource)
40+
private SessionEventArgsBase(ProxyServer server)
4141
{
42-
BufferSize = server.BufferSize;
4342
BufferPool = server.BufferPool;
4443
ExceptionFunc = server.ExceptionFunc;
4544
TimeLine["Session Created"] = DateTime.Now;
4645
}
4746

4847
protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint,
4948
CancellationTokenSource cancellationTokenSource,
50-
Request request) : this(server, endPoint, cancellationTokenSource)
49+
Request request) : this(server)
5150
{
5251
CancellationTokenSource = cancellationTokenSource;
5352

src/Titanium.Web.Proxy/ExplicitClientHandler.cs

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect
3535
var cancellationTokenSource = new CancellationTokenSource();
3636
var cancellationToken = cancellationTokenSource.Token;
3737

38-
var clientStream = new CustomBufferedStream(clientConnection.GetStream(), BufferPool, BufferSize);
39-
var clientStreamWriter = new HttpResponseWriter(clientStream, BufferPool, BufferSize);
38+
var clientStream = new CustomBufferedStream(clientConnection.GetStream(), BufferPool);
39+
var clientStreamWriter = new HttpResponseWriter(clientStream, BufferPool);
4040

4141
Task<TcpServerConnection> prefetchConnectionTask = null;
4242
bool closeServerConnection = false;
@@ -50,7 +50,7 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect
5050
TunnelConnectSessionEventArgs connectArgs = null;
5151

5252
// Client wants to create a secure tcp tunnel (probably its a HTTPS or Websocket request)
53-
if (await HttpHelper.IsConnectMethod(clientStream, BufferPool, BufferSize, cancellationToken) == 1)
53+
if (await HttpHelper.IsConnectMethod(clientStream, BufferPool, cancellationToken) == 1)
5454
{
5555
// read the first line HTTP command
5656
string httpCmd = await clientStream.ReadLineAsync(cancellationToken);
@@ -75,6 +75,8 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect
7575

7676
connectArgs = new TunnelConnectSessionEventArgs(this, endPoint, connectRequest,
7777
cancellationTokenSource);
78+
clientStream.DataRead += (o, args) => connectArgs.OnDataSent(args.Buffer, args.Offset, args.Count);
79+
clientStream.DataWrite += (o, args) => connectArgs.OnDataReceived(args.Buffer, args.Offset, args.Count);
7880
connectArgs.ProxyClient.Connection = clientConnection;
7981
connectArgs.ProxyClient.ClientStream = clientStream;
8082

@@ -213,8 +215,8 @@ await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response,
213215
#endif
214216

215217
// HTTPS server created - we can now decrypt the client's traffic
216-
clientStream = new CustomBufferedStream(sslStream, BufferPool, BufferSize);
217-
clientStreamWriter = new HttpResponseWriter(clientStream, BufferPool, BufferSize);
218+
clientStream = new CustomBufferedStream(sslStream, BufferPool);
219+
clientStreamWriter = new HttpResponseWriter(clientStream, BufferPool);
218220
}
219221
catch (Exception e)
220222
{
@@ -223,7 +225,7 @@ await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response,
223225
$"Couldn't authenticate host '{connectHostname}' with certificate '{certName}'.", e, connectArgs);
224226
}
225227

226-
if (await HttpHelper.IsConnectMethod(clientStream, BufferPool, BufferSize, cancellationToken) == -1)
228+
if (await HttpHelper.IsConnectMethod(clientStream, BufferPool, cancellationToken) == -1)
227229
{
228230
decryptSsl = false;
229231
}
@@ -263,7 +265,7 @@ await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response,
263265
if (available > 0)
264266
{
265267
// send the buffered data
266-
var data = BufferPool.GetBuffer(BufferSize);
268+
var data = BufferPool.GetBuffer();
267269

268270
try
269271
{
@@ -283,10 +285,8 @@ await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response,
283285

284286
if (!clientStream.IsClosed && !connection.Stream.IsClosed)
285287
{
286-
await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool, BufferSize,
287-
(buffer, offset, count) => { connectArgs.OnDataSent(buffer, offset, count); },
288-
(buffer, offset, count) => { connectArgs.OnDataReceived(buffer, offset, count); },
289-
connectArgs.CancellationTokenSource, ExceptionFunc);
288+
await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool,
289+
null, null, connectArgs.CancellationTokenSource, ExceptionFunc);
290290
}
291291
}
292292
finally
@@ -298,7 +298,7 @@ await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool, BufferSize,
298298
}
299299
}
300300

301-
if (connectArgs != null && await HttpHelper.IsPriMethod(clientStream, BufferPool, BufferSize, cancellationToken) == 1)
301+
if (connectArgs != null && await HttpHelper.IsPriMethod(clientStream, BufferPool, cancellationToken) == 1)
302302
{
303303
// todo
304304
string httpCmd = await clientStream.ReadLineAsync(cancellationToken);
@@ -335,7 +335,7 @@ await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool, BufferSize,
335335
await connection.StreamWriter.WriteLineAsync("SM", cancellationToken);
336336
await connection.StreamWriter.WriteLineAsync(cancellationToken);
337337
#if NETCOREAPP2_1
338-
await Http2Helper.SendHttp2(clientStream, connection.Stream, BufferSize,
338+
await Http2Helper.SendHttp2(clientStream, connection.Stream, BufferPool.BufferSize,
339339
(buffer, offset, count) => { connectArgs.OnDataSent(buffer, offset, count); },
340340
(buffer, offset, count) => { connectArgs.OnDataReceived(buffer, offset, count); },
341341
() => new SessionEventArgs(this, endPoint, cancellationTokenSource)
@@ -357,6 +357,7 @@ await Http2Helper.SendHttp2(clientStream, connection.Stream, BufferSize,
357357
}
358358

359359
calledRequestHandler = true;
360+
360361
// Now create the request
361362
await handleHttpSessionRequest(endPoint, clientConnection, clientStream, clientStreamWriter,
362363
cancellationTokenSource, connectHostname, connectArgs, prefetchConnectionTask);

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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,10 @@ internal static class StreamExtensions
1818
/// <param name="output"></param>
1919
/// <param name="onCopy"></param>
2020
/// <param name="bufferPool"></param>
21-
/// <param name="bufferSize"></param>
2221
internal static Task CopyToAsync(this Stream input, Stream output, Action<byte[], int, int> onCopy,
23-
IBufferPool bufferPool, int bufferSize)
22+
IBufferPool bufferPool)
2423
{
25-
return CopyToAsync(input, output, onCopy, bufferPool, bufferSize, CancellationToken.None);
24+
return CopyToAsync(input, output, onCopy, bufferPool, CancellationToken.None);
2625
}
2726

2827
/// <summary>
@@ -32,12 +31,11 @@ internal static Task CopyToAsync(this Stream input, Stream output, Action<byte[]
3231
/// <param name="output"></param>
3332
/// <param name="onCopy"></param>
3433
/// <param name="bufferPool"></param>
35-
/// <param name="bufferSize"></param>
3634
/// <param name="cancellationToken"></param>
3735
internal static async Task CopyToAsync(this Stream input, Stream output, Action<byte[], int, int> onCopy,
38-
IBufferPool bufferPool, int bufferSize, CancellationToken cancellationToken)
36+
IBufferPool bufferPool, CancellationToken cancellationToken)
3937
{
40-
var buffer = bufferPool.GetBuffer(bufferSize);
38+
var buffer = bufferPool.GetBuffer();
4139
try
4240
{
4341
while (!cancellationToken.IsCancellationRequested)

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,5 @@ internal static string GetOriginalPathAndQuery(this Uri uri)
1212

1313
return uri.IsWellFormedOriginalString() ? uri.PathAndQuery : uri.GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);
1414
}
15-
}
15+
}
1616
}

src/Titanium.Web.Proxy/Helpers/HttpHelper.cs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -128,39 +128,35 @@ internal static string GetWildCardDomainName(string hostname)
128128
/// <summary>
129129
/// Determines whether is connect method.
130130
/// </summary>
131-
/// <param name="clientStreamReader">The client stream reader.</param>
132131
/// <returns>1: when CONNECT, 0: when valid HTTP method, -1: otherwise</returns>
133-
internal static Task<int> IsConnectMethod(ICustomStreamReader clientStreamReader, IBufferPool bufferPool, int bufferSize, CancellationToken cancellationToken = default)
132+
internal static Task<int> IsConnectMethod(ICustomStreamReader clientStreamReader, IBufferPool bufferPool, CancellationToken cancellationToken = default)
134133
{
135-
return startsWith(clientStreamReader, bufferPool, bufferSize, "CONNECT", cancellationToken);
134+
return startsWith(clientStreamReader, bufferPool, "CONNECT", cancellationToken);
136135
}
137136

138137
/// <summary>
139138
/// Determines whether is pri method (HTTP/2).
140139
/// </summary>
141-
/// <param name="clientStreamReader">The client stream reader.</param>
142140
/// <returns>1: when PRI, 0: when valid HTTP method, -1: otherwise</returns>
143-
internal static Task<int> IsPriMethod(ICustomStreamReader clientStreamReader, IBufferPool bufferPool, int bufferSize, CancellationToken cancellationToken = default)
141+
internal static Task<int> IsPriMethod(ICustomStreamReader clientStreamReader, IBufferPool bufferPool, CancellationToken cancellationToken = default)
144142
{
145-
return startsWith(clientStreamReader, bufferPool, bufferSize, "PRI", cancellationToken);
143+
return startsWith(clientStreamReader, bufferPool, "PRI", cancellationToken);
146144
}
147145

148146
/// <summary>
149147
/// Determines whether the stream starts with the given string.
150148
/// </summary>
151-
/// <param name="clientStreamReader">The client stream reader.</param>
152-
/// <param name="expectedStart">The expected start.</param>
153149
/// <returns>
154150
/// 1: when starts with the given string, 0: when valid HTTP method, -1: otherwise
155151
/// </returns>
156-
private static async Task<int> startsWith(ICustomStreamReader clientStreamReader, IBufferPool bufferPool, int bufferSize, string expectedStart, CancellationToken cancellationToken = default)
152+
private static async Task<int> startsWith(ICustomStreamReader clientStreamReader, IBufferPool bufferPool, string expectedStart, CancellationToken cancellationToken = default)
157153
{
158154
int iRet = -1;
159155
const int lengthToCheck = 10;
160156
byte[] buffer = null;
161157
try
162158
{
163-
buffer = bufferPool.GetBuffer(Math.Max(bufferSize, lengthToCheck));
159+
buffer = bufferPool.GetBuffer(Math.Max(bufferPool.BufferSize, lengthToCheck));
164160

165161
int peeked = await clientStreamReader.PeekBytesAsync(buffer, 0, 0, lengthToCheck, cancellationToken);
166162

src/Titanium.Web.Proxy/Helpers/HttpRequestWriter.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ namespace Titanium.Web.Proxy.Helpers
88
{
99
internal sealed class HttpRequestWriter : HttpWriter
1010
{
11-
internal HttpRequestWriter(Stream stream, IBufferPool bufferPool, int bufferSize)
12-
: base(stream, bufferPool, bufferSize)
11+
internal HttpRequestWriter(Stream stream, IBufferPool bufferPool)
12+
: base(stream, bufferPool)
1313
{
1414
}
1515

src/Titanium.Web.Proxy/Helpers/HttpResponseWriter.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ namespace Titanium.Web.Proxy.Helpers
99
{
1010
internal sealed class HttpResponseWriter : HttpWriter
1111
{
12-
internal HttpResponseWriter(Stream stream, IBufferPool bufferPool, int bufferSize)
13-
: base(stream, bufferPool, bufferSize)
12+
internal HttpResponseWriter(Stream stream, IBufferPool bufferPool)
13+
: base(stream, bufferPool)
1414
{
1515
}
1616

src/Titanium.Web.Proxy/Helpers/HttpWriter.cs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,12 @@ internal class HttpWriter : ICustomStreamWriter
2020

2121
private static readonly Encoding encoder = Encoding.ASCII;
2222

23-
internal HttpWriter(Stream stream, IBufferPool bufferPool, int bufferSize)
23+
internal HttpWriter(Stream stream, IBufferPool bufferPool)
2424
{
25-
BufferSize = bufferSize;
2625
this.stream = stream;
2726
this.bufferPool = bufferPool;
2827
}
2928

30-
internal int BufferSize { get; }
31-
3229
/// <summary>
3330
/// Writes a line async
3431
/// </summary>
@@ -48,9 +45,9 @@ private async Task writeAsyncInternal(string value, bool addNewLine, Cancellatio
4845
{
4946
int newLineChars = addNewLine ? newLine.Length : 0;
5047
int charCount = value.Length;
51-
if (charCount < BufferSize - newLineChars)
48+
if (charCount < bufferPool.BufferSize - newLineChars)
5249
{
53-
var buffer = bufferPool.GetBuffer(BufferSize);
50+
var buffer = bufferPool.GetBuffer();
5451
try
5552
{
5653
int idx = encoder.GetBytes(value, 0, charCount, buffer, 0);
@@ -246,7 +243,7 @@ private async Task copyBodyChunkedAsync(ICustomStreamReader reader, Action<byte[
246243
private async Task copyBytesFromStream(ICustomStreamReader reader, long count, Action<byte[], int, int> onCopy,
247244
CancellationToken cancellationToken)
248245
{
249-
var buffer = bufferPool.GetBuffer(BufferSize);
246+
var buffer = bufferPool.GetBuffer();
250247

251248
try
252249
{

0 commit comments

Comments
 (0)