Commit ae0844b2 authored by justcoding121's avatar justcoding121

resharper code cleanup

parent 6f166dbb
......@@ -16,7 +16,8 @@ namespace Titanium.Web.Proxy.EventArguments
}
/// <summary>
/// The server name indication hostname if available. Otherwise the generic certificate hostname of TransparentEndPoint.
/// The server name indication hostname if available. Otherwise the generic certificate hostname of
/// TransparentEndPoint.
/// </summary>
public string SniHostName { get; internal set; }
......
......@@ -21,10 +21,10 @@ namespace Titanium.Web.Proxy.EventArguments
/// </summary>
protected readonly int BufferSize;
protected readonly ExceptionHandler ExceptionFunc;
internal readonly CancellationTokenSource CancellationTokenSource;
protected readonly ExceptionHandler ExceptionFunc;
/// <summary>
/// Constructor to initialize the proxy
/// </summary>
......
......@@ -35,7 +35,8 @@ namespace Titanium.Web.Proxy.EventArguments
/// </summary>
public bool IsHttpsConnect
{
get => isHttpsConnect ?? throw new Exception("The value of this property is known in the BeforeTunnectConnectResponse event");
get => isHttpsConnect ??
throw new Exception("The value of this property is known in the BeforeTunnectConnectResponse event");
internal set => isHttpsConnect = value;
}
}
......
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
......@@ -90,7 +89,8 @@ namespace Titanium.Web.Proxy
}
//send the response
await clientStreamWriter.WriteResponseAsync(connectArgs.WebSession.Response, cancellationToken: cancellationToken);
await clientStreamWriter.WriteResponseAsync(connectArgs.WebSession.Response,
cancellationToken: cancellationToken);
return;
}
......@@ -99,7 +99,8 @@ namespace Titanium.Web.Proxy
await endPoint.InvokeBeforeTunnectConnectResponse(this, connectArgs, ExceptionFunc);
//send the response
await clientStreamWriter.WriteResponseAsync(connectArgs.WebSession.Response, cancellationToken: cancellationToken);
await clientStreamWriter.WriteResponseAsync(connectArgs.WebSession.Response,
cancellationToken: cancellationToken);
return;
}
......@@ -212,7 +213,8 @@ namespace Titanium.Web.Proxy
{
// clientStream.Available sbould be at most BufferSize because it is using the same buffer size
await clientStream.ReadAsync(data, 0, available, cancellationToken);
await connection.StreamWriter.WriteAsync(data, 0, available, true, cancellationToken);
await connection.StreamWriter.WriteAsync(data, 0, available, true,
cancellationToken);
}
finally
{
......@@ -220,7 +222,8 @@ namespace Titanium.Web.Proxy
}
}
var serverHelloInfo = await SslTools.PeekServerHello(connection.Stream, cancellationToken);
var serverHelloInfo =
await SslTools.PeekServerHello(connection.Stream, cancellationToken);
((ConnectResponse)connectArgs.WebSession.Response).ServerHelloInfo = serverHelloInfo;
}
......@@ -242,13 +245,22 @@ namespace Titanium.Web.Proxy
{
// HTTP/2 Connection Preface
string line = await clientStreamReader.ReadLineAsync(cancellationToken);
if (line != string.Empty) throw new Exception($"HTTP/2 Protocol violation. Empty string expected, '{line}' received");
if (line != string.Empty)
{
throw new Exception($"HTTP/2 Protocol violation. Empty string expected, '{line}' received");
}
line = await clientStreamReader.ReadLineAsync(cancellationToken);
if (line != "SM") throw new Exception($"HTTP/2 Protocol violation. 'SM' expected, '{line}' received");
if (line != "SM")
{
throw new Exception($"HTTP/2 Protocol violation. 'SM' expected, '{line}' received");
}
line = await clientStreamReader.ReadLineAsync(cancellationToken);
if (line != string.Empty) throw new Exception($"HTTP/2 Protocol violation. Empty string expected, '{line}' received");
if (line != string.Empty)
{
throw new Exception($"HTTP/2 Protocol violation. Empty string expected, '{line}' received");
}
//create new connection
using (var connection = await GetServerConnection(connectArgs, true, cancellationToken))
......@@ -268,7 +280,8 @@ namespace Titanium.Web.Proxy
//Now create the request
await HandleHttpSessionRequest(endPoint, tcpClient, clientStream, clientStreamReader,
clientStreamWriter, cancellationTokenSource, connectHostname, connectArgs?.WebSession.ConnectRequest);
clientStreamWriter, cancellationTokenSource, connectHostname,
connectArgs?.WebSession.ConnectRequest);
}
catch (ProxyHttpException e)
{
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Generic;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using StreamExtended;
......@@ -13,7 +10,8 @@ namespace Titanium.Web.Proxy.Extensions
{
internal static class SslExtensions
{
internal static readonly List<SslApplicationProtocol> Http11ProtocolAsList = new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 };
internal static readonly List<SslApplicationProtocol> Http11ProtocolAsList =
new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 };
internal static string GetServerName(this ClientHelloInfo clientHelloInfo)
{
......@@ -60,14 +58,18 @@ namespace Titanium.Web.Proxy.Extensions
return Http11ProtocolAsList;
}
internal static Task AuthenticateAsClientAsync(this SslStream sslStream, SslClientAuthenticationOptions option, CancellationToken token)
internal static Task AuthenticateAsClientAsync(this SslStream sslStream, SslClientAuthenticationOptions option,
CancellationToken token)
{
return sslStream.AuthenticateAsClientAsync(option.TargetHost, option.ClientCertificates, option.EnabledSslProtocols, option.CertificateRevocationCheckMode != X509RevocationMode.NoCheck);
return sslStream.AuthenticateAsClientAsync(option.TargetHost, option.ClientCertificates,
option.EnabledSslProtocols, option.CertificateRevocationCheckMode != X509RevocationMode.NoCheck);
}
internal static Task AuthenticateAsServerAsync(this SslStream sslStream, SslServerAuthenticationOptions options, CancellationToken token)
internal static Task AuthenticateAsServerAsync(this SslStream sslStream, SslServerAuthenticationOptions options,
CancellationToken token)
{
return sslStream.AuthenticateAsServerAsync(options.ServerCertificate, options.ClientCertificateRequired, options.EnabledSslProtocols, options.CertificateRevocationCheckMode != X509RevocationMode.NoCheck);
return sslStream.AuthenticateAsServerAsync(options.ServerCertificate, options.ClientCertificateRequired,
options.EnabledSslProtocols, options.CertificateRevocationCheckMode != X509RevocationMode.NoCheck);
}
#endif
}
......@@ -75,7 +77,8 @@ namespace Titanium.Web.Proxy.Extensions
#if !NETCOREAPP2_1
internal enum SslApplicationProtocol
{
Http11, Http2
Http11,
Http2
}
internal class SslClientAuthenticationOptions
......
......@@ -35,7 +35,8 @@ namespace Titanium.Web.Proxy.Helpers
/// <param name="description">The HTTP status description.</param>
/// <param name="cancellationToken">Optional cancellation token for this async task.</param>
/// <returns>The Task.</returns>
internal Task WriteResponseStatusAsync(Version version, int code, string description, CancellationToken cancellationToken)
internal Task WriteResponseStatusAsync(Version version, int code, string description,
CancellationToken cancellationToken)
{
return WriteLineAsync(Response.CreateResponseLine(version, code, description), cancellationToken);
}
......
......@@ -98,7 +98,8 @@ namespace Titanium.Web.Proxy.Helpers
/// <param name="flush"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
internal async Task WriteHeadersAsync(HeaderCollection headers, bool flush = true, CancellationToken cancellationToken = default)
internal async Task WriteHeadersAsync(HeaderCollection headers, bool flush = true,
CancellationToken cancellationToken = default)
{
foreach (var header in headers)
{
......@@ -121,7 +122,8 @@ namespace Titanium.Web.Proxy.Helpers
}
}
internal async Task WriteAsync(byte[] data, int offset, int count, bool flush, CancellationToken cancellationToken = default)
internal async Task WriteAsync(byte[] data, int offset, int count, bool flush,
CancellationToken cancellationToken = default)
{
await WriteAsync(data, offset, count, cancellationToken);
if (flush)
......@@ -202,7 +204,8 @@ namespace Titanium.Web.Proxy.Helpers
/// <param name="onCopy"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task CopyBodyChunkedAsync(CustomBinaryReader reader, Action<byte[], int, int> onCopy, CancellationToken cancellationToken)
private async Task CopyBodyChunkedAsync(CustomBinaryReader reader, Action<byte[], int, int> onCopy,
CancellationToken cancellationToken)
{
while (true)
{
......@@ -242,7 +245,8 @@ namespace Titanium.Web.Proxy.Helpers
/// <param name="onCopy"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task CopyBytesFromStream(CustomBinaryReader reader, long count, Action<byte[], int, int> onCopy, CancellationToken cancellationToken)
private async Task CopyBytesFromStream(CustomBinaryReader reader, long count, Action<byte[], int, int> onCopy,
CancellationToken cancellationToken)
{
var buffer = reader.Buffer;
long remainingBytes = count;
......@@ -276,7 +280,8 @@ namespace Titanium.Web.Proxy.Helpers
/// <param name="flush"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
protected async Task WriteAsync(RequestResponseBase requestResponse, bool flush = true, CancellationToken cancellationToken = default)
protected async Task WriteAsync(RequestResponseBase requestResponse, bool flush = true,
CancellationToken cancellationToken = default)
{
var body = requestResponse.CompressBodyAndUpdateContentLength();
await WriteHeadersAsync(requestResponse.Headers, flush, cancellationToken);
......
......@@ -44,7 +44,7 @@ namespace Titanium.Web.Proxy.Helpers
}
/// <summary>
/// <see href="https://msdn.microsoft.com/en-us/library/aa366896.aspx"/>
/// <see href="https://msdn.microsoft.com/en-us/library/aa366896.aspx" />
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct Tcp6Row
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Titanium.Web.Proxy.Helpers
namespace Titanium.Web.Proxy.Helpers
{
internal class Ref<T>
{
......@@ -21,7 +15,7 @@ namespace Titanium.Web.Proxy.Helpers
public override string ToString()
{
T value = Value;
var value = Value;
return value == null ? string.Empty : value.ToString();
}
......
using System;
using System.Runtime.InteropServices;
namespace Titanium.Web.Proxy.Helpers
{
......@@ -19,7 +18,8 @@ namespace Titanium.Web.Proxy.Helpers
/// cache for Windows platform check
/// </summary>
/// <returns></returns>
private static readonly Lazy<bool> isRunningOnWindows = new Lazy<bool>(() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
private static readonly Lazy<bool> isRunningOnWindows =
new Lazy<bool>(() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
#endif
......
......@@ -41,7 +41,7 @@ namespace Titanium.Web.Proxy.Helpers
if (ipVersion == IpVersion.Ipv4)
{
NativeMethods.TcpRow* rowPtr = (NativeMethods.TcpRow*)(tcpTable + 4);
var rowPtr = (NativeMethods.TcpRow*)(tcpTable + 4);
for (int i = 0; i < rowCount; ++i)
{
......@@ -55,7 +55,7 @@ namespace Titanium.Web.Proxy.Helpers
}
else
{
NativeMethods.Tcp6Row* rowPtr = (NativeMethods.Tcp6Row*)(tcpTable + 4);
var rowPtr = (NativeMethods.Tcp6Row*)(tcpTable + 4);
for (int i = 0; i < rowCount; ++i)
{
......@@ -276,9 +276,11 @@ namespace Titanium.Web.Proxy.Helpers
//Now async relay all server=>client & client=>server data
var sendRelay =
CopyHttp2FrameAsync(clientStream, serverStream, onDataSend, bufferSize, connectionId, cancellationTokenSource.Token);
CopyHttp2FrameAsync(clientStream, serverStream, onDataSend, bufferSize, connectionId,
cancellationTokenSource.Token);
var receiveRelay =
CopyHttp2FrameAsync(serverStream, clientStream, onDataReceive, bufferSize, connectionId, cancellationTokenSource.Token);
CopyHttp2FrameAsync(serverStream, clientStream, onDataReceive, bufferSize, connectionId,
cancellationTokenSource.Token);
await Task.WhenAny(sendRelay, receiveRelay);
cancellationTokenSource.Cancel();
......@@ -302,7 +304,8 @@ namespace Titanium.Web.Proxy.Helpers
int length = (headerBuffer[0] << 16) + (headerBuffer[1] << 8) + headerBuffer[2];
byte type = headerBuffer[3];
byte flags = headerBuffer[4];
int streamId = ((headerBuffer[5] & 0x7f) << 24) + (headerBuffer[6] << 16) + (headerBuffer[7] << 8) + headerBuffer[8];
int streamId = ((headerBuffer[5] & 0x7f) << 24) + (headerBuffer[6] << 16) + (headerBuffer[7] << 8) +
headerBuffer[8];
read = await ForceRead(input, buffer, 0, length, cancellationToken);
if (read != length)
......@@ -321,7 +324,8 @@ namespace Titanium.Web.Proxy.Helpers
}
}
private static async Task<int> ForceRead(Stream input, byte[] buffer, int offset, int bytesToRead, CancellationToken cancellationToken)
private static async Task<int> ForceRead(Stream input, byte[] buffer, int offset, int bytesToRead,
CancellationToken cancellationToken)
{
int totalRead = 0;
while (bytesToRead > 0)
......
......@@ -8,7 +8,8 @@ namespace Titanium.Web.Proxy.Http
{
internal static class HeaderParser
{
internal static async Task ReadHeaders(CustomBinaryReader reader, HeaderCollection headerCollection, CancellationToken cancellationToken)
internal static async Task ReadHeaders(CustomBinaryReader reader, HeaderCollection headerCollection,
CancellationToken cancellationToken)
{
string tmpLine;
while (!string.IsNullOrEmpty(tmpLine = await reader.ReadLineAsync(cancellationToken)))
......
......@@ -80,7 +80,8 @@ namespace Titanium.Web.Proxy.Http
/// Prepare and send the http(s) request
/// </summary>
/// <returns></returns>
internal async Task SendRequest(bool enable100ContinueBehaviour, bool isTransparent, CancellationToken cancellationToken)
internal async Task SendRequest(bool enable100ContinueBehaviour, bool isTransparent,
CancellationToken cancellationToken)
{
var upstreamProxy = ServerConnection.UpStreamProxy;
......
......@@ -60,13 +60,18 @@ namespace Titanium.Web.Proxy.Network
/// <summary>
///
/// </summary>
/// <param name="rootCertificateName"></param>
/// <param name="rootCertificateIssuerName"></param>
/// <param name="userTrustRootCertificate">Should fake HTTPS certificate be trusted by this machine's user certificate store?</param>
/// <param name="userTrustRootCertificate">
/// Should fake HTTPS certificate be trusted by this machine's user certificate
/// store?
/// </param>
/// <param name="machineTrustRootCertificate">Should fake HTTPS certificate be trusted by this machine's certificate store?</param>
/// <param name="trustRootCertificateAsAdmin">Should we attempt to trust certificates with elevated permissions by prompting for UAC if required?</param>
/// <param name="trustRootCertificateAsAdmin">
/// Should we attempt to trust certificates with elevated permissions by
/// prompting for UAC if required?
/// </param>
/// <param name="exceptionFunc"></param>
internal CertificateManager(string rootCertificateName, string rootCertificateIssuerName,
bool userTrustRootCertificate, bool machineTrustRootCertificate, bool trustRootCertificateAsAdmin,
......@@ -639,7 +644,10 @@ namespace Titanium.Web.Proxy.Network
/// named as "rootCert.pfx" (and will be saved in proxy dll directory).
/// </param>
/// <param name="password">Set a password for the .pfx file.</param>
/// <param name="overwritePfXFile">true : replace an existing .pfx file if password is incorect or if RootCertificate==null.</param>
/// <param name="overwritePfXFile">
/// true : replace an existing .pfx file if password is incorect or if
/// RootCertificate==null.
/// </param>
/// <param name="storageFlag"></param>
/// <returns>
/// true if succeeded, else false.
......@@ -765,9 +773,15 @@ namespace Titanium.Web.Proxy.Network
/// Also makes root certificate trusted based on provided parameters.
/// Note:setting machineTrustRootCertificate to true will force userTrustRootCertificate to true.
/// </summary>
/// <param name="userTrustRootCertificate">Should fake HTTPS certificate be trusted by this machine's user certificate store?</param>
/// <param name="userTrustRootCertificate">
/// Should fake HTTPS certificate be trusted by this machine's user certificate
/// store?
/// </param>
/// <param name="machineTrustRootCertificate">Should fake HTTPS certificate be trusted by this machine's certificate store?</param>
/// <param name="trustRootCertificateAsAdmin">Should we attempt to trust certificates with elevated permissions by prompting for UAC if required?</param>
/// <param name="trustRootCertificateAsAdmin">
/// Should we attempt to trust certificates with elevated permissions by
/// prompting for UAC if required?
/// </param>
public void EnsureRootCertificate(bool userTrustRootCertificate,
bool machineTrustRootCertificate, bool trustRootCertificateAsAdmin = false)
{
......
......@@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using StreamExtended.Network;
......@@ -35,7 +34,8 @@ namespace Titanium.Web.Proxy.Network.Tcp
/// <returns></returns>
internal async Task<TcpConnection> CreateClient(string remoteHostName, int remotePort,
List<SslApplicationProtocol> applicationProtocols, Version httpVersion, bool decryptSsl, bool isConnect,
ProxyServer proxyServer, IPEndPoint upStreamEndPoint, ExternalProxy externalProxy, CancellationToken cancellationToken)
ProxyServer proxyServer, IPEndPoint upStreamEndPoint, ExternalProxy externalProxy,
CancellationToken cancellationToken)
{
bool useUpstreamProxy = false;
......@@ -79,7 +79,7 @@ namespace Titanium.Web.Proxy.Network.Tcp
var connectRequest = new ConnectRequest
{
OriginalUrl = $"{remoteHostName}:{remotePort}",
HttpVersion = httpVersion,
HttpVersion = httpVersion
};
connectRequest.Headers.AddHeader(KnownHeaders.Connection, KnownHeaders.ConnectionKeepAlive);
......@@ -87,7 +87,8 @@ namespace Titanium.Web.Proxy.Network.Tcp
if (!string.IsNullOrEmpty(externalProxy.UserName) && externalProxy.Password != null)
{
connectRequest.Headers.AddHeader(HttpHeader.ProxyConnectionKeepAlive);
connectRequest.Headers.AddHeader(HttpHeader.GetProxyAuthorizationHeader(externalProxy.UserName, externalProxy.Password));
connectRequest.Headers.AddHeader(
HttpHeader.GetProxyAuthorizationHeader(externalProxy.UserName, externalProxy.Password));
}
await writer.WriteRequestAsync(connectRequest, cancellationToken: cancellationToken);
......
......@@ -28,6 +28,7 @@ namespace Titanium.Web.Proxy
/// HTTP & HTTPS scheme shorthands.
/// </summary>
internal static readonly string UriSchemeHttp = Uri.UriSchemeHttp;
internal static readonly string UriSchemeHttps = Uri.UriSchemeHttps;
/// <summary>
......@@ -58,9 +59,15 @@ namespace Titanium.Web.Proxy
/// <summary>
/// Initializes a new instance of ProxyServer class with provided parameters.
/// </summary>
/// <param name="userTrustRootCertificate">Should fake HTTPS certificate be trusted by this machine's user certificate store?</param>
/// <param name="userTrustRootCertificate">
/// Should fake HTTPS certificate be trusted by this machine's user certificate
/// store?
/// </param>
/// <param name="machineTrustRootCertificate">Should fake HTTPS certificate be trusted by this machine's certificate store?</param>
/// <param name="trustRootCertificateAsAdmin">Should we attempt to trust certificates with elevated permissions by prompting for UAC if required?</param>
/// <param name="trustRootCertificateAsAdmin">
/// Should we attempt to trust certificates with elevated permissions by
/// prompting for UAC if required?
/// </param>
public ProxyServer(bool userTrustRootCertificate = true, bool machineTrustRootCertificate = false,
bool trustRootCertificateAsAdmin = false) : this(null, null, userTrustRootCertificate,
machineTrustRootCertificate, trustRootCertificateAsAdmin)
......@@ -72,9 +79,15 @@ namespace Titanium.Web.Proxy
/// </summary>
/// <param name="rootCertificateName">Name of the root certificate.</param>
/// <param name="rootCertificateIssuerName">Name of the root certificate issuer.</param>
/// <param name="userTrustRootCertificate">Should fake HTTPS certificate be trusted by this machine's user certificate store?</param>
/// <param name="userTrustRootCertificate">
/// Should fake HTTPS certificate be trusted by this machine's user certificate
/// store?
/// </param>
/// <param name="machineTrustRootCertificate">Should fake HTTPS certificate be trusted by this machine's certificate store?</param>
/// <param name="trustRootCertificateAsAdmin">Should we attempt to trust certificates with elevated permissions by prompting for UAC if required?</param>
/// <param name="trustRootCertificateAsAdmin">
/// Should we attempt to trust certificates with elevated permissions by
/// prompting for UAC if required?
/// </param>
public ProxyServer(string rootCertificateName, string rootCertificateIssuerName,
bool userTrustRootCertificate = true, bool machineTrustRootCertificate = false,
bool trustRootCertificateAsAdmin = false)
......
......@@ -290,7 +290,8 @@ namespace Titanium.Web.Proxy
if (request.ExpectContinue)
{
args.WebSession.SetConnection(connection);
await args.WebSession.SendRequest(Enable100ContinueBehaviour, args.IsTransparent, cancellationToken);
await args.WebSession.SendRequest(Enable100ContinueBehaviour, args.IsTransparent,
cancellationToken);
}
//If 100 continue was the response inform that to the client
......@@ -316,7 +317,8 @@ namespace Titanium.Web.Proxy
if (!request.ExpectContinue)
{
args.WebSession.SetConnection(connection);
await args.WebSession.SendRequest(Enable100ContinueBehaviour, args.IsTransparent, cancellationToken);
await args.WebSession.SendRequest(Enable100ContinueBehaviour, args.IsTransparent,
cancellationToken);
}
//check if content-length is > 0
......@@ -359,7 +361,8 @@ namespace Titanium.Web.Proxy
/// <param name="isConnect"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<TcpConnection> GetServerConnection(SessionEventArgsBase args, bool isConnect, CancellationToken cancellationToken)
private async Task<TcpConnection> GetServerConnection(SessionEventArgsBase args, bool isConnect,
CancellationToken cancellationToken)
{
ExternalProxy customUpStreamProxy = null;
......
......@@ -118,7 +118,8 @@ namespace Titanium.Web.Proxy
//Write body if exists
if (response.HasBody)
{
await args.CopyResponseBodyAsync(clientStreamWriter, TransformationMode.None, cancellationToken);
await args.CopyResponseBodyAsync(clientStreamWriter, TransformationMode.None,
cancellationToken);
}
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment