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
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
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.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Text;
using SocketHttpListener.Primitives;
using ProtocolType = MediaBrowser.Model.Net.ProtocolType;
using SocketType = MediaBrowser.Model.Net.SocketType;
namespace SocketHttpListener.Net
{
sealed class EndPointListener
{
HttpListener listener;
IPEndPoint endpoint;
Socket sock;
Dictionary<ListenerPrefix, HttpListener> prefixes; // Dictionary <ListenerPrefix, HttpListener>
List<ListenerPrefix> unhandled; // List<ListenerPrefix> unhandled; host = '*'
List<ListenerPrefix> all; // List<ListenerPrefix> all; host = '+'
X509Certificate cert;
bool secure;
Dictionary<HttpConnection, HttpConnection> unregistered;
private readonly ILogger _logger;
private bool _closed;
private bool _enableDualMode;
private readonly ICryptoProvider _cryptoProvider;
private readonly ISocketFactory _socketFactory;
private readonly ITextEncoding _textEncoding;
private readonly IMemoryStreamFactory _memoryStreamFactory;
private readonly IFileSystem _fileSystem;
private readonly IEnvironmentInfo _environment;
public EndPointListener(HttpListener listener, IPAddress addr, int port, bool secure, X509Certificate cert, ILogger logger, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, IMemoryStreamFactory memoryStreamFactory, ITextEncoding textEncoding, IFileSystem fileSystem, IEnvironmentInfo environment)
{
this.listener = listener;
_logger = logger;
_cryptoProvider = cryptoProvider;
_socketFactory = socketFactory;
_memoryStreamFactory = memoryStreamFactory;
_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>();
unregistered = new Dictionary<HttpConnection, HttpConnection>();
CreateSocket();
}
internal HttpListener Listener
{
get
{
return listener;
}
}
private void CreateSocket()
{
try
{
sock = CreateSocket(endpoint.Address.AddressFamily, _enableDualMode);
}
catch (SocketCreateException ex)
{
if (_enableDualMode && endpoint.Address.Equals(IPAddress.IPv6Any) &&
(string.Equals(ex.ErrorCode, "AddressFamilyNotSupported", StringComparison.OrdinalIgnoreCase) ||
// mono on bsd is throwing this
string.Equals(ex.ErrorCode, "ProtocolNotSupported", StringComparison.OrdinalIgnoreCase)))
{
endpoint = new IPEndPoint(IPAddress.Any, endpoint.Port);
_enableDualMode = false;
sock = CreateSocket(endpoint.Address.AddressFamily, _enableDualMode);
}
else
{
throw;
}
}
try
{
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
}
catch (SocketException)
{
// This is not supported on all operating systems (qnap)
}
sock.Bind(endpoint);
// This is the number TcpListener uses.
sock.Listen(2147483647);
new SocketAcceptor(_logger, sock, ProcessAccept, () => _closed).StartAccept();
_closed = false;
}
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;
}
}
}
private async void ProcessAccept(Socket accepted)
{
try
{
var listener = this;
if (listener.secure && listener.cert == null)
{
accepted.Close();
return;
}
HttpConnection conn = await HttpConnection.Create(_logger, accepted, listener, listener.secure, listener.cert, _cryptoProvider, _memoryStreamFactory, _textEncoding, _fileSystem, _environment).ConfigureAwait(false);
//_logger.Debug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId);
lock (listener.unregistered)
{
listener.unregistered[conn] = conn;
}
conn.BeginReadRequest();
}
catch (Exception ex)
{
_logger.ErrorException("Error in ProcessAccept", ex);
}
}
internal void RemoveConnection(HttpConnection conn)
{
lock (unregistered)
{
unregistered.Remove(conn);
}
}
public bool BindContext(HttpListenerContext context)
{
HttpListenerRequest req = context.Request;
ListenerPrefix prefix;
HttpListener listener = SearchListener(req.Url, out 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);
}
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 path_slash = path[path.Length - 1] == '/' ? path : path + "/";
HttpListener best_match = null;
int best_length = -1;
if (host != null && host != "")
{
var p_ro = prefixes;
foreach (ListenerPrefix p in p_ro.Keys)
{
string ppath = p.Path;
if (ppath.Length < best_length)
continue;
if (p.Host != host || p.Port != port)
continue;
if (path.StartsWith(ppath) || path_slash.StartsWith(ppath))
{
best_length = ppath.Length;
best_match = (HttpListener)p_ro[p];
prefix = p;
}
}
if (best_length != -1)
return best_match;
}
List<ListenerPrefix> list = unhandled;
best_match = MatchFromList(host, path, list, out prefix);
if (path != path_slash && best_match == null)
best_match = MatchFromList(host, path_slash, list, out prefix);
if (best_match != null)
return best_match;
list = all;
best_match = MatchFromList(host, path, list, out prefix);
if (path != path_slash && best_match == null)
best_match = MatchFromList(host, path_slash, list, out prefix);
if (best_match != null)
return best_match;
return null;
}
HttpListener MatchFromList(string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
{
prefix = null;
if (list == null)
return null;
HttpListener best_match = null;
int best_length = -1;
foreach (ListenerPrefix p in list)
{
string ppath = p.Path;
if (ppath.Length < best_length)
continue;
if (path.StartsWith(ppath))
{
best_length = ppath.Length;
best_match = p.Listener;
prefix = p;
}
}
return best_match;
}
void AddSpecial(List<ListenerPrefix> coll, ListenerPrefix prefix)
{
if (coll == null)
return;
foreach (ListenerPrefix p in coll)
{
if (p.Path == prefix.Path) //TODO: code
throw new HttpListenerException(400, "Prefix already in use.");
}
coll.Add(prefix);
}
bool RemoveSpecial(List<ListenerPrefix> coll, ListenerPrefix prefix)
{
if (coll == null)
return false;
int c = coll.Count;
for (int i = 0; i < c; i++)
{
ListenerPrefix p = (ListenerPrefix)coll[i];
if (p.Path == prefix.Path)
{
coll.RemoveAt(i);
return true;
}
}
return false;
}
void CheckIfRemove()
{
if (prefixes.Count > 0)
return;
List<ListenerPrefix> list = unhandled;
if (list != null && list.Count > 0)
return;
list = all;
if (list != null && list.Count > 0)
return;
EndPointManager.RemoveEndPoint(this, endpoint);
}
public void Close()
{
_closed = true;
sock.Close();
lock (unregistered)
{
//
// Clone the list because RemoveConnection can be called from Close
//
var connections = new List<HttpConnection>(unregistered.Keys);
foreach (HttpConnection c in connections)
c.Close(true);
unregistered.Clear();
}
}
public void AddPrefix(ListenerPrefix prefix, HttpListener listener)
{
List<ListenerPrefix> current;
List<ListenerPrefix> future;
if (prefix.Host == "*")
{
do
{
current = unhandled;
future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
prefix.Listener = listener;
AddSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref unhandled, future, current) != current);
return;
}
if (prefix.Host == "+")
{
do
{
current = all;
future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
prefix.Listener = listener;
AddSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref all, future, current) != current);
return;
}
Dictionary<ListenerPrefix, HttpListener> prefs;
Dictionary<ListenerPrefix, HttpListener> p2;
do
{
prefs = prefixes;
if (prefs.ContainsKey(prefix))
{
HttpListener other = (HttpListener)prefs[prefix];
if (other != listener) // TODO: code.
throw new HttpListenerException(400, "There's another listener for " + prefix);
return;
}
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 = unhandled;
future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
if (!RemoveSpecial(future, prefix))
break; // Prefix not found
} while (Interlocked.CompareExchange(ref unhandled, future, current) != current);
CheckIfRemove();
return;
}
if (prefix.Host == "+")
{
do
{
current = all;
future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
if (!RemoveSpecial(future, prefix))
break; // Prefix not found
} while (Interlocked.CompareExchange(ref all, future, current) != current);
CheckIfRemove();
return;
}
Dictionary<ListenerPrefix, HttpListener> prefs;
Dictionary<ListenerPrefix, HttpListener> 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();
}
}
}
|