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

Commit 51e83ba

Browse files
authored
Merge pull request #683 from justcoding121/master
beta
2 parents 35a4890 + abf159f commit 51e83ba

File tree

11 files changed

+65
-41
lines changed

11 files changed

+65
-41
lines changed

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

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,10 @@
44
using System.Net;
55
using System.Threading;
66
using System.Threading.Tasks;
7-
using Titanium.Web.Proxy.Compression;
87
using Titanium.Web.Proxy.Helpers;
98
using Titanium.Web.Proxy.Http;
109
using Titanium.Web.Proxy.Http.Responses;
1110
using Titanium.Web.Proxy.Models;
12-
using Titanium.Web.Proxy.Network;
1311
using Titanium.Web.Proxy.Network.Tcp;
1412
using Titanium.Web.Proxy.StreamExtended.Network;
1513

src/Titanium.Web.Proxy/ExplicitClientHandler.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,18 +52,16 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect
5252
if (await HttpHelper.IsConnectMethod(clientStream, BufferPool, cancellationToken) == 1)
5353
{
5454
// read the first line HTTP command
55-
string? httpCmd = await clientStream.ReadLineAsync(cancellationToken);
56-
if (string.IsNullOrEmpty(httpCmd))
55+
var requestLine = await clientStream.ReadRequestLine(cancellationToken);
56+
if (requestLine.IsEmpty())
5757
{
5858
return;
5959
}
6060

61-
Request.ParseRequestLine(httpCmd!, out string _, out var httpUrl, out var version);
62-
63-
var connectRequest = new ConnectRequest(httpUrl.GetString())
61+
var connectRequest = new ConnectRequest(requestLine.RequestUri.GetString())
6462
{
65-
RequestUriString8 = httpUrl,
66-
HttpVersion = version
63+
RequestUriString8 = requestLine.RequestUri,
64+
HttpVersion = requestLine.Version
6765
};
6866

6967
await HeaderParser.ReadHeaders(clientStream, connectRequest.Headers, cancellationToken);
@@ -105,7 +103,7 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect
105103
}
106104

107105
// write back successful CONNECT response
108-
var response = ConnectResponse.CreateSuccessfulConnectResponse(version);
106+
var response = ConnectResponse.CreateSuccessfulConnectResponse(requestLine.Version);
109107

110108
// Set ContentLength explicitly to properly handle HTTP 1.0
111109
response.ContentLength = 0;
@@ -175,7 +173,7 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect
175173
}
176174
}
177175

178-
string connectHostname = httpUrl.GetString();
176+
string connectHostname = requestLine.RequestUri.GetString();
179177
int idx = connectHostname.IndexOf(":");
180178
if (idx >= 0)
181179
{
@@ -214,6 +212,8 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect
214212

215213
// HTTPS server created - we can now decrypt the client's traffic
216214
clientStream = new HttpClientStream(sslStream, BufferPool);
215+
sslStream = null; // clientStream was created, no need to keep SSL stream reference
216+
217217
clientStream.DataRead += (o, args) => connectArgs.OnDecryptedDataSent(args.Buffer, args.Offset, args.Count);
218218
clientStream.DataWrite += (o, args) => connectArgs.OnDecryptedDataReceived(args.Buffer, args.Offset, args.Count);
219219
}

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,19 @@ internal async ValueTask WriteResponseAsync(Response response, CancellationToken
2929

3030
await WriteAsync(response, headerBuilder, cancellationToken);
3131
}
32+
33+
internal async ValueTask<RequestStatusInfo> ReadRequestLine(CancellationToken cancellationToken = default)
34+
{
35+
// read the first line HTTP command
36+
string? httpCmd = await ReadLineAsync(cancellationToken);
37+
if (string.IsNullOrEmpty(httpCmd))
38+
{
39+
return default;
40+
}
41+
42+
Request.ParseRequestLine(httpCmd!, out string method, out var requestUri, out var version);
43+
44+
return new RequestStatusInfo { Method = method, RequestUri = requestUri, Version = version };
45+
}
3246
}
3347
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using System;
2+
using Titanium.Web.Proxy.Models;
3+
4+
namespace Titanium.Web.Proxy.Helpers
5+
{
6+
struct RequestStatusInfo
7+
{
8+
public string Method { get; set; }
9+
10+
public ByteString RequestUri { get; set; }
11+
12+
public Version Version { get; set; }
13+
14+
public bool IsEmpty()
15+
{
16+
return Method == null && RequestUri.Length == 0 && Version == null;
17+
}
18+
}
19+
}

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/Request.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ internal override void EnsureBodyAvailable(bool throwWhenNotReadYet = true)
254254
}
255255
}
256256

257-
internal static void ParseRequestLine(string httpCmd, out string httpMethod, out ByteString httpUrl,
257+
internal static void ParseRequestLine(string httpCmd, out string method, out ByteString requestUri,
258258
out Version version)
259259
{
260260
int firstSpace = httpCmd.IndexOf(' ');
@@ -269,21 +269,21 @@ internal static void ParseRequestLine(string httpCmd, out string httpMethod, out
269269
// break up the line into three components (method, remote URL & Http Version)
270270

271271
// Find the request Verb
272-
httpMethod = httpCmd.Substring(0, firstSpace);
273-
if (!isAllUpper(httpMethod))
272+
method = httpCmd.Substring(0, firstSpace);
273+
if (!isAllUpper(method))
274274
{
275-
httpMethod = httpMethod.ToUpper();
275+
method = method.ToUpper();
276276
}
277277

278278
version = HttpHeader.Version11;
279279

280280
if (firstSpace == lastSpace)
281281
{
282-
httpUrl = (ByteString)httpCmd.AsSpan(firstSpace + 1).ToString();
282+
requestUri = (ByteString)httpCmd.AsSpan(firstSpace + 1).ToString();
283283
}
284284
else
285285
{
286-
httpUrl = (ByteString)httpCmd.AsSpan(firstSpace + 1, lastSpace - firstSpace - 1).ToString();
286+
requestUri = (ByteString)httpCmd.AsSpan(firstSpace + 1, lastSpace - firstSpace - 1).ToString();
287287

288288
// parse the HTTP version
289289
var httpVersion = httpCmd.AsSpan(lastSpace + 1);

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ internal set
196196
/// Use the encoding specified to decode the byte[] data to string
197197
/// </summary>
198198
[Browsable(false)]
199-
public string BodyString => bodyString ?? (bodyString = Encoding.GetString(Body));
199+
public string BodyString => bodyString ??= Encoding.GetString(Body);
200200

201201
/// <summary>
202202
/// Was the body read by user?

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: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ private async Task handleHttpSessionRequest(ProxyEndPoint endPoint, TcpClientCon
5858
}
5959

6060
// read the request line
61-
string? httpCmd = await clientStream.ReadLineAsync(cancellationToken);
62-
if (string.IsNullOrEmpty(httpCmd))
61+
var requestLine = await clientStream.ReadRequestLine(cancellationToken);
62+
if (requestLine.IsEmpty())
6363
{
6464
return;
6565
}
@@ -73,8 +73,6 @@ private async Task handleHttpSessionRequest(ProxyEndPoint endPoint, TcpClientCon
7373
{
7474
try
7575
{
76-
Request.ParseRequestLine(httpCmd!, out string httpMethod, out ByteString httpUrl, out var version);
77-
7876
// Read the request headers in to unique and non-unique header collections
7977
await HeaderParser.ReadHeaders(clientStream, args.HttpClient.Request.Headers,
8078
cancellationToken);
@@ -86,10 +84,10 @@ await HeaderParser.ReadHeaders(clientStream, args.HttpClient.Request.Headers,
8684
request.Authority = connectRequest.Authority;
8785
}
8886

89-
request.RequestUriString8 = httpUrl;
87+
request.RequestUriString8 = requestLine.RequestUri;
9088

91-
request.Method = httpMethod;
92-
request.HttpVersion = version;
89+
request.Method = requestLine.Method;
90+
request.HttpVersion = requestLine.Version;
9391

9492
if (!args.IsTransparent)
9593
{
@@ -293,13 +291,13 @@ private async Task<RetryResult> handleHttpSessionRequest(SessionEventArgs args,
293291
}
294292

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

299297
}, generator, serverConnection);
300298
}
301299

302-
private async Task handleHttpSessionRequest(TcpServerConnection connection, SessionEventArgs args)
300+
private async Task handleHttpSessionRequest(SessionEventArgs args)
303301
{
304302
var cancellationToken = args.CancellationTokenSource.Token;
305303
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)