Repository navigation
Expand file tree
/
Copy pathHttpListener.cs
More file actions
743 lines (654 loc) · 22.2 KB
/
Copy pathHttpListener.cs
File metadata and controls
743 lines (654 loc) · 22.2 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
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
#region License
/*
* HttpListener.cs
*
* This code is derived from System.Net.HttpListener.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2014 sta.blockhead
*
* 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.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
// TODO: Logging.
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides a simple, programmatically controlled HTTP listener.
/// </summary>
public sealed class HttpListener : IDisposable
{
#region Private Fields
private AuthenticationSchemes _authSchemes;
private Func<HttpListenerRequest, AuthenticationSchemes> _authSchemeSelector;
private string _certFolderPath;
private Dictionary<HttpConnection, HttpConnection> _connections;
private List<HttpListenerContext> _contextQueue;
private Func<IIdentity, NetworkCredential> _credentialsFinder;
private X509Certificate2 _defaultCert;
private bool _disposed;
private bool _ignoreWriteExceptions;
private bool _listening;
private HttpListenerPrefixCollection _prefixes;
private string _realm;
private Dictionary<HttpListenerContext, HttpListenerContext> _registry;
private List<ListenerAsyncResult> _waitQueue;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpListener"/> class.
/// </summary>
public HttpListener ()
{
_authSchemes = AuthenticationSchemes.Anonymous;
_connections = new Dictionary<HttpConnection, HttpConnection> ();
_contextQueue = new List<HttpListenerContext> ();
_prefixes = new HttpListenerPrefixCollection (this);
_registry = new Dictionary<HttpListenerContext, HttpListenerContext> ();
_waitQueue = new List<ListenerAsyncResult> ();
}
#endregion
#region Internal Properties
internal bool IsDisposed {
get {
return _disposed;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the scheme used to authenticate the clients.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values,
/// represents the scheme used to authenticate the clients. The default value is
/// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public AuthenticationSchemes AuthenticationSchemes {
get {
CheckDisposed ();
return _authSchemes;
}
set {
CheckDisposed ();
_authSchemes = value;
}
}
/// <summary>
/// Gets or sets the delegate called to select the scheme used to authenticate the clients.
/// </summary>
/// <remarks>
/// <para>
/// If you set this property, the listener uses the authentication scheme selected by
/// the delegate for each request.
/// </para>
/// <para>
/// If you don't set, the listener uses the value of the <c>AuthenticationSchemes</c>
/// property as the authentication scheme for all requests.
/// </para>
/// </remarks>
/// <value>
/// A <c>Func<<see cref="HttpListenerRequest"/>, <see cref="AuthenticationSchemes"/>></c>
/// delegate that invokes the method(s) used to select an authentication scheme. The default
/// value is <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public Func<HttpListenerRequest, AuthenticationSchemes> AuthenticationSchemeSelector {
get {
CheckDisposed ();
return _authSchemeSelector;
}
set {
CheckDisposed ();
_authSchemeSelector = value;
}
}
/// <summary>
/// Gets or sets the path to the folder in which stores the certificate files used to
/// authenticate the server on the secure connection.
/// </summary>
/// <remarks>
/// <para>
/// This property represents the path to the folder in which stores the certificate files
/// associated with each port number of added URI prefixes. A set of the certificate files
/// is a pair of the <c>'port number'.cer</c> (DER) and <c>'port number'.key</c>
/// (DER, RSA Private Key).
/// </para>
/// <para>
/// If this property is <see langword="null"/> or empty, the result of
/// <c>System.Environment.GetFolderPath
/// (<see cref="Environment.SpecialFolder.ApplicationData"/>)</c> is used as the default path.
/// </para>
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the path to the folder in which stores
/// the certificate files. The default value is <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public string CertificateFolderPath {
get {
CheckDisposed ();
return _certFolderPath;
}
set {
CheckDisposed ();
_certFolderPath = value;
}
}
/// <summary>
/// Gets or sets the default certificate used to authenticate the server on the secure
/// connection.
/// </summary>
/// <value>
/// A <see cref="X509Certificate2"/> used to authenticate the server if the certificate
/// files aren't found in the <see cref="CertificateFolderPath"/>. The default value is
/// <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public X509Certificate2 DefaultCertificate {
get {
CheckDisposed ();
return _defaultCert;
}
set {
CheckDisposed ();
_defaultCert = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the listener returns exceptions that occur when
/// sending the response to the client.
/// </summary>
/// <value>
/// <c>true</c> if the listener doesn't return exceptions that occur when sending the response
/// to the client; otherwise, <c>false</c>. The default value is <c>false</c>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public bool IgnoreWriteExceptions {
get {
CheckDisposed ();
return _ignoreWriteExceptions;
}
set {
CheckDisposed ();
_ignoreWriteExceptions = value;
}
}
/// <summary>
/// Gets a value indicating whether the listener has been started.
/// </summary>
/// <value>
/// <c>true</c> if the listener has been started; otherwise, <c>false</c>.
/// </value>
public bool IsListening {
get {
return _listening;
}
}
/// <summary>
/// Gets a value indicating whether the listener can be used with the current operating system.
/// </summary>
/// <value>
/// <c>true</c>.
/// </value>
public static bool IsSupported {
get {
return true;
}
}
/// <summary>
/// Gets the URI prefixes handled by the listener.
/// </summary>
/// <value>
/// A <see cref="HttpListenerPrefixCollection"/> that contains the URI prefixes.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public HttpListenerPrefixCollection Prefixes {
get {
CheckDisposed ();
return _prefixes;
}
}
/// <summary>
/// Gets or sets the name of the realm associated with the listener.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the name of the realm. The default value is
/// <c>SECRET AREA</c>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public string Realm {
get {
CheckDisposed ();
return _realm == null || _realm.Length == 0
? (_realm = "SECRET AREA")
: _realm;
}
set {
CheckDisposed ();
_realm = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether, when NTLM authentication is used,
/// the authentication information of first request is used to authenticate
/// additional requests on the same connection.
/// </summary>
/// <remarks>
/// This property isn't currently supported and always throws
/// a <see cref="NotSupportedException"/>.
/// </remarks>
/// <value>
/// <c>true</c> if the authentication information of first request is used;
/// otherwise, <c>false</c>.
/// </value>
/// <exception cref="NotSupportedException">
/// Any use of this property.
/// </exception>
public bool UnsafeConnectionNtlmAuthentication {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
/// <summary>
/// Gets or sets the delegate called to find the credentials for an identity used to
/// authenticate a client.
/// </summary>
/// <value>
/// A <c>Func<<see cref="IIdentity"/>, <see cref="NetworkCredential"/>></c> delegate
/// that invokes the method(s) used to find the credentials. The default value is a function
/// that only returns <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
get {
CheckDisposed ();
return _credentialsFinder ?? (_credentialsFinder = identity => null);
}
set {
CheckDisposed ();
_credentialsFinder = value;
}
}
#endregion
#region Private Methods
private void cleanup (bool force)
{
lock (((ICollection) _registry).SyncRoot) {
if (!force)
sendServiceUnavailable ();
cleanupContextRegistry ();
cleanupConnections ();
cleanupWaitQueue ();
}
}
private void cleanupConnections ()
{
lock (((ICollection) _connections).SyncRoot) {
if (_connections.Count == 0)
return;
// Need to copy this since closing will call RemoveConnection.
var keys = _connections.Keys;
var conns = new HttpConnection [keys.Count];
keys.CopyTo (conns, 0);
_connections.Clear ();
for (var i = conns.Length - 1; i >= 0; i--)
conns [i].Close (true);
}
}
private void cleanupContextRegistry ()
{
lock (((ICollection) _registry).SyncRoot) {
if (_registry.Count == 0)
return;
// Need to copy this since closing will call UnregisterContext.
var keys = _registry.Keys;
var all = new HttpListenerContext [keys.Count];
keys.CopyTo (all, 0);
_registry.Clear ();
for (var i = all.Length - 1; i >= 0; i--)
all [i].Connection.Close (true);
}
}
private void cleanupWaitQueue ()
{
lock (((ICollection) _waitQueue).SyncRoot) {
if (_waitQueue.Count == 0)
return;
var ex = new ObjectDisposedException (GetType ().ToString ());
foreach (var ares in _waitQueue)
ares.Complete (ex);
_waitQueue.Clear ();
}
}
private void close (bool force)
{
EndPointManager.RemoveListener (this);
cleanup (force);
}
// Must be called with a lock on _contextQueue.
private HttpListenerContext getContextFromQueue ()
{
if (_contextQueue.Count == 0)
return null;
var context = _contextQueue [0];
_contextQueue.RemoveAt (0);
return context;
}
private void sendServiceUnavailable ()
{
lock (((ICollection) _contextQueue).SyncRoot) {
if (_contextQueue.Count == 0)
return;
var contexts = _contextQueue.ToArray ();
_contextQueue.Clear ();
foreach (var context in contexts) {
var res = context.Response;
res.StatusCode = (int) HttpStatusCode.ServiceUnavailable;
res.Close ();
}
}
}
#endregion
#region Internal Methods
internal void AddConnection (HttpConnection connection)
{
lock (((ICollection) _connections).SyncRoot)
_connections [connection] = connection;
}
internal ListenerAsyncResult BeginGetContext (ListenerAsyncResult asyncResult)
{
CheckDisposed ();
if (_prefixes.Count == 0)
throw new InvalidOperationException ("Please, call AddPrefix before using this method.");
if (!_listening)
throw new InvalidOperationException ("Please, call Start before using this method.");
// Lock _waitQueue early to avoid race conditions.
lock (((ICollection) _waitQueue).SyncRoot) {
lock (((ICollection) _contextQueue).SyncRoot) {
var context = getContextFromQueue ();
if (context != null) {
asyncResult.Complete (context, true);
return asyncResult;
}
}
_waitQueue.Add (asyncResult);
}
return asyncResult;
}
internal void CheckDisposed ()
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
}
internal void RegisterContext (HttpListenerContext context)
{
lock (((ICollection) _registry).SyncRoot)
_registry [context] = context;
ListenerAsyncResult ares = null;
lock (((ICollection) _waitQueue).SyncRoot) {
if (_waitQueue.Count == 0) {
lock (((ICollection) _contextQueue).SyncRoot)
_contextQueue.Add (context);
}
else {
ares = _waitQueue [0];
_waitQueue.RemoveAt (0);
}
}
if (ares != null)
ares.Complete (context);
}
internal void RemoveConnection (HttpConnection connection)
{
lock (((ICollection) _connections).SyncRoot)
_connections.Remove (connection);
}
internal AuthenticationSchemes SelectAuthenticationScheme (HttpListenerContext context)
{
return AuthenticationSchemeSelector != null
? AuthenticationSchemeSelector (context.Request)
: _authSchemes;
}
internal void UnregisterContext (HttpListenerContext context)
{
lock (((ICollection) _registry).SyncRoot)
_registry.Remove (context);
lock (((ICollection) _contextQueue).SyncRoot) {
var i = _contextQueue.IndexOf (context);
if (i >= 0)
_contextQueue.RemoveAt (i);
}
}
#endregion
#region Public Methods
/// <summary>
/// Shuts down the listener immediately.
/// </summary>
public void Abort ()
{
if (_disposed)
return;
close (true);
_disposed = true;
}
/// <summary>
/// Begins getting an incoming request information asynchronously.
/// </summary>
/// <remarks>
/// This asynchronous operation must be completed by calling the <c>EndGetContext</c> method.
/// Typically, that method is invoked by the <paramref name="callback"/> delegate.
/// </remarks>
/// <returns>
/// An <see cref="IAsyncResult"/> that represents the status of the asynchronous operation.
/// </returns>
/// <param name="callback">
/// An <see cref="AsyncCallback"/> delegate that references the method(s) to invoke
/// when the asynchronous operation completes.
/// </param>
/// <param name="state">
/// An <see cref="object"/> that contains a user defined object to pass to
/// the <paramref name="callback"/> delegate.
/// </param>
/// <exception cref="InvalidOperationException">
/// <para>
/// This listener doesn't have any URI prefixes to listen on.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// This listener hasn't been started or is stopped currently.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public IAsyncResult BeginGetContext (AsyncCallback callback, Object state)
{
return BeginGetContext (new ListenerAsyncResult (callback, state));
}
/// <summary>
/// Shuts down the listener.
/// </summary>
public void Close ()
{
if (_disposed)
return;
close (false);
_disposed = true;
}
/// <summary>
/// Ends an asynchronous operation to get an incoming request information.
/// </summary>
/// <remarks>
/// This method completes an asynchronous operation started by calling
/// the <c>BeginGetContext</c> method.
/// </remarks>
/// <returns>
/// A <see cref="HttpListenerContext"/> that contains a request information.
/// </returns>
/// <param name="asyncResult">
/// An <see cref="IAsyncResult"/> obtained by calling the <c>BeginGetContext</c> method.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="asyncResult"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="asyncResult"/> wasn't obtained by calling the <c>BeginGetContext</c> method.
/// </exception>
/// <exception cref="InvalidOperationException">
/// This method was already called for the specified <paramref name="asyncResult"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public HttpListenerContext EndGetContext (IAsyncResult asyncResult)
{
CheckDisposed ();
if (asyncResult == null)
throw new ArgumentNullException ("asyncResult");
var ares = asyncResult as ListenerAsyncResult;
if (ares == null)
throw new ArgumentException ("Wrong IAsyncResult.", "asyncResult");
if (ares.EndCalled)
throw new InvalidOperationException ("Cannot reuse this IAsyncResult.");
ares.EndCalled = true;
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne ();
lock (((ICollection) _waitQueue).SyncRoot) {
var i = _waitQueue.IndexOf (ares);
if (i >= 0)
_waitQueue.RemoveAt (i);
}
var context = ares.GetContext ();
var scheme = SelectAuthenticationScheme (context);
if (scheme != AuthenticationSchemes.Anonymous)
context.SetUser (scheme, Realm, UserCredentialsFinder);
return context; // This will throw on error.
}
/// <summary>
/// Gets an incoming request information.
/// </summary>
/// <remarks>
/// This method waits for an incoming request and returns a request information
/// when the listener receives a request.
/// </remarks>
/// <returns>
/// A <see cref="HttpListenerContext"/> that contains a request information.
/// </returns>
/// <exception cref="InvalidOperationException">
/// <para>
/// This listener doesn't have any URI prefixes to listen on.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// This listener hasn't been started or is stopped currently.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public HttpListenerContext GetContext ()
{
var ares = BeginGetContext (new ListenerAsyncResult (null, null));
ares.InGet = true;
return EndGetContext (ares);
}
/// <summary>
/// Starts to receive incoming requests.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public void Start ()
{
CheckDisposed ();
if (_listening)
return;
EndPointManager.AddListener (this);
_listening = true;
}
/// <summary>
/// Stops receiving incoming requests.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public void Stop ()
{
CheckDisposed ();
if (!_listening)
return;
_listening = false;
EndPointManager.RemoveListener (this);
sendServiceUnavailable ();
}
#endregion
#region Explicit Interface Implementation
/// <summary>
/// Releases all resource used by the listener.
/// </summary>
void IDisposable.Dispose ()
{
if (_disposed)
return;
close (true); // TODO: Should we force here or not?
_disposed = true;
}
#endregion
}
}