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
520
521
522
523
524
525
526
527
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Text;
using Microsoft.Extensions.Logging;
namespace SocketHttpListener.Net
{
internal sealed class HttpEndPointListener
{
private HttpListener _listener;
private IPEndPoint _endpoint;
private Socket _socket;
private Dictionary<ListenerPrefix, HttpListener> _prefixes;
private List<ListenerPrefix> _unhandledPrefixes; // host = '*'
private List<ListenerPrefix> _allPrefixes; // host = '+'
private X509Certificate _cert;
private bool _secure;
private Dictionary<HttpConnection, HttpConnection> _unregisteredConnections;
private readonly ILogger _logger;
private bool _closed;
private bool _enableDualMode;
private readonly ICryptoProvider _cryptoProvider;
private readonly ISocketFactory _socketFactory;
private readonly ITextEncoding _textEncoding;
private readonly IStreamHelper _streamHelper;
private readonly IFileSystem _fileSystem;
private readonly IEnvironmentInfo _environment;
public HttpEndPointListener(HttpListener listener, IPAddress addr, int port, bool secure, X509Certificate cert, ILogger logger, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, IStreamHelper streamHelper, ITextEncoding textEncoding, IFileSystem fileSystem, IEnvironmentInfo environment)
{
this._listener = listener;
_logger = logger;
_cryptoProvider = cryptoProvider;
_socketFactory = socketFactory;
_streamHelper = streamHelper;
_textEncoding = textEncoding;
_fileSystem = fileSystem;
_environment = environment;
this._secure = secure;
this._cert = cert;
_enableDualMode = addr.Equals(IPAddress.IPv6Any);
_endpoint = new IPEndPoint(addr, port);
_prefixes = new Dictionary<ListenerPrefix, HttpListener>();
_unregisteredConnections = new Dictionary<HttpConnection, HttpConnection>();
CreateSocket();
}
internal HttpListener Listener => _listener;
private void CreateSocket()
{
try
{
_socket = CreateSocket(_endpoint.Address.AddressFamily, _enableDualMode);
}
catch (SocketCreateException ex)
{
if (_enableDualMode && _endpoint.Address.Equals(IPAddress.IPv6Any) &&
(string.Equals(ex.ErrorCode, "AddressFamilyNotSupported", StringComparison.OrdinalIgnoreCase) ||
// mono 4.8.1 and lower on bsd is throwing this
string.Equals(ex.ErrorCode, "ProtocolNotSupported", StringComparison.OrdinalIgnoreCase) ||
// mono 5.2 on bsd is throwing this
string.Equals(ex.ErrorCode, "OperationNotSupported", StringComparison.OrdinalIgnoreCase)))
{
_endpoint = new IPEndPoint(IPAddress.Any, _endpoint.Port);
_enableDualMode = false;
_socket = CreateSocket(_endpoint.Address.AddressFamily, _enableDualMode);
}
else
{
throw;
}
}
try
{
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
}
catch (SocketException)
{
// This is not supported on all operating systems (qnap)
}
_socket.Bind(_endpoint);
// This is the number TcpListener uses.
_socket.Listen(2147483647);
Accept();
_closed = false;
}
private void Accept()
{
var acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.UserToken = this;
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAccept);
Accept(acceptEventArg);
}
private static void TryCloseAndDispose(Socket socket)
{
try
{
using (socket)
{
socket.Close();
}
}
catch
{
}
}
private static void TryClose(Socket socket)
{
try
{
socket.Close();
}
catch
{
}
}
private void Accept(SocketAsyncEventArgs acceptEventArg)
{
// acceptSocket must be cleared since the context object is being reused
acceptEventArg.AcceptSocket = null;
try
{
bool willRaiseEvent = _socket.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
ProcessAccept(acceptEventArg);
}
}
catch (ObjectDisposedException)
{
// TODO Investigate or properly fix.
}
catch (Exception ex)
{
var epl = (HttpEndPointListener)acceptEventArg.UserToken;
epl._logger.LogError(ex, "Error in socket.AcceptAsync");
}
}
// This method is the callback method associated with Socket.AcceptAsync
// operations and is invoked when an accept operation is complete
//
private static void OnAccept(object sender, SocketAsyncEventArgs e)
{
ProcessAccept(e);
}
private static async void ProcessAccept(SocketAsyncEventArgs args)
{
var epl = (HttpEndPointListener)args.UserToken;
if (epl._closed)
{
return;
}
// http://msdn.microsoft.com/en-us/library/system.net.sockets.acceptSocket.acceptasync%28v=vs.110%29.aspx
// Under certain conditions ConnectionReset can occur
// Need to attept to re-accept
var socketError = args.SocketError;
var accepted = args.AcceptSocket;
epl.Accept(args);
if (socketError == SocketError.ConnectionReset)
{
epl._logger.LogError("SocketError.ConnectionReset reported. Attempting to re-accept.");
return;
}
if (accepted == null)
{
return;
}
if (epl._secure && epl._cert == null)
{
TryClose(accepted);
return;
}
try
{
var remoteEndPointString = accepted.RemoteEndPoint == null ? string.Empty : accepted.RemoteEndPoint.ToString();
var localEndPointString = accepted.LocalEndPoint == null ? string.Empty : accepted.LocalEndPoint.ToString();
//_logger.LogInformation("HttpEndPointListener Accepting connection from {0} to {1} secure connection requested: {2}", remoteEndPointString, localEndPointString, _secure);
var conn = new HttpConnection(epl._logger, accepted, epl, epl._secure, epl._cert, epl._cryptoProvider, epl._streamHelper, epl._textEncoding, epl._fileSystem, epl._environment);
await conn.Init().ConfigureAwait(false);
//_logger.LogDebug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId);
lock (epl._unregisteredConnections)
{
epl._unregisteredConnections[conn] = conn;
}
conn.BeginReadRequest();
}
catch (Exception ex)
{
epl._logger.LogError(ex, "Error in ProcessAccept");
TryClose(accepted);
epl.Accept();
return;
}
}
private Socket CreateSocket(AddressFamily addressFamily, bool dualMode)
{
try
{
var socket = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
if (dualMode)
{
socket.DualMode = true;
}
return socket;
}
catch (SocketException ex)
{
throw new SocketCreateException(ex.SocketErrorCode.ToString(), ex);
}
catch (ArgumentException ex)
{
if (dualMode)
{
// Mono for BSD incorrectly throws ArgumentException instead of SocketException
throw new SocketCreateException("AddressFamilyNotSupported", ex);
}
else
{
throw;
}
}
}
internal void RemoveConnection(HttpConnection conn)
{
lock (_unregisteredConnections)
{
_unregisteredConnections.Remove(conn);
}
}
public bool BindContext(HttpListenerContext context)
{
var req = context.Request;
HttpListener listener = SearchListener(req.Url, out var prefix);
if (listener == null)
return false;
context.Connection.Prefix = prefix;
return true;
}
public void UnbindContext(HttpListenerContext context)
{
if (context == null || context.Request == null)
return;
_listener.UnregisterContext(context);
}
private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix)
{
prefix = null;
if (uri == null)
return null;
string host = uri.Host;
int port = uri.Port;
string path = WebUtility.UrlDecode(uri.AbsolutePath);
string pathSlash = path[path.Length - 1] == '/' ? path : path + "/";
HttpListener bestMatch = null;
int bestLength = -1;
if (host != null && host != "")
{
Dictionary<ListenerPrefix, HttpListener> localPrefixes = _prefixes;
foreach (var p in localPrefixes.Keys)
{
string ppath = p.Path;
if (ppath.Length < bestLength)
continue;
if (p.Host != host || p.Port != port)
continue;
if (path.StartsWith(ppath) || pathSlash.StartsWith(ppath))
{
bestLength = ppath.Length;
bestMatch = localPrefixes[p];
prefix = p;
}
}
if (bestLength != -1)
return bestMatch;
}
List<ListenerPrefix> list = _unhandledPrefixes;
bestMatch = MatchFromList(host, path, list, out prefix);
if (path != pathSlash && bestMatch == null)
bestMatch = MatchFromList(host, pathSlash, list, out prefix);
if (bestMatch != null)
return bestMatch;
list = _allPrefixes;
bestMatch = MatchFromList(host, path, list, out prefix);
if (path != pathSlash && bestMatch == null)
bestMatch = MatchFromList(host, pathSlash, list, out prefix);
if (bestMatch != null)
return bestMatch;
return null;
}
private HttpListener MatchFromList(string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
{
prefix = null;
if (list == null)
return null;
HttpListener bestMatch = null;
int bestLength = -1;
foreach (ListenerPrefix p in list)
{
string ppath = p.Path;
if (ppath.Length < bestLength)
continue;
if (path.StartsWith(ppath))
{
bestLength = ppath.Length;
bestMatch = p._listener;
prefix = p;
}
}
return bestMatch;
}
private void AddSpecial(List<ListenerPrefix> list, ListenerPrefix prefix)
{
if (list == null)
return;
foreach (ListenerPrefix p in list)
{
if (p.Path == prefix.Path)
throw new Exception("net_listener_already");
}
list.Add(prefix);
}
private bool RemoveSpecial(List<ListenerPrefix> list, ListenerPrefix prefix)
{
if (list == null)
return false;
int c = list.Count;
for (int i = 0; i < c; i++)
{
ListenerPrefix p = list[i];
if (p.Path == prefix.Path)
{
list.RemoveAt(i);
return true;
}
}
return false;
}
private void CheckIfRemove()
{
if (_prefixes.Count > 0)
return;
List<ListenerPrefix> list = _unhandledPrefixes;
if (list != null && list.Count > 0)
return;
list = _allPrefixes;
if (list != null && list.Count > 0)
return;
HttpEndPointManager.RemoveEndPoint(this, _endpoint);
}
public void Close()
{
_closed = true;
_socket.Close();
lock (_unregisteredConnections)
{
// Clone the list because RemoveConnection can be called from Close
var connections = new List<HttpConnection>(_unregisteredConnections.Keys);
foreach (HttpConnection c in connections)
c.Close(true);
_unregisteredConnections.Clear();
}
}
public void AddPrefix(ListenerPrefix prefix, HttpListener listener)
{
List<ListenerPrefix> current;
List<ListenerPrefix> future;
if (prefix.Host == "*")
{
do
{
current = _unhandledPrefixes;
future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
prefix._listener = listener;
AddSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current);
return;
}
if (prefix.Host == "+")
{
do
{
current = _allPrefixes;
future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
prefix._listener = listener;
AddSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current);
return;
}
Dictionary<ListenerPrefix, HttpListener> prefs, p2;
do
{
prefs = _prefixes;
if (prefs.ContainsKey(prefix))
{
throw new Exception("net_listener_already");
}
p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
p2[prefix] = listener;
} while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs);
}
public void RemovePrefix(ListenerPrefix prefix, HttpListener listener)
{
List<ListenerPrefix> current;
List<ListenerPrefix> future;
if (prefix.Host == "*")
{
do
{
current = _unhandledPrefixes;
future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
if (!RemoveSpecial(future, prefix))
break; // Prefix not found
} while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current);
CheckIfRemove();
return;
}
if (prefix.Host == "+")
{
do
{
current = _allPrefixes;
future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
if (!RemoveSpecial(future, prefix))
break; // Prefix not found
} while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current);
CheckIfRemove();
return;
}
Dictionary<ListenerPrefix, HttpListener> prefs, p2;
do
{
prefs = _prefixes;
if (!prefs.ContainsKey(prefix))
break;
p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
p2.Remove(prefix);
} while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs);
CheckIfRemove();
}
}
}
|