/
HttpListener.cs
2902 lines (2536 loc) · 132 KB
/
HttpListener.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
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// <copyright file="HttpListener.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
//disabled until BindHandle has an overload that accepts Criticalhandles
#pragma warning disable 618
namespace System.Net {
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
using System.Diagnostics.CodeAnalysis;
public class HttpListenerBasicIdentity : GenericIdentity
{
private string m_Password;
public HttpListenerBasicIdentity(string username, string password) :
base(username, BasicClient.AuthType)
{
m_Password = password;
}
public virtual string Password
{
get
{
return m_Password;
}
}
}
internal abstract unsafe class RequestContextBase : IDisposable
{
private UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* m_MemoryBlob;
private UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* m_OriginalBlobAddress;
private byte[] m_BackingBuffer;
// Must call this from derived class' constructors.
protected void BaseConstruction(UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* requestBlob)
{
if (requestBlob == null)
{
GC.SuppressFinalize(this);
}
else
{
m_MemoryBlob = requestBlob;
}
}
// ReleasePins() should be called exactly once. It must be called before Dispose() is called, which means it must be called
// before an object (HttpListenerReqeust) which closes the RequestContext on demand is returned to the application.
internal void ReleasePins()
{
GlobalLog.Assert(m_MemoryBlob != null || m_BackingBuffer == null, "RequestContextBase::ReleasePins()|ReleasePins() called twice.");
m_OriginalBlobAddress = m_MemoryBlob;
UnsetBlob();
OnReleasePins();
}
protected abstract void OnReleasePins();
public void Close()
{
Dispose();
}
public void Dispose()
{
GlobalLog.Assert(m_MemoryBlob == null, "RequestContextBase::Dispose()|Dispose() called before ReleasePins().");
Dispose(true);
}
protected virtual void Dispose(bool disposing) { }
~RequestContextBase()
{
Dispose(false);
}
internal UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* RequestBlob
{
get
{
GlobalLog.Assert(m_MemoryBlob != null || m_BackingBuffer == null, "RequestContextBase::Dispose()|RequestBlob requested after ReleasePins().");
return m_MemoryBlob;
}
}
internal byte[] RequestBuffer
{
get
{
return m_BackingBuffer;
}
}
internal uint Size
{
get
{
return (uint) m_BackingBuffer.Length;
}
}
internal IntPtr OriginalBlobAddress
{
get
{
UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* blob = m_MemoryBlob;
return (IntPtr) (blob == null ? m_OriginalBlobAddress : blob);
}
}
protected void SetBlob(UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* requestBlob)
{
GlobalLog.Assert(m_MemoryBlob != null || m_BackingBuffer == null, "RequestContextBase::Dispose()|SetBlob() called after ReleasePins().");
if (requestBlob == null)
{
UnsetBlob();
return;
}
if (m_MemoryBlob == null)
{
GC.ReRegisterForFinalize(this);
}
m_MemoryBlob = requestBlob;
}
protected void UnsetBlob()
{
if (m_MemoryBlob != null)
{
GC.SuppressFinalize(this);
}
m_MemoryBlob = null;
}
protected void SetBuffer(int size)
{
m_BackingBuffer = size == 0 ? null : new byte[size];
}
}
internal unsafe class AsyncRequestContext : RequestContextBase
{
private NativeOverlapped* m_NativeOverlapped;
private ListenerAsyncResult m_Result;
internal AsyncRequestContext(ListenerAsyncResult result)
{
m_Result = result;
BaseConstruction(Allocate(0));
}
private UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* Allocate(uint size)
{
uint newSize = size != 0 ? size : RequestBuffer == null ? 4096 : Size;
if (m_NativeOverlapped != null && newSize != RequestBuffer.Length)
{
NativeOverlapped* nativeOverlapped = m_NativeOverlapped;
m_NativeOverlapped = null;
Overlapped.Free(nativeOverlapped);
}
if (m_NativeOverlapped == null)
{
SetBuffer(checked((int) newSize));
Overlapped overlapped = new Overlapped();
overlapped.AsyncResult = m_Result;
m_NativeOverlapped = overlapped.Pack(ListenerAsyncResult.IOCallback, RequestBuffer);
return (UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST*) Marshal.UnsafeAddrOfPinnedArrayElement(RequestBuffer, 0);
}
return RequestBlob;
}
internal void Reset(ulong requestId, uint size)
{
SetBlob(Allocate(size));
RequestBlob->RequestId = requestId;
}
protected override void OnReleasePins()
{
if (m_NativeOverlapped != null)
{
NativeOverlapped* nativeOverlapped = m_NativeOverlapped;
m_NativeOverlapped = null;
Overlapped.Free(nativeOverlapped);
}
}
protected override void Dispose(bool disposing)
{
if (m_NativeOverlapped != null)
{
GlobalLog.Assert(!disposing, "AsyncRequestContext::Dispose()|Must call ReleasePins() before calling Dispose().");
if (!NclUtilities.HasShutdownStarted || disposing)
{
Overlapped.Free(m_NativeOverlapped);
}
}
base.Dispose(disposing);
}
internal NativeOverlapped* NativeOverlapped
{
get
{
return m_NativeOverlapped;
}
}
}
internal unsafe class SyncRequestContext : RequestContextBase
{
private GCHandle m_PinnedHandle;
internal SyncRequestContext(int size)
{
BaseConstruction(Allocate(size));
}
private UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* Allocate(int size)
{
if (m_PinnedHandle.IsAllocated)
{
if (RequestBuffer.Length == size)
{
return RequestBlob;
}
m_PinnedHandle.Free();
}
SetBuffer(size);
if (RequestBuffer == null)
{
return null;
}
m_PinnedHandle = GCHandle.Alloc(RequestBuffer, GCHandleType.Pinned);
return (UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST*) Marshal.UnsafeAddrOfPinnedArrayElement(RequestBuffer, 0);
}
internal void Reset(int size)
{
SetBlob(Allocate(size));
}
protected override void OnReleasePins()
{
if (m_PinnedHandle.IsAllocated)
{
m_PinnedHandle.Free();
}
}
protected override void Dispose(bool disposing)
{
if (m_PinnedHandle.IsAllocated)
{
GlobalLog.Assert(!disposing, "AsyncRequestContext::Dispose()|Must call ReleasePins() before calling Dispose().");
if (!NclUtilities.HasShutdownStarted || disposing)
{
m_PinnedHandle.Free();
}
}
base.Dispose(disposing);
}
}
public sealed unsafe class HttpListener : IDisposable
{
private static readonly Type ChannelBindingStatusType = typeof(UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_CHANNEL_BIND_STATUS);
private static readonly int RequestChannelBindStatusSize =
Marshal.SizeOf(typeof(UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_CHANNEL_BIND_STATUS));
// Win8# 559317 fixed a bug in Http.sys's HttpReceiveClientCertificate method.
// Without this fix IOCP callbacks were not being called although ERROR_IO_PENDING was
// returned from HttpReceiveClientCertificate when using the
// FileCompletionNotificationModes.SkipCompletionPortOnSuccess flag.
// This bug was only hit when the buffer passed into HttpReceiveClientCertificate
// (1500 bytes initially) is tool small for the certificate.
// Due to this bug in downlevel operating systems the FileCompletionNotificationModes.SkipCompletionPortOnSuccess
// flag is only used on Win8 and later.
internal static readonly bool SkipIOCPCallbackOnSuccess = ComNetOS.IsWin8orLater;
// Mitigate potential DOS attacks by limiting the number of unknown headers we accept. Numerous header names
// with hash collisions will cause the server to consume excess CPU. 1000 headers limits CPU time to under
// 0.5 seconds per request. Respond with a 400 Bad Request.
private const int UnknownHeaderLimit = 1000;
private static byte[] s_WwwAuthenticateBytes = new byte[]
{
(byte) 'W', (byte) 'W', (byte) 'W', (byte) '-', (byte) 'A', (byte) 'u', (byte) 't', (byte) 'h',
(byte) 'e', (byte) 'n', (byte) 't', (byte) 'i', (byte) 'c', (byte) 'a', (byte) 't', (byte) 'e'
};
private class AuthenticationSelectorInfo
{
private AuthenticationSchemeSelector m_SelectorDelegate;
private bool m_CanUseAdvancedAuth;
internal AuthenticationSelectorInfo(AuthenticationSchemeSelector selectorDelegate, bool canUseAdvancedAuth)
{
Debug.Assert(selectorDelegate != null);
m_SelectorDelegate = selectorDelegate;
m_CanUseAdvancedAuth = canUseAdvancedAuth;
}
internal AuthenticationSchemeSelector Delegate
{
get
{
return m_SelectorDelegate;
}
}
internal bool AdvancedAuth
{
get
{
return m_CanUseAdvancedAuth;
}
}
}
private AuthenticationSelectorInfo m_AuthenticationDelegate;
private AuthenticationSchemes m_AuthenticationScheme = AuthenticationSchemes.Anonymous;
private SecurityException m_SecurityException;
private string m_Realm;
private CriticalHandle m_RequestQueueHandle;
private bool m_RequestHandleBound;
private volatile State m_State; // m_State is set only within lock blocks, but often read outside locks.
private HttpListenerPrefixCollection m_Prefixes;
private bool m_IgnoreWriteExceptions;
private bool m_UnsafeConnectionNtlmAuthentication;
private ExtendedProtectionSelector m_ExtendedProtectionSelectorDelegate;
private ExtendedProtectionPolicy m_ExtendedProtectionPolicy;
private ServiceNameStore m_DefaultServiceNames;
private HttpServerSessionHandle m_ServerSessionHandle;
private ulong m_UrlGroupId;
private HttpListenerTimeoutManager m_TimeoutManager;
private bool m_V2Initialized;
private Hashtable m_DisconnectResults; // ulong -> DisconnectAsyncResult
private object m_InternalLock;
internal Hashtable m_UriPrefixes = new Hashtable();
public delegate ExtendedProtectionPolicy ExtendedProtectionSelector(HttpListenerRequest request);
public HttpListener()
{
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "HttpListener", "");
if (!UnsafeNclNativeMethods.HttpApi.Supported) {
throw new PlatformNotSupportedException();
}
Debug.Assert(UnsafeNclNativeMethods.HttpApi.ApiVersion ==
UnsafeNclNativeMethods.HttpApi.HTTP_API_VERSION.Version20, "Invalid Http api version");
m_State = State.Stopped;
m_InternalLock = new object();
m_DefaultServiceNames = new ServiceNameStore();
m_TimeoutManager = new HttpListenerTimeoutManager(this);
// default: no CBT checks on any platform (appcompat reasons); applies also to PolicyEnforcement
// config element
m_ExtendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
if (Logging.On) Logging.Exit(Logging.HttpListener, this, "HttpListener", "");
}
internal CriticalHandle RequestQueueHandle {
get {
return m_RequestQueueHandle;
}
}
public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate {
get {
AuthenticationSelectorInfo selector = m_AuthenticationDelegate;
return selector == null ? null : selector.Delegate;
}
set {
CheckDisposed();
try
{
new SecurityPermission(SecurityPermissionFlag.ControlPrincipal).Demand();
m_AuthenticationDelegate = new AuthenticationSelectorInfo(value, true);
}
catch (SecurityException exception)
{
m_SecurityException = exception;
m_AuthenticationDelegate = new AuthenticationSelectorInfo(value, false);
}
}
}
public ExtendedProtectionSelector ExtendedProtectionSelectorDelegate
{
get {
return m_ExtendedProtectionSelectorDelegate;
}
set {
CheckDisposed();
if (value == null) {
throw new ArgumentNullException();
}
if (!AuthenticationManager.OSSupportsExtendedProtection) {
throw new PlatformNotSupportedException(SR.GetString(SR.security_ExtendedProtection_NoOSSupport));
}
m_ExtendedProtectionSelectorDelegate = value;
}
}
public AuthenticationSchemes AuthenticationSchemes {
get {
return m_AuthenticationScheme;
}
set {
CheckDisposed();
// Enabling certain schemes requires special permissions.
if ((value & (AuthenticationSchemes.Digest | AuthenticationSchemes.Negotiate | AuthenticationSchemes.Ntlm)) != 0)
{
new SecurityPermission(SecurityPermissionFlag.ControlPrincipal).Demand();
}
m_AuthenticationScheme = value;
}
}
public ExtendedProtectionPolicy ExtendedProtectionPolicy
{
get {
return m_ExtendedProtectionPolicy;
}
set {
CheckDisposed();
if (value == null)
{
throw new ArgumentNullException("value");
}
if (!AuthenticationManager.OSSupportsExtendedProtection && value.PolicyEnforcement == PolicyEnforcement.Always)
{
throw new PlatformNotSupportedException(SR.GetString(SR.security_ExtendedProtection_NoOSSupport));
}
if (value.CustomChannelBinding != null)
{
throw new ArgumentException(SR.GetString(SR.net_listener_cannot_set_custom_cbt), "CustomChannelBinding");
}
m_ExtendedProtectionPolicy = value;
}
}
public ServiceNameCollection DefaultServiceNames
{
get {
return m_DefaultServiceNames.ServiceNames;
}
}
public string Realm {
get {
return m_Realm;
}
set {
CheckDisposed();
m_Realm = value;
}
}
private void ValidateV2Property() {
// Make sure that calling CheckDisposed and SetupV2Config is an atomic operation. This
// avoids race conditions if the listener is aborted/closed after CheckDisposed(), but
// before SetupV2Config().
lock (m_InternalLock) {
CheckDisposed();
SetupV2Config();
}
}
private void SetUrlGroupProperty(UnsafeNclNativeMethods.HttpApi.HTTP_SERVER_PROPERTY property, IntPtr info, uint infosize) {
uint statusCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS;
GlobalLog.Assert(m_UrlGroupId != 0, "SetUrlGroupProperty called with invalid url group id");
GlobalLog.Assert(info != IntPtr.Zero, "SetUrlGroupProperty called with invalid pointer");
//
// Set the url group property using Http Api.
//
statusCode = UnsafeNclNativeMethods.HttpApi.HttpSetUrlGroupProperty(
m_UrlGroupId, property, info, infosize);
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
HttpListenerException exception = new HttpListenerException((int)statusCode);
if (Logging.On) Logging.Exception(Logging.HttpListener, this, "HttpSetUrlGroupProperty:: Property: " +
property, exception);
throw exception;
}
}
internal void SetServerTimeout(int[] timeouts, uint minSendBytesPerSecond) {
ValidateV2Property(); // CheckDispose and initilize HttpListener in the case of app.config timeouts
UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_LIMIT_INFO timeoutinfo =
new UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_LIMIT_INFO();
timeoutinfo.Flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT;
timeoutinfo.DrainEntityBody =
(ushort)timeouts[(int)UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_TYPE.DrainEntityBody];
timeoutinfo.EntityBody =
(ushort)timeouts[(int)UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_TYPE.EntityBody];
timeoutinfo.RequestQueue =
(ushort)timeouts[(int)UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_TYPE.RequestQueue];
timeoutinfo.IdleConnection =
(ushort)timeouts[(int)UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_TYPE.IdleConnection];
timeoutinfo.HeaderWait =
(ushort)timeouts[(int)UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_TYPE.HeaderWait];
timeoutinfo.MinSendRate = minSendBytesPerSecond;
IntPtr infoptr = new IntPtr(&timeoutinfo);
SetUrlGroupProperty(
UnsafeNclNativeMethods.HttpApi.HTTP_SERVER_PROPERTY.HttpServerTimeoutsProperty,
infoptr, (uint)Marshal.SizeOf(typeof(UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_LIMIT_INFO)));
}
public HttpListenerTimeoutManager TimeoutManager {
get {
ValidateV2Property();
Debug.Assert(m_TimeoutManager != null, "Timeout manager is not assigned");
return m_TimeoutManager;
}
}
public static bool IsSupported {
get {
return UnsafeNclNativeMethods.HttpApi.Supported;
}
}
public bool IsListening {
get {
return m_State==State.Started;
}
}
public bool IgnoreWriteExceptions {
get {
return m_IgnoreWriteExceptions;
}
set {
CheckDisposed();
m_IgnoreWriteExceptions = value;
}
}
public bool UnsafeConnectionNtlmAuthentication {
get {
return m_UnsafeConnectionNtlmAuthentication;
}
set {
CheckDisposed();
if (m_UnsafeConnectionNtlmAuthentication==value) {
return;
}
lock (DisconnectResults.SyncRoot)
{
if (m_UnsafeConnectionNtlmAuthentication == value)
{
return;
}
m_UnsafeConnectionNtlmAuthentication = value;
if (!value)
{
foreach (DisconnectAsyncResult result in DisconnectResults.Values)
{
result.AuthenticatedConnection = null;
}
}
}
}
}
private Hashtable DisconnectResults
{
get
{
if (m_DisconnectResults == null)
{
lock (m_InternalLock)
{
if (m_DisconnectResults == null)
{
m_DisconnectResults = Hashtable.Synchronized(new Hashtable());
}
}
}
return m_DisconnectResults;
}
}
internal void AddPrefix(string uriPrefix)
{
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "AddPrefix", "uriPrefix:" + uriPrefix);
string registeredPrefix = null;
try {
if (uriPrefix==null) {
throw new ArgumentNullException("uriPrefix");
}
(new WebPermission(NetworkAccess.Accept, uriPrefix)).Demand();
CheckDisposed();
GlobalLog.Print("HttpListener#" + ValidationHelper.HashString(this) + "::AddPrefix() uriPrefix:" + uriPrefix);
int i;
if (string.Compare(uriPrefix, 0, "http://", 0, 7, StringComparison.OrdinalIgnoreCase)==0) {
i = 7;
}
else if (string.Compare(uriPrefix, 0, "https://", 0, 8, StringComparison.OrdinalIgnoreCase)==0) {
i = 8;
}
else {
throw new ArgumentException(SR.GetString(SR.net_listener_scheme), "uriPrefix");
}
bool inSquareBrakets = false;
int j = i;
while (j<uriPrefix.Length && uriPrefix[j]!='/' && (uriPrefix[j]!=':' || inSquareBrakets)) {
if (uriPrefix[j]=='[') {
if (inSquareBrakets) {
j = i;
break;
}
inSquareBrakets = true;
}
if (inSquareBrakets && uriPrefix[j]==']') {
inSquareBrakets = false;
}
j++;
}
if (i==j) {
throw new ArgumentException(SR.GetString(SR.net_listener_host), "uriPrefix");
}
if (uriPrefix[uriPrefix.Length-1]!='/') {
throw new ArgumentException(SR.GetString(SR.net_listener_slash), "uriPrefix");
}
registeredPrefix = uriPrefix[j]==':' ? String.Copy(uriPrefix) : uriPrefix.Substring(0, j) + (i==7 ? ":80" : ":443") + uriPrefix.Substring(j);
fixed (char* pChar = registeredPrefix) {
i = 0;
while (pChar[i]!=':') {
pChar[i] = (char)CaseInsensitiveAscii.AsciiToLower[(byte)pChar[i]];
i++;
}
}
GlobalLog.Print("HttpListener#" + ValidationHelper.HashString(this) + "::AddPrefix() mapped uriPrefix:" + uriPrefix + " to registeredPrefix:" + registeredPrefix);
if (m_State==State.Started) {
GlobalLog.Print("HttpListener#" + ValidationHelper.HashString(this) + "::AddPrefix() calling UnsafeNclNativeMethods.HttpApi.HttpAddUrl[ToUrlGroup]");
uint statusCode = InternalAddPrefix(registeredPrefix);
if (statusCode!=UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_ALREADY_EXISTS)
throw new HttpListenerException((int)statusCode, SR.GetString(SR.net_listener_already, registeredPrefix));
else
throw new HttpListenerException((int)statusCode);
}
}
m_UriPrefixes[uriPrefix] = registeredPrefix;
m_DefaultServiceNames.Add(uriPrefix);
} catch (Exception exception) {
if(Logging.On)Logging.Exception(Logging.HttpListener, this, "AddPrefix", exception);
throw;
} finally {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "AddPrefix", "prefix:" + registeredPrefix);
}
}
public HttpListenerPrefixCollection Prefixes {
get {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "Prefixes_get", "");
CheckDisposed();
if (m_Prefixes==null) {
m_Prefixes = new HttpListenerPrefixCollection(this);
}
return m_Prefixes;
}
}
internal bool RemovePrefix(string uriPrefix) {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "RemovePrefix", "uriPrefix:" + uriPrefix);
try {
CheckDisposed();
GlobalLog.Print("HttpListener#" + ValidationHelper.HashString(this) + "::RemovePrefix() uriPrefix:" + uriPrefix);
if (uriPrefix==null) {
throw new ArgumentNullException("uriPrefix");
}
if(!m_UriPrefixes.Contains(uriPrefix)){
return false;
}
if (m_State==State.Started) {
InternalRemovePrefix((string)m_UriPrefixes[uriPrefix]);
}
m_UriPrefixes.Remove(uriPrefix);
m_DefaultServiceNames.Remove(uriPrefix);
} catch (Exception exception) {
if(Logging.On)Logging.Exception(Logging.HttpListener, this, "RemovePrefix", exception);
throw;
} finally {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "RemovePrefix", "uriPrefix:" + uriPrefix);
}
return true;
}
internal void RemoveAll(bool clear) {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "RemoveAll", "");
try {
CheckDisposed();
// go through the uri list and unregister for each one of them
if (m_UriPrefixes.Count>0) {
if (m_State==State.Started) {
foreach (string registeredPrefix in m_UriPrefixes.Values) {
// ignore possible failures
InternalRemovePrefix(registeredPrefix);
}
}
if (clear) {
m_UriPrefixes.Clear();
m_DefaultServiceNames.Clear();
}
}
} finally {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "RemoveAll", "");
}
}
private IntPtr DangerousGetHandle() {
return ((HttpRequestQueueV2Handle)m_RequestQueueHandle).DangerousGetHandle();
}
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
internal void EnsureBoundHandle()
{
if (!m_RequestHandleBound)
{
lock (m_InternalLock)
{
if (!m_RequestHandleBound)
{
ThreadPool.BindHandle(DangerousGetHandle());
m_RequestHandleBound = true;
}
}
}
}
private void SetupV2Config() {
uint statusCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS;
ulong id = 0;
//
// If we have already initialized V2 config, then nothing to do.
//
if (m_V2Initialized) {
return;
}
//
// V2 initialization sequence:
// 1. Create server session
// 2. Create url group
// 3. Create request queue - Done in Start()
// 4. Add urls to url group - Done in Start()
// 5. Attach request queue to url group - Done in Start()
//
try {
statusCode = UnsafeNclNativeMethods.HttpApi.HttpCreateServerSession(
UnsafeNclNativeMethods.HttpApi.Version, &id, 0);
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
throw new HttpListenerException((int)statusCode);
}
GlobalLog.Assert(id != 0, "Invalid id returned by HttpCreateServerSession");
m_ServerSessionHandle = new HttpServerSessionHandle(id);
id = 0;
statusCode = UnsafeNclNativeMethods.HttpApi.HttpCreateUrlGroup(
m_ServerSessionHandle.DangerousGetServerSessionId(), &id, 0);
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
throw new HttpListenerException((int)statusCode);
}
GlobalLog.Assert(id != 0, "Invalid id returned by HttpCreateUrlGroup");
m_UrlGroupId = id;
m_V2Initialized = true;
}
catch (Exception exception) {
//
// If V2 initialization fails, we mark object as unusable.
//
m_State = State.Closed;
//
// If Url group or request queue creation failed, close server session before throwing.
//
if (m_ServerSessionHandle != null) {
m_ServerSessionHandle.Close();
}
if (Logging.On) Logging.Exception(Logging.HttpListener, this, "SetupV2Config", exception);
throw;
}
}
public void Start() {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "Start", "");
// Make sure there are no race conditions between Start/Stop/Abort/Close/Dispose and
// calls to SetupV2Config: Start needs to setup all resources (esp. in V2 where besides
// the request handle, there is also a server session and a Url group. Abort/Stop must
// not interfere while Start is allocating those resources. The lock also makes sure
// all methods changing state can read and change the state in an atomic way.
lock (m_InternalLock) {
try {
CheckDisposed();
if (m_State==State.Started) {
return;
}
// SetupV2Config() is not called in the ctor, because it may throw. This would
// be a regression since in v1 the ctor never threw. Besides, ctors should do
// minimal work according to the framework design guidelines.
SetupV2Config();
CreateRequestQueueHandle();
AttachRequestQueueToUrlGroup();
// All resources are set up correctly. Now add all prefixes.
try {
AddAllPrefixes();
}
catch (HttpListenerException) {
// If an error occured while adding prefixes, free all resources allocated by previous steps.
DetachRequestQueueFromUrlGroup();
ClearDigestCache();
throw;
}
m_State = State.Started;
} catch (Exception exception) {
// Make sure the HttpListener instance can't be used if Start() failed.
m_State = State.Closed;
CloseRequestQueueHandle();
CleanupV2Config();
if (Logging.On) Logging.Exception(Logging.HttpListener, this, "Start", exception);
throw;
} finally {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "Start", "");
}
}
}
private void CleanupV2Config() {
//
// If we never setup V2, just return.
//
if (!m_V2Initialized) {
return;
}
//
// V2 stopping sequence:
// 1. Detach request queue from url group - Done in Stop()/Abort()
// 2. Remove urls from url group - Done in Stop()
// 3. Close request queue - Done in Stop()/Abort()
// 4. Close Url group.
// 5. Close server session.
GlobalLog.Assert(m_UrlGroupId != 0, "HttpCloseUrlGroup called with invalid url group id");
uint statusCode = UnsafeNclNativeMethods.HttpApi.HttpCloseUrlGroup(m_UrlGroupId);
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
if (Logging.On) Logging.PrintError(Logging.HttpListener, this, "CloseV2Config", SR.GetString(SR.net_listener_close_urlgroup_error, statusCode));
}
m_UrlGroupId = 0;
GlobalLog.Assert(m_ServerSessionHandle != null, "ServerSessionHandle is null in CloseV2Config");
GlobalLog.Assert(!m_ServerSessionHandle.IsInvalid, "ServerSessionHandle is invalid in CloseV2Config");
m_ServerSessionHandle.Close();
}
private void AttachRequestQueueToUrlGroup() {
//
// Set the association between request queue and url group. After this, requests for registered urls will
// get delivered to this request queue.
//
UnsafeNclNativeMethods.HttpApi.HTTP_BINDING_INFO info = new UnsafeNclNativeMethods.HttpApi.HTTP_BINDING_INFO();
info.Flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT;
info.RequestQueueHandle = DangerousGetHandle();
IntPtr infoptr = new IntPtr(&info);
SetUrlGroupProperty(UnsafeNclNativeMethods.HttpApi.HTTP_SERVER_PROPERTY.HttpServerBindingProperty,
infoptr, (uint)Marshal.SizeOf(typeof(UnsafeNclNativeMethods.HttpApi.HTTP_BINDING_INFO)));
}
private void DetachRequestQueueFromUrlGroup() {
GlobalLog.Assert(m_UrlGroupId != 0, "DetachRequestQueueFromUrlGroup can't detach using Url group id 0.");
//
// Break the association between request queue and url group. After this, requests for registered urls
// will get 503s.
// Note that this method may be called multiple times (Stop() and then Abort()). This
// is fine since http.sys allows to set HttpServerBindingProperty multiple times for valid
// Url groups.
//
UnsafeNclNativeMethods.HttpApi.HTTP_BINDING_INFO info = new UnsafeNclNativeMethods.HttpApi.HTTP_BINDING_INFO();
info.Flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE;
info.RequestQueueHandle = IntPtr.Zero;
IntPtr infoptr = new IntPtr(&info);
uint statusCode = UnsafeNclNativeMethods.HttpApi.HttpSetUrlGroupProperty(m_UrlGroupId,
UnsafeNclNativeMethods.HttpApi.HTTP_SERVER_PROPERTY.HttpServerBindingProperty,
infoptr, (uint)Marshal.SizeOf(typeof(UnsafeNclNativeMethods.HttpApi.HTTP_BINDING_INFO)));
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
if (Logging.On) Logging.PrintError(Logging.HttpListener, this, "DetachRequestQueueFromUrlGroup", SR.GetString(SR.net_listener_detach_error, statusCode));
}
}
public void Stop() {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "Stop", "");
try {
lock (m_InternalLock) {
CheckDisposed();
if (m_State==State.Stopped) {
return;
}
RemoveAll(false);
DetachRequestQueueFromUrlGroup();
// Even though it would be enough to just detach the request queue in v2, in order to
// keep app compat with earlier versions of the framework, we need to close the request queue.
// This will make sure that pending GetContext() calls will complete and throw an exception. Just
// detaching the url group from the request queue would not cause GetContext() to return.
CloseRequestQueueHandle();
m_State = State.Stopped;
}
ClearDigestCache();
} catch (Exception exception) {
if(Logging.On)Logging.Exception(Logging.HttpListener, this, "Stop", exception);
throw;
} finally {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "Stop", "");
}
}
private unsafe void CreateRequestQueueHandle() {
uint statusCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS;
HttpRequestQueueV2Handle requestQueueHandle = null;
statusCode =
UnsafeNclNativeMethods.SafeNetHandles.HttpCreateRequestQueue(
UnsafeNclNativeMethods.HttpApi.Version, null, null, 0, out requestQueueHandle);
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
throw new HttpListenerException((int)statusCode);
}
// Disabling callbacks when IO operation completes synchronously (returns ErrorCodes.ERROR_SUCCESS)
if (SkipIOCPCallbackOnSuccess &&