Commit 5f5ca4fc authored by Honfika's avatar Honfika

netstandard support based on adminnz's changes

parent 34cf380a
......@@ -69,7 +69,7 @@ namespace Titanium.Web.Proxy.EventArguments
/// <summary>
/// Does this session uses SSL
/// </summary>
public bool IsHttps => WebSession.Request.RequestUri.Scheme == Uri.UriSchemeHttps;
public bool IsHttps => WebSession.Request.RequestUri.Scheme == ProxyServer.UriSchemeHttps;
/// <summary>
/// Client End Point.
......
......@@ -10,7 +10,7 @@ namespace Titanium.Web.Proxy.EventArguments
{
public class TunnelConnectSessionEventArgs : SessionEventArgs
{
public bool IsHttps { get; set; }
public bool IsHttpsConnect { get; set; }
public TunnelConnectSessionEventArgs(ProxyEndPoint endPoint) : base(0, endPoint, null)
{
......
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Remoting;
using System.Threading;
using System.Threading.Tasks;
......@@ -14,7 +13,9 @@ namespace Titanium.Web.Proxy.Helpers
/// <seealso cref="System.IO.Stream" />
internal class CustomBufferedStream : Stream
{
#if NET45
private AsyncCallback readCallback;
#endif
private readonly Stream baseStream;
......@@ -35,7 +36,9 @@ namespace Titanium.Web.Proxy.Helpers
/// <param name="bufferSize">Size of the buffer.</param>
public CustomBufferedStream(Stream baseStream, int bufferSize)
{
#if NET45
readCallback = ReadCallback;
#endif
this.baseStream = baseStream;
streamBuffer = BufferPool.GetBuffer(bufferSize);
}
......@@ -111,6 +114,7 @@ namespace Titanium.Web.Proxy.Helpers
baseStream.Write(buffer, offset, count);
}
#if NET45
/// <summary>
/// Begins an asynchronous read operation. (Consider using <see cref="M:System.IO.Stream.ReadAsync(System.Byte[],System.Int32,System.Int32)" /> instead; see the Remarks section.)
/// </summary>
......@@ -163,6 +167,7 @@ namespace Titanium.Web.Proxy.Helpers
OnDataSent(buffer, offset, count);
return baseStream.BeginWrite(buffer, offset, count, callback, state);
}
#endif
/// <summary>
/// Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token.
......@@ -184,18 +189,7 @@ namespace Titanium.Web.Proxy.Helpers
await base.CopyToAsync(destination, bufferSize, cancellationToken);
}
/// <summary>
/// Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
/// </summary>
/// <param name="requestedType">The <see cref="T:System.Type" /> of the object that the new <see cref="T:System.Runtime.Remoting.ObjRef" /> will reference.</param>
/// <returns>
/// Information required to generate a proxy.
/// </returns>
public override ObjRef CreateObjRef(Type requestedType)
{
return baseStream.CreateObjRef(requestedType);
}
#if NET45
/// <summary>
/// Waits for the pending asynchronous read to complete. (Consider using <see cref="M:System.IO.Stream.ReadAsync(System.Byte[],System.Int32,System.Int32)" /> instead; see the Remarks section.)
/// </summary>
......@@ -222,6 +216,7 @@ namespace Titanium.Web.Proxy.Helpers
{
baseStream.EndWrite(asyncResult);
}
#endif
/// <summary>
/// Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.
......@@ -235,17 +230,6 @@ namespace Titanium.Web.Proxy.Helpers
return baseStream.FlushAsync(cancellationToken);
}
/// <summary>
/// Obtains a lifetime service object to control the lifetime policy for this instance.
/// </summary>
/// <returns>
/// An object of type <see cref="T:System.Runtime.Remoting.Lifetime.ILease" /> used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the <see cref="P:System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseManagerPollTime" /> property.
/// </returns>
public override object InitializeLifetimeService()
{
return baseStream.InitializeLifetimeService();
}
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream,
/// advances the position within the stream by the number of bytes read,
......@@ -380,7 +364,9 @@ namespace Titanium.Web.Proxy.Helpers
baseStream.Dispose();
BufferPool.ReturnBuffer(streamBuffer);
streamBuffer = null;
#if NET45
readCallback = null;
#endif
}
}
......
......@@ -25,7 +25,6 @@ namespace Titanium.Web.Proxy.Helpers
return FindProcessIdFromLocalPort(port, IpVersion.Ipv6);
}
#endif
/// <summary>
/// Adapated from below link
......@@ -76,5 +75,56 @@ namespace Titanium.Web.Proxy.Helpers
return isLocalhost;
}
#else
/// <summary>
/// Adapated from below link
/// http://stackoverflow.com/questions/11834091/how-to-check-if-localhost
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
internal static bool IsLocalIpAddress(IPAddress address)
{
// get local IP addresses
var localIPs = Dns.GetHostAddressesAsync(Dns.GetHostName()).Result;
// test if any host IP equals to any local IP or to localhost
return IPAddress.IsLoopback(address) || localIPs.Contains(address);
}
internal static bool IsLocalIpAddress(string hostName)
{
bool isLocalhost = false;
var localhost = Dns.GetHostEntryAsync("127.0.0.1").Result;
if (hostName == localhost.HostName)
{
var hostEntry = Dns.GetHostEntryAsync(hostName).Result;
isLocalhost = hostEntry.AddressList.Any(IPAddress.IsLoopback);
}
if (!isLocalhost)
{
localhost = Dns.GetHostEntryAsync(Dns.GetHostName()).Result;
IPAddress ipAddress;
if (IPAddress.TryParse(hostName, out ipAddress))
isLocalhost = localhost.AddressList.Any(x => x.Equals(ipAddress));
if (!isLocalhost)
{
try
{
var hostEntry = Dns.GetHostEntryAsync(hostName).Result;
isLocalhost = localhost.AddressList.Any(x => hostEntry.AddressList.Any(x.Equals));
}
catch (SocketException)
{
}
}
}
return isLocalhost;
}
#endif
}
}
......@@ -127,11 +127,11 @@ namespace Titanium.Web.Proxy.Helpers
}
ProxyProtocolType? protocolType = null;
if (protocolTypeStr.Equals("http", StringComparison.InvariantCultureIgnoreCase))
if (protocolTypeStr.Equals(Proxy.ProxyServer.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase))
{
protocolType = ProxyProtocolType.Http;
}
else if (protocolTypeStr.Equals("https", StringComparison.InvariantCultureIgnoreCase))
else if (protocolTypeStr.Equals(Proxy.ProxyServer.UriSchemeHttps, StringComparison.InvariantCultureIgnoreCase))
{
protocolType = ProxyProtocolType.Https;
}
......
......@@ -43,10 +43,10 @@ namespace Titanium.Web.Proxy.Helpers
switch (ProtocolType)
{
case ProxyProtocolType.Http:
protocol = "http";
protocol = ProxyServer.UriSchemeHttp;
break;
case ProxyProtocolType.Https:
protocol = "https";
protocol = Proxy.ProxyServer.UriSchemeHttps;
break;
default:
throw new Exception("Unsupported protocol type");
......
......@@ -48,7 +48,7 @@ namespace Titanium.Web.Proxy.Http
/// <summary>
/// Is Https?
/// </summary>
public bool IsHttps => Request.RequestUri.Scheme == Uri.UriSchemeHttps;
public bool IsHttps => Request.RequestUri.Scheme == ProxyServer.UriSchemeHttps;
internal HttpWebClient()
......
using System;
#if NET45
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Org.BouncyCastle.Asn1;
......@@ -189,3 +190,4 @@ namespace Titanium.Web.Proxy.Network.Certificate
}
}
}
#endif
\ No newline at end of file
......@@ -55,7 +55,11 @@ namespace Titanium.Web.Proxy.Network
if (certEngine == null)
{
#if NET45
certEngine = engine == CertificateEngine.BouncyCastle ? (ICertificateMaker)new BCCertificateMaker() : new WinCertificateMaker();
#else
certEngine = new BCCertificateMaker();
#endif
}
}
}
......@@ -135,7 +139,11 @@ namespace Titanium.Web.Proxy.Network
private string GetRootCertificatePath()
{
#if NET45
string assemblyLocation = Assembly.GetExecutingAssembly().Location;
#else
string assemblyLocation = string.Empty;
#endif
// dynamically loaded assemblies returns string.Empty location
if (assemblyLocation == string.Empty)
......@@ -375,8 +383,11 @@ namespace Titanium.Web.Proxy.Network
}
X509Certificate2 certificate = null;
// todo: lock in netstandard, too
#if NET45
lock (string.Intern(certificateName))
{
#endif
if (certificateCache.ContainsKey(certificateName) == false)
{
try
......@@ -409,7 +420,9 @@ namespace Titanium.Web.Proxy.Network
return cached.Certificate;
}
}
}
#if NET45
}
#endif
return certificate;
}
......@@ -477,8 +490,8 @@ namespace Titanium.Web.Proxy.Network
}
finally
{
x509RootStore.Close();
x509PersonalStore.Close();
x509RootStore.Dispose();
x509PersonalStore.Dispose();
}
}
......@@ -517,8 +530,8 @@ namespace Titanium.Web.Proxy.Network
}
finally
{
x509RootStore.Close();
x509PersonalStore.Close();
x509RootStore.Dispose();
x509PersonalStore.Dispose();
}
}
......
......@@ -55,7 +55,11 @@ namespace Titanium.Web.Proxy.Network.Tcp
//If this proxy uses another external proxy then create a tunnel request for HTTP/HTTPS connections
if (useProxy)
{
#if NET45
client = new TcpClient(server.UpStreamEndPoint);
#else
client = new TcpClient(server.UpStreamEndPoint.AddressFamily);
#endif
await client.ConnectAsync(externalProxy.HostName, externalProxy.Port);
stream = new CustomBufferedStream(client.GetStream(), server.BufferSize);
......@@ -93,7 +97,11 @@ namespace Titanium.Web.Proxy.Network.Tcp
}
else
{
#if NET45
client = new TcpClient(server.UpStreamEndPoint);
#else
client = new TcpClient(server.UpStreamEndPoint.AddressFamily);
#endif
await client.ConnectAsync(remoteHostName, remotePort);
stream = new CustomBufferedStream(client.GetStream(), server.BufferSize);
}
......
......@@ -16,7 +16,9 @@ using Titanium.Web.Proxy.Helpers.WinHttp;
using Titanium.Web.Proxy.Models;
using Titanium.Web.Proxy.Network;
using Titanium.Web.Proxy.Network.Tcp;
#if NET45
using Titanium.Web.Proxy.Network.WinAuth.Security;
#endif
namespace Titanium.Web.Proxy
{
......@@ -25,6 +27,14 @@ namespace Titanium.Web.Proxy
/// </summary>
public partial class ProxyServer : IDisposable
{
#if NET45
internal static readonly string UriSchemeHttp = Uri.UriSchemeHttp;
internal static readonly string UriSchemeHttps = Uri.UriSchemeHttps;
#else
internal const string UriSchemeHttp = "http";
internal const string UriSchemeHttps = "https";
#endif
/// <summary>
/// Is the proxy currently running
/// </summary>
......@@ -69,12 +79,12 @@ namespace Titanium.Web.Proxy
/// Manage system proxy settings
/// </summary>
private SystemProxyManager systemProxySettingsManager { get; }
#endif
/// <summary>
/// Set firefox to use default system proxy
/// </summary>
private readonly FireFoxProxySettingsManager firefoxProxySettingsManager = new FireFoxProxySettingsManager();
#endif
/// <summary>
/// Buffer size used throughout this proxy
......@@ -622,6 +632,7 @@ namespace Titanium.Web.Proxy
CertificateManager?.Dispose();
}
#if NET45
/// <summary>
/// Listen on the given end point on local machine
/// </summary>
......@@ -635,6 +646,23 @@ namespace Titanium.Web.Proxy
// accept clients asynchronously
endPoint.Listener.BeginAcceptTcpClient(OnAcceptConnection, endPoint);
}
#else
private async void Listen(ProxyEndPoint endPoint)
{
endPoint.Listener = new TcpListener(endPoint.IpAddress, endPoint.Port);
endPoint.Listener.Start();
endPoint.Port = ((IPEndPoint)endPoint.Listener.LocalEndpoint).Port;
while (true)
{
TcpClient tcpClient = await endPoint.Listener.AcceptTcpClientAsync();
if (tcpClient != null)
Task.Run(async () => HandleClient(tcpClient, endPoint));
}
}
#endif
/// <summary>
/// Verifiy if its safe to set this end point as System proxy
......@@ -681,6 +709,7 @@ namespace Titanium.Web.Proxy
}
}
#if NET45
/// <summary>
/// When a connection is received from client act
/// </summary>
......@@ -712,48 +741,54 @@ namespace Titanium.Web.Proxy
{
Task.Run(async () =>
{
Interlocked.Increment(ref clientConnectionCount);
tcpClient.ReceiveTimeout = ConnectionTimeOutSeconds * 1000;
tcpClient.SendTimeout = ConnectionTimeOutSeconds * 1000;
try
{
if (endPoint.GetType() == typeof(TransparentProxyEndPoint))
{
await HandleClient(endPoint as TransparentProxyEndPoint, tcpClient);
}
else
{
await HandleClient(endPoint as ExplicitProxyEndPoint, tcpClient);
}
}
finally
{
Interlocked.Decrement(ref clientConnectionCount);
try
{
if (tcpClient != null)
{
//This line is important!
//contributors please don't remove it without discussion
//It helps to avoid eventual deterioration of performance due to TCP port exhaustion
//due to default TCP CLOSE_WAIT timeout for 4 minutes
tcpClient.LingerState = new LingerOption(true, 0);
tcpClient.Dispose();
}
}
catch
{
}
}
await HandleClient(tcpClient, endPoint);
});
}
// Get the listener that handles the client request.
endPoint.Listener.BeginAcceptTcpClient(OnAcceptConnection, endPoint);
}
#endif
private async Task HandleClient(TcpClient tcpClient, ProxyEndPoint endPoint)
{
Interlocked.Increment(ref clientConnectionCount);
tcpClient.ReceiveTimeout = ConnectionTimeOutSeconds * 1000;
tcpClient.SendTimeout = ConnectionTimeOutSeconds * 1000;
try
{
if (endPoint.GetType() == typeof(TransparentProxyEndPoint))
{
await HandleClient(endPoint as TransparentProxyEndPoint, tcpClient);
}
else
{
await HandleClient(endPoint as ExplicitProxyEndPoint, tcpClient);
}
}
finally
{
Interlocked.Decrement(ref clientConnectionCount);
try
{
if (tcpClient != null)
{
//This line is important!
//contributors please don't remove it without discussion
//It helps to avoid eventual deterioration of performance due to TCP port exhaustion
//due to default TCP CLOSE_WAIT timeout for 4 minutes
tcpClient.LingerState = new LingerOption(true, 0);
tcpClient.Dispose();
}
}
catch
{
}
}
}
/// <summary>
/// Quit listening on the given end point
......
......@@ -132,7 +132,7 @@ namespace Titanium.Web.Proxy
if (TunnelConnectResponse != null)
{
connectArgs.IsHttps = isClientHello;
connectArgs.IsHttpsConnect = isClientHello;
await TunnelConnectResponse.InvokeParallelAsync(this, connectArgs, ExceptionFunc);
}
......@@ -189,7 +189,7 @@ namespace Titanium.Web.Proxy
//Now create the request
disposed = await HandleHttpSessionRequest(tcpClient, httpCmd, clientStream, clientStreamReader, clientStreamWriter,
httpRemoteUri.Scheme == Uri.UriSchemeHttps ? httpRemoteUri.Host : null, endPoint, connectRequest);
httpRemoteUri.Scheme == UriSchemeHttps ? httpRemoteUri.Host : null, endPoint, connectRequest);
}
catch (Exception e)
{
......@@ -548,7 +548,7 @@ namespace Titanium.Web.Proxy
ExternalProxy customUpStreamHttpProxy = null;
ExternalProxy customUpStreamHttpsProxy = null;
if (args.WebSession.Request.RequestUri.Scheme == "http")
if (args.WebSession.Request.RequestUri.Scheme == UriSchemeHttp)
{
if (GetCustomUpStreamHttpProxyFunc != null)
{
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard1.5</TargetFramework>
<RootNamespace>Titanium.Web.Proxy</RootNamespace>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Properties\AssemblyInfo.cs" />
<Compile Remove="Helpers\WinHttp\NativeMethods.WinHttp.cs" />
<Compile Remove="Helpers\WinHttp\WinHttpHandle.cs" />
<Compile Remove="Helpers\WinHttp\WinHttpWebProxyFinder.cs" />
<Compile Remove="Helpers\NativeMethods.SystemProxy.cs" />
<Compile Remove="Helpers\NativeMethods.Tcp.cs" />
<Compile Remove="Helpers\Firefox.cs" />
<Compile Remove="Helpers\ProxyInfo.cs" />
<Compile Remove="Helpers\RunTime.cs" />
<Compile Remove="Helpers\SystemProxy.cs" />
<Compile Remove="Network\Certificate\WinCertificateMaker.cs" />
<Compile Remove="Network\Tcp\TcpRow.cs" />
<Compile Remove="Network\Tcp\TcpTable.cs" />
<Compile Remove="Network\WinAuth\Security\Common.cs" />
<Compile Remove="Network\WinAuth\Security\LittleEndian.cs" />
<Compile Remove="Network\WinAuth\Security\Message.cs" />
<Compile Remove="Network\WinAuth\Security\State.cs" />
<Compile Remove="Network\WinAuth\Security\WinAuthEndPoint.cs" />
<Compile Remove="Network\WinAuth\WinAuthHandler.cs" />
<Compile Remove="WinAuthHandler.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Portable.BouncyCastle" Version="1.8.1.2" />
<PackageReference Include="System.Net.NameResolution" Version="4.3.0" />
<PackageReference Include="System.Net.Security" Version="4.3.1" />
<PackageReference Include="System.Runtime.Serialization.Formatters" Version="4.3.0" />
<PackageReference Include="System.Security.SecureString" Version="4.3.0" />
</ItemGroup>
</Project>
\ No newline at end of file
......@@ -93,13 +93,7 @@
<Compile Include="Helpers\Firefox.cs" />
<Compile Include="Helpers\HttpHelper.cs" />
<Compile Include="Helpers\Network.cs" />
<Compile Include="Helpers\ProxyInfo.cs" />
<Compile Include="Helpers\RunTime.cs" />
<Compile Include="Helpers\SystemProxy.cs" />
<Compile Include="Helpers\Tcp.cs" />
<Compile Include="Helpers\WinHttp\NativeMethods.WinHttp.cs" />
<Compile Include="Helpers\WinHttp\WinHttpHandle.cs" />
<Compile Include="Helpers\WinHttp\WinHttpWebProxyFinder.cs" />
<Compile Include="Http\ConnectRequest.cs" />
<Compile Include="Http\ConnectResponse.cs" />
<Compile Include="Http\HeaderCollection.cs" />
......@@ -138,8 +132,14 @@
<Compile Include="ResponseHandler.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="Helpers\WinHttp\NativeMethods.WinHttp.cs" />
<Compile Include="Helpers\WinHttp\WinHttpHandle.cs" />
<Compile Include="Helpers\WinHttp\WinHttpWebProxyFinder.cs" />
<Compile Include="Helpers\NativeMethods.SystemProxy.cs" />
<Compile Include="Helpers\NativeMethods.Tcp.cs" />
<Compile Include="Helpers\ProxyInfo.cs" />
<Compile Include="Helpers\RunTime.cs" />
<Compile Include="Helpers\SystemProxy.cs" />
<Compile Include="Network\Tcp\TcpRow.cs" />
<Compile Include="Network\Tcp\TcpTable.cs" />
</ItemGroup>
......
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