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

Commit 47be26d

Browse files
committed
2 parents 8b41f88 + ded334f commit 47be26d

File tree

9 files changed

+108
-34
lines changed

9 files changed

+108
-34
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ private Task onBeforeTunnelConnectResponse(object sender, TunnelConnectSessionEv
151151
return Task.FromResult(false);
152152
}
153153

154-
// intecept & cancel redirect or update requests
154+
// intercept & cancel redirect or update requests
155155
private async Task onRequest(object sender, SessionEventArgs e)
156156
{
157157
await writeToConsole("Active Client Connections:" + ((ProxyServer)sender).ClientConnectionCount);

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

Lines changed: 93 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
using System;
22
using System.Globalization;
33
using System.IO;
4+
using System.Threading;
45
using System.Threading.Tasks;
56
using Titanium.Web.Proxy.Exceptions;
6-
using Titanium.Web.Proxy.Helpers;
77
using Titanium.Web.Proxy.StreamExtended.BufferPool;
88
using Titanium.Web.Proxy.StreamExtended.Network;
99

@@ -51,11 +51,22 @@ private void getNextChunk()
5151
{
5252
// read the chunk trail of the previous chunk
5353
string? s = baseReader.ReadLineAsync().Result;
54+
if (s == null)
55+
{
56+
bytesRemaining = -1;
57+
return;
58+
}
5459
}
5560

5661
readChunkTrail = true;
5762

58-
string? chunkHead = baseReader.ReadLineAsync().Result!;
63+
string? chunkHead = baseReader.ReadLineAsync().Result;
64+
if (chunkHead == null)
65+
{
66+
bytesRemaining = -1;
67+
return;
68+
}
69+
5970
int idx = chunkHead.IndexOf(";", StringComparison.Ordinal);
6071
if (idx >= 0)
6172
{
@@ -80,6 +91,50 @@ private void getNextChunk()
8091
}
8192
}
8293

94+
private async Task getNextChunkAsync()
95+
{
96+
if (readChunkTrail)
97+
{
98+
// read the chunk trail of the previous chunk
99+
string? s = await baseReader.ReadLineAsync();
100+
if (s == null)
101+
{
102+
bytesRemaining = -1;
103+
return;
104+
}
105+
}
106+
107+
readChunkTrail = true;
108+
109+
string? chunkHead = await baseReader.ReadLineAsync();
110+
if (chunkHead == null)
111+
{
112+
bytesRemaining = -1;
113+
return;
114+
}
115+
116+
int idx = chunkHead.IndexOf(";", StringComparison.Ordinal);
117+
if (idx >= 0)
118+
{
119+
chunkHead = chunkHead.Substring(0, idx);
120+
}
121+
122+
if (!int.TryParse(chunkHead, NumberStyles.HexNumber, null, out int chunkSize))
123+
{
124+
throw new ProxyHttpException($"Invalid chunk length: '{chunkHead}'", null, null);
125+
}
126+
127+
bytesRemaining = chunkSize;
128+
129+
if (chunkSize == 0)
130+
{
131+
bytesRemaining = -1;
132+
133+
// chunk trail
134+
await baseReader.ReadLineAsync();
135+
}
136+
}
137+
83138
public override void Flush()
84139
{
85140
throw new NotSupportedException();
@@ -131,6 +186,42 @@ public override int Read(byte[] buffer, int offset, int count)
131186
return res;
132187
}
133188

189+
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
190+
{
191+
if (bytesRemaining == -1)
192+
{
193+
return 0;
194+
}
195+
196+
if (bytesRemaining == 0)
197+
{
198+
if (isChunked)
199+
{
200+
await getNextChunkAsync();
201+
}
202+
else
203+
{
204+
bytesRemaining = -1;
205+
}
206+
}
207+
208+
if (bytesRemaining == -1)
209+
{
210+
return 0;
211+
}
212+
213+
int toRead = (int)Math.Min(count, bytesRemaining);
214+
int res = await baseReader.ReadAsync(buffer, offset, toRead, cancellationToken);
215+
bytesRemaining -= res;
216+
217+
if (res == 0)
218+
{
219+
bytesRemaining = -1;
220+
}
221+
222+
return res;
223+
}
224+
134225
public async Task Finish()
135226
{
136227
if (bytesRemaining != -1)

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -650,7 +650,7 @@ public async ValueTask<bool> FillBufferAsync(CancellationToken cancellationToken
650650

651651
if (bufferDataLength == buffer.Length)
652652
{
653-
ResizeBuffer(ref buffer, bufferDataLength * 2);
653+
resizeBuffer(ref buffer, bufferDataLength * 2);
654654
}
655655
}
656656
}
@@ -683,7 +683,7 @@ public async Task ReadAndIgnoreAllLinesAsync(CancellationToken cancellationToken
683683
/// </summary>
684684
/// <param name="buffer"></param>
685685
/// <param name="size"></param>
686-
private static void ResizeBuffer(ref byte[] buffer, long size)
686+
private static void resizeBuffer(ref byte[] buffer, long size)
687687
{
688688
var newBuffer = new byte[size];
689689
Buffer.BlockCopy(buffer, 0, newBuffer, 0, buffer.Length);
@@ -889,7 +889,7 @@ public async Task CopyBodyAsync(RequestResponseBase requestResponse, bool useOri
889889
string? contentEncoding = useOriginalHeaderValues ? requestResponse.OriginalContentEncoding : requestResponse.ContentEncoding;
890890

891891
Stream s = limitedStream = new LimitedStream(this, bufferPool, isChunked, contentLength);
892-
892+
893893
if (transformation == TransformationMode.Uncompress && contentEncoding != null)
894894
{
895895
s = decompressStream = DecompressionFactory.Create(CompressionUtil.CompressionNameToEnum(contentEncoding), s);

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

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -100,12 +100,10 @@ private static uint toNetworkByteOrder(uint port)
100100
/// <param name="onDataSend"></param>
101101
/// <param name="onDataReceive"></param>
102102
/// <param name="cancellationTokenSource"></param>
103-
/// <param name="exceptionFunc"></param>
104103
/// <returns></returns>
105104
private static async Task sendRawTap(Stream clientStream, Stream serverStream, IBufferPool bufferPool,
106105
Action<byte[], int, int>? onDataSend, Action<byte[], int, int>? onDataReceive,
107-
CancellationTokenSource cancellationTokenSource,
108-
ExceptionHandler exceptionFunc)
106+
CancellationTokenSource cancellationTokenSource)
109107
{
110108
// Now async relay all server=>client & client=>server data
111109
var sendRelay =
@@ -139,8 +137,7 @@ internal static Task SendRaw(Stream clientStream, Stream serverStream, IBufferPo
139137
{
140138
// todo: fix APM mode
141139
return sendRawTap(clientStream, serverStream, bufferPool, onDataSend, onDataReceive,
142-
cancellationTokenSource,
143-
exceptionFunc);
140+
cancellationTokenSource);
144141
}
145142
}
146143
}

src/Titanium.Web.Proxy/Http/HeaderParser.cs

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,5 @@ internal static async ValueTask ReadHeaders(ILineStream reader, HeaderCollection
2424
headerCollection.AddHeader(headerName, headerValue);
2525
}
2626
}
27-
28-
/// <summary>
29-
/// Increase size of buffer and copy existing content to new buffer
30-
/// </summary>
31-
/// <param name="buffer"></param>
32-
/// <param name="size"></param>
33-
private static void resizeBuffer(ref byte[] buffer, long size)
34-
{
35-
var newBuffer = new byte[size];
36-
Buffer.BlockCopy(buffer, 0, newBuffer, 0, buffer.Length);
37-
buffer = newBuffer;
38-
}
3927
}
4028
}

src/Titanium.Web.Proxy/Network/Certificate/BCCertificateMaker.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System;
22
using System.IO;
33
using System.Security.Cryptography.X509Certificates;
4-
using System.Threading;
54
using Org.BouncyCastle.Asn1;
65
using Org.BouncyCastle.Asn1.Pkcs;
76
using Org.BouncyCastle.Asn1.X509;
@@ -219,11 +218,9 @@ private X509Certificate2 makeCertificateInternal(string hostName, string subject
219218
/// <param name="subject">The s subject cn.</param>
220219
/// <param name="switchToMtaIfNeeded">if set to <c>true</c> [switch to MTA if needed].</param>
221220
/// <param name="signingCert">The signing cert.</param>
222-
/// <param name="cancellationToken">Task cancellation token</param>
223221
/// <returns>X509Certificate2.</returns>
224222
private X509Certificate2 makeCertificateInternal(string subject,
225-
bool switchToMtaIfNeeded, X509Certificate2? signingCert = null,
226-
CancellationToken cancellationToken = default)
223+
bool switchToMtaIfNeeded, X509Certificate2? signingCert = null)
227224
{
228225
return makeCertificateInternal(subject, $"CN={subject}",
229226
DateTime.UtcNow.AddDays(-certificateGraceDays), DateTime.UtcNow.AddDays(certificateValidDays),

src/Titanium.Web.Proxy/RequestHandler.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -291,13 +291,13 @@ private async Task<RetryResult> handleHttpSessionRequest(SessionEventArgs args,
291291
}
292292

293293
// construct the web request that we are going to issue on behalf of the client.
294-
await handleHttpSessionRequest(connection, args);
294+
await handleHttpSessionRequest(args);
295295
return true;
296296

297297
}, generator, serverConnection);
298298
}
299299

300-
private async Task handleHttpSessionRequest(TcpServerConnection connection, SessionEventArgs args)
300+
private async Task handleHttpSessionRequest(SessionEventArgs args)
301301
{
302302
var cancellationToken = args.CancellationTokenSource.Token;
303303
var request = args.HttpClient.Request;

src/Titanium.Web.Proxy/StreamExtended/SslTools.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ internal class SslTools
154154

155155
if(extensionsStartPosition < recordLength + 5)
156156
{
157-
extensions = await ReadExtensions(majorVersion, minorVersion, peekStream, bufferPool, cancellationToken);
157+
extensions = await ReadExtensions(majorVersion, minorVersion, peekStream, cancellationToken);
158158
}
159159

160160
var clientHelloInfo = new ClientHelloInfo(3, majorVersion, minorVersion, random, sessionId, ciphers, peekStream.Position)
@@ -292,7 +292,7 @@ public static async Task<bool> IsServerHello(IPeekStream stream, IBufferPool buf
292292

293293
if (extensionsStartPosition < recordLength + 5)
294294
{
295-
extensions = await ReadExtensions(majorVersion, minorVersion, peekStream, bufferPool, cancellationToken);
295+
extensions = await ReadExtensions(majorVersion, minorVersion, peekStream, cancellationToken);
296296
}
297297

298298
var serverHelloInfo = new ServerHelloInfo(3, majorVersion, minorVersion, random, sessionId, cipherSuite, peekStream.Position)
@@ -308,7 +308,7 @@ public static async Task<bool> IsServerHello(IPeekStream stream, IBufferPool buf
308308
return null;
309309
}
310310

311-
private static async Task<Dictionary<string, SslExtension>?> ReadExtensions(int majorVersion, int minorVersion, PeekStreamReader peekStreamReader, IBufferPool bufferPool, CancellationToken cancellationToken)
311+
private static async Task<Dictionary<string, SslExtension>?> ReadExtensions(int majorVersion, int minorVersion, PeekStreamReader peekStreamReader, CancellationToken cancellationToken)
312312
{
313313
Dictionary<string, SslExtension>? extensions = null;
314314
if (majorVersion > 3 || majorVersion == 3 && minorVersion >= 1)

src/Titanium.Web.Proxy/TransparentClientHandler.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,14 +75,15 @@ private async Task handleClient(TransparentProxyEndPoint endPoint, TcpClientConn
7575

7676
// HTTPS server created - we can now decrypt the client's traffic
7777
clientStream = new HttpClientStream(sslStream, BufferPool);
78+
sslStream = null; // clientStream was created, no need to keep SSL stream reference
7879
}
7980
catch (Exception e)
8081
{
81-
var certname = certificate?.GetNameInfo(X509NameType.SimpleName, false);
82+
var certName = certificate?.GetNameInfo(X509NameType.SimpleName, false);
8283
var session = new SessionEventArgs(this, endPoint, clientConnection, clientStream, null,
8384
cancellationTokenSource);
8485
throw new ProxyConnectException(
85-
$"Couldn't authenticate host '{httpsHostName}' with certificate '{certname}'.", e, session);
86+
$"Couldn't authenticate host '{httpsHostName}' with certificate '{certName}'.", e, session);
8687
}
8788

8889
}

0 commit comments

Comments
 (0)