forked from extremecodetv/SocksSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProxyClientHandler.cs
More file actions
222 lines (183 loc) · 7.89 KB
/
Copy pathProxyClientHandler.cs
File metadata and controls
222 lines (183 loc) · 7.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
using System;
using System.IO;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Threading;
using System.Threading.Tasks;
using SocksSharp.Proxy;
using SocksSharp.Proxy.Request;
using SocksSharp.Proxy.Response;
namespace SocksSharp
{
/// <summary>
/// Represents <see cref="HttpMessageHandler"/> with <see cref="IProxyClient{T}"/>
/// to provide the <see cref="HttpClient"/> support for <see cref="IProxy"/> proxy type
/// </summary>
/// <typeparam name="T"></typeparam>
public class ProxyClientHandler<T> : HttpMessageHandler, IDisposable where T : IProxy
{
private readonly IProxyClient<T> proxyClient;
private Stream connectionCommonStream;
private NetworkStream connectionNetworkStream;
#region Properties
/// <summary>
/// Gets a current ProxyClient
/// </summary>
public IProxyClient<T> Proxy => proxyClient;
/// <summary>
/// Gets a value that indicates whether the handler uses a proxy for requests.
/// </summary>
public bool UseProxy => true;
/// <summary>
/// Gets a value that indicates whether the handler supports proxy settings.
/// </summary>
public bool SupportsProxy => true;
/// <summary>
/// Gets a value that indicates whether the handler should follow redirection responses.
/// </summary>
public bool AllowAutoRedirect => false;
/// <summary>
/// Gets a value that indicates whether the handler supports
/// configuration settings for the <see cref="AllowAutoRedirect"/>
/// </summary>
public bool SupportsRedirectConfiguration => false;
/// <summary>
/// Gets the type of decompression method used by the handler for automatic
/// decompression of the HTTP content response.
/// </summary>
/// <remarks>
/// Support GZip and Deflate encoding automatically
/// </remarks>
public DecompressionMethods AutomaticDecompression
{
get => DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
/// <summary>
/// Gets or sets a value that indicates whether the handler uses the CookieContainer
/// property to store server cookies and uses these cookies when sending requests.
/// </summary>
public bool UseCookies { get; set; }
/// <summary>
/// Gets or sets the cookie container used to store server cookies by the handler.
/// </summary>
public CookieContainer CookieContainer { get; set; }
/// <summary>
/// Gets or sets delegate to verifies the remote Secure Sockets Layer (SSL)
/// certificate used for authentication.
/// </summary>
public RemoteCertificateValidationCallback ServerCertificateCustomValidationCallback { get; set; }
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="ProxyClientHandler{T}"/> with <see cref="ProxySettings"/> settings
/// </summary>
/// <param name="proxySettings">Proxy settings</param>
/// <exception cref="ArgumentNullException">
/// Value of parameter is <see langword="null"/>
/// </exception>
public ProxyClientHandler(ProxySettings proxySettings)
{
if(proxySettings == null)
{
throw new ArgumentNullException(nameof(proxySettings));
}
this.proxyClient = (IProxyClient<T>)Activator.CreateInstance(typeof(ProxyClient<T>));
this.proxyClient.Settings = proxySettings;
}
/// <summary>
/// Creates an instance of HttpResponseMessage based on the information provided in the HttpRequestMessage as an operation that will not block.
/// </summary>
/// <param name="request">The HTTP request message.</param>
/// <param name="cancellationToken">A cancellation token to cancel the operation.</param>
/// <returns>Instance of <see cref="HttpResponseMessage"/> containing http response</returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if(request == null)
{
throw new ArgumentNullException(nameof(request));
}
return await Task.Run(async () =>
{
if (UseCookies && CookieContainer == null)
{
throw new ArgumentNullException(nameof(CookieContainer));
}
CreateConnection(request);
await SendDataAsync(request, cancellationToken).ConfigureAwait(false);
var responseMessage = await ReceiveDataAsync(request, cancellationToken).ConfigureAwait(false);
return responseMessage;
}).ConfigureAwait(false);
}
#region Methods (private)
private async Task SendDataAsync(HttpRequestMessage request, CancellationToken ct)
{
byte[] buffer;
var hasContent = request.Content != null;
var requestBuilder = UseCookies
? new RequestBuilder(request, CookieContainer)
: new RequestBuilder(request);
//Send starting line
buffer = requestBuilder.BuildStartingLine();
await connectionCommonStream.WriteAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false);
//Send headers
buffer = requestBuilder.BuildHeaders(hasContent);
await connectionCommonStream.WriteAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false);
if (hasContent)
{
await SendContentAsync(request, ct).ConfigureAwait(false);
}
}
private async Task<HttpResponseMessage> ReceiveDataAsync(HttpRequestMessage request, CancellationToken ct)
{
var responseBuilder = UseCookies
? new ResponseBuilder(1024, CookieContainer, request.RequestUri)
: new ResponseBuilder(1024);
return await responseBuilder.GetResponseAsync(request, connectionCommonStream, ct);
}
private void CreateConnection(HttpRequestMessage request)
{
Uri uri = request.RequestUri;
connectionNetworkStream = proxyClient.GetDestinationStream(uri.Host, uri.Port);
if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
{
try
{
SslStream sslStream;
sslStream = new SslStream(connectionNetworkStream, false, ServerCertificateCustomValidationCallback);
sslStream.AuthenticateAsClient(uri.Host);
connectionCommonStream = sslStream;
}
catch (Exception ex)
{
if (ex is IOException || ex is AuthenticationException)
{
throw new ProxyException("Failed SSL connect");
}
throw;
}
}
else
{
connectionCommonStream = connectionNetworkStream;
}
}
private async Task SendContentAsync(HttpRequestMessage request, CancellationToken ct)
{
var buffer = await request.Content.ReadAsByteArrayAsync();
await connectionCommonStream.WriteAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
connectionCommonStream?.Dispose();
connectionNetworkStream?.Dispose();
}
base.Dispose(disposing);
}
#endregion
}
}