-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathServicePoint.cs
519 lines (444 loc) · 11.6 KB
/
ServicePoint.cs
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//
// System.Net.ServicePoint
//
// Authors:
// Lawrence Pit ([email protected])
// Gonzalo Paniagua Javier ([email protected])
//
// (c) 2002 Lawrence Pit
// (c) 2003 Ximian, Inc. (http://www.ximian.com)
//
// Copyright (c) 2018 Nivloc Enterprises Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Collections;
#if SSHARP
using Crestron.SimplSharp;
using SSMono.Security.Cryptography.X509Certificates;
using Timer = Crestron.SimplSharp.CTimer;
using Socket = Crestron.SimplSharp.CrestronSockets.CrestronClientSocket;
#else
using System.Diagnostics;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
#endif
#if SSHARP
namespace SSMono.Net
#else
namespace System.Net
#endif
{
public class ServicePoint
{
private Uri uri;
private int connectionLimit;
private int maxIdleTime;
private int currentConnections;
private DateTime idleSince;
private Version protocolVersion;
private X509Certificate certificate;
private X509Certificate clientCertificate;
private IPHostEntry host;
private bool usesProxy;
private Dictionary<string, WebConnectionGroup> groups;
private bool sendContinue = true;
private bool useConnect;
private object hostE = new object ();
private bool useNagle;
private BindIPEndPoint endPointCallback = null;
private bool tcp_keepalive;
private int tcp_keepalive_time;
private int tcp_keepalive_interval;
private Timer idleTimer;
// Constructors
internal ServicePoint (Uri uri, int connectionLimit, int maxIdleTime)
{
this.uri = uri;
this.connectionLimit = connectionLimit;
this.maxIdleTime = maxIdleTime;
this.currentConnections = 0;
this.idleSince = DateTime.UtcNow;
}
// Properties
public Uri Address
{
get { return uri; }
}
private static Exception GetMustImplement ()
{
return new NotImplementedException ();
}
public BindIPEndPoint BindIPEndPointDelegate
{
get { return endPointCallback; }
set { endPointCallback = value; }
}
public X509Certificate Certificate
{
get { return certificate; }
}
public X509Certificate ClientCertificate
{
get { return clientCertificate; }
}
[MonoTODO]
public int ConnectionLeaseTimeout
{
get { throw GetMustImplement (); }
set { throw GetMustImplement (); }
}
public int ConnectionLimit
{
get { return connectionLimit; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException ();
connectionLimit = value;
}
}
public string ConnectionName
{
get { return uri.Scheme; }
}
public int CurrentConnections
{
get { return currentConnections; }
}
public DateTime IdleSince
{
get { return idleSince.ToLocalTime (); }
}
public int MaxIdleTime
{
get { return maxIdleTime; }
set
{
if (value < Timeout.Infinite || value > Int32.MaxValue)
throw new ArgumentOutOfRangeException ();
lock (this)
{
maxIdleTime = value;
if (idleTimer != null)
idleTimer.Change (maxIdleTime, maxIdleTime);
}
}
}
public virtual Version ProtocolVersion
{
get { return protocolVersion; }
}
[MonoTODO]
public int ReceiveBufferSize
{
get { throw GetMustImplement (); }
set { throw GetMustImplement (); }
}
public bool SupportsPipelining
{
get { return HttpVersion.Version11.Equals (protocolVersion); }
}
public bool Expect100Continue
{
get { return SendContinue; }
set { SendContinue = value; }
}
public bool UseNagleAlgorithm
{
get { return useNagle; }
set { useNagle = value; }
}
internal bool SendContinue
{
get { return sendContinue && (protocolVersion == null || protocolVersion == HttpVersion.Version11); }
set { sendContinue = value; }
}
// Methods
public void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval)
{
if (enabled)
{
if (keepAliveTime <= 0)
throw new ArgumentOutOfRangeException ("keepAliveTime", "Must be greater than 0");
if (keepAliveInterval <= 0)
throw new ArgumentOutOfRangeException ("keepAliveInterval", "Must be greater than 0");
}
tcp_keepalive = enabled;
tcp_keepalive_time = keepAliveTime;
tcp_keepalive_interval = keepAliveInterval;
}
internal void KeepAliveSetup (Socket socket)
{
#if SSHARP
#else
if (!tcp_keepalive)
return;
byte[] bytes = new byte[12];
PutBytes (bytes, (uint)(tcp_keepalive ? 1 : 0), 0);
PutBytes (bytes, (uint)tcp_keepalive_time, 4);
PutBytes (bytes, (uint)tcp_keepalive_interval, 8);
socket.IOControl (IOControlCode.KeepAliveValues, bytes, null);
#endif
}
private static void PutBytes (byte[] bytes, uint v, int offset)
{
if (BitConverter.IsLittleEndian)
{
bytes[offset] = (byte)(v & 0x000000ff);
bytes[offset + 1] = (byte)((v & 0x0000ff00) >> 8);
bytes[offset + 2] = (byte)((v & 0x00ff0000) >> 16);
bytes[offset + 3] = (byte)((v & 0xff000000) >> 24);
}
else
{
bytes[offset + 3] = (byte)(v & 0x000000ff);
bytes[offset + 2] = (byte)((v & 0x0000ff00) >> 8);
bytes[offset + 1] = (byte)((v & 0x00ff0000) >> 16);
bytes[offset] = (byte)((v & 0xff000000) >> 24);
}
}
// Internal Methods
internal bool UsesProxy
{
get { return usesProxy; }
set { usesProxy = value; }
}
internal bool UseConnect
{
get { return useConnect; }
set { useConnect = value; }
}
private WebConnectionGroup GetConnectionGroup (string name)
{
if (name == null)
name = "";
/*
* Optimization:
*
* In the vast majority of cases, we only have one single WebConnectionGroup per ServicePoint, so we
* don't need to allocate a dictionary.
*
*/
WebConnectionGroup group;
if (groups != null && groups.TryGetValue (name, out group))
return group;
group = new WebConnectionGroup (this, name);
group.ConnectionClosed += (s, e) => currentConnections--;
if (groups == null)
groups = new Dictionary<string, WebConnectionGroup> ();
groups.Add (name, group);
return group;
}
private void RemoveConnectionGroup (WebConnectionGroup group)
{
if (groups == null)
return;
if (groups.Count == 0)
throw new InvalidOperationException ();
groups.Remove (group.Name);
}
internal bool CheckAvailableForRecycling (out DateTime outIdleSince)
{
outIdleSince = DateTime.MinValue;
TimeSpan idleTimeSpan;
List<WebConnectionGroup> groupList = null, removeList = null;
lock (this)
{
if (groups == null || groups.Count == 0)
{
idleSince = DateTime.MinValue;
return true;
}
idleTimeSpan = TimeSpan.FromMilliseconds (maxIdleTime);
/*
* WebConnectionGroup.TryRecycle() must run outside the lock, so we need to
* copy the group dictionary if it exists.
*
* In most cases, we only have a single connection group, so we can simply store
* that in a local variable instead of copying a collection.
*
*/
groupList = new List<WebConnectionGroup> (groups.Values);
}
foreach (var group in groupList)
{
if (!group.TryRecycle (idleTimeSpan, ref outIdleSince))
continue;
if (removeList == null)
removeList = new List<WebConnectionGroup> ();
removeList.Add (group);
}
lock (this)
{
idleSince = outIdleSince;
if (removeList != null)
{
foreach (var group in removeList)
RemoveConnectionGroup (group);
}
if (groups != null && groups.Count == 0)
groups = null;
if (groups == null)
{
if (idleTimer != null)
{
idleTimer.Dispose ();
idleTimer = null;
}
return true;
}
return false;
}
}
private void IdleTimerCallback (object obj)
{
DateTime dummy;
CheckAvailableForRecycling (out dummy);
}
internal IPHostEntry HostEntry
{
get
{
lock (hostE)
{
if (host != null)
return host;
string uriHost = uri.Host;
// There is no need to do DNS resolution on literal IP addresses
if (uri.HostNameType == UriHostNameType.IPv6 || uri.HostNameType == UriHostNameType.IPv4)
{
if (uri.HostNameType == UriHostNameType.IPv6)
{
// Remove square brackets
uriHost = uriHost.Substring (1, uriHost.Length - 2);
}
// Creates IPHostEntry
host = new IPHostEntry ();
host.AddressList = new IPAddress[] {IPAddress.Parse (uriHost)};
return host;
}
// Try DNS resolution on host names
try
{
#if SSHARP
IPAddress[] addrs = DnsEx.GetHostAddresses (uriHost);
host = new IPHostEntry { AddressList = addrs, HostName = uriHost };
#else
host = Dns.GetHostByName (uriHost);
#endif
}
catch
{
return null;
}
}
return host;
}
}
internal void SetVersion (Version version)
{
protocolVersion = version;
}
internal EventHandler SendRequest (HttpWebRequest request, string groupName)
{
WebConnection cnc;
lock (this)
{
bool created;
WebConnectionGroup cncGroup = GetConnectionGroup (groupName);
cnc = cncGroup.GetConnection (request, out created);
if (created)
{
++currentConnections;
if (idleTimer == null)
idleTimer = new Timer (IdleTimerCallback, null, maxIdleTime, maxIdleTime);
}
}
return cnc.SendRequest (request);
}
public bool CloseConnectionGroup (string connectionGroupName)
{
lock (this)
{
WebConnectionGroup cncGroup = GetConnectionGroup (connectionGroupName);
if (cncGroup != null)
{
cncGroup.Close ();
return true;
}
}
return false;
}
internal void SetCertificates (X509Certificate client, X509Certificate server)
{
certificate = server;
clientCertificate = client;
}
internal bool CallEndPointDelegate (Socket sock, IPEndPoint remote)
{
if (endPointCallback == null)
return true;
int count = 0;
for (;;)
{
IPEndPoint local = null;
try
{
local = endPointCallback (this, remote, count);
}
catch
{
// This is to differentiate from an
// OverflowException, which should propagate.
return false;
}
if (local == null)
return true;
#if SSHARP
return false;
#else
try
{
//sock.LocalEndPoint = local;
sock.Bind (local);
}
catch (SocketException)
{
// This is intentional; the docs say
// that if the Bind fails, we keep
// going until there is an
// OverflowException on the retry
// count.
checked
{
++count;
}
continue;
}
return true;
#endif
}
}
}
}