/
HttpListenerRequest.cs
1514 lines (1292 loc) · 64.8 KB
/
HttpListenerRequest.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="HttpListenerRequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Permissions;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Security.Principal;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
internal enum ListenerClientCertState {
NotInitialized,
InProgress,
Completed
}
unsafe internal class ListenerClientCertAsyncResult : LazyAsyncResult {
private NativeOverlapped* m_pOverlapped;
private byte[] m_BackingBuffer;
private UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* m_MemoryBlob;
private uint m_Size;
internal NativeOverlapped* NativeOverlapped
{
get
{
return m_pOverlapped;
}
}
internal UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* RequestBlob
{
get
{
return m_MemoryBlob;
}
}
private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(WaitCallback);
internal ListenerClientCertAsyncResult(object asyncObject, object userState, AsyncCallback callback, uint size) : base(asyncObject, userState, callback) {
// we will use this overlapped structure to issue async IO to ul
// the event handle will be put in by the BeginHttpApi2.ERROR_SUCCESS() method
Reset(size);
}
internal void Reset(uint size) {
if (size == m_Size)
{
return;
}
if (m_Size != 0)
{
Overlapped.Free(m_pOverlapped);
}
m_Size = size;
if (size == 0)
{
m_pOverlapped = null;
m_MemoryBlob = null;
m_BackingBuffer = null;
return;
}
m_BackingBuffer = new byte[checked((int) size)];
Overlapped overlapped = new Overlapped();
overlapped.AsyncResult = this;
m_pOverlapped = overlapped.Pack(s_IOCallback, m_BackingBuffer);
m_MemoryBlob = (UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*) Marshal.UnsafeAddrOfPinnedArrayElement(m_BackingBuffer, 0);
}
internal unsafe void IOCompleted(uint errorCode, uint numBytes)
{
IOCompleted(this, errorCode, numBytes);
}
private static unsafe void IOCompleted(ListenerClientCertAsyncResult asyncResult, uint errorCode, uint numBytes)
{
HttpListenerRequest httpListenerRequest = (HttpListenerRequest) asyncResult.AsyncObject;
object result = null;
try {
if (errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA)
{
//There is a bug that has existed in http.sys since w2k3. Bytesreceived will only
//return the size of the inital cert structure. To get the full size,
//we need to add the certificate encoding size as well.
UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob;
asyncResult.Reset(numBytes + pClientCertInfo->CertEncodedSize);
uint bytesReceived = 0;
errorCode =
UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate(
httpListenerRequest.HttpListenerContext.RequestQueueHandle,
httpListenerRequest.m_ConnectionId,
(uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE,
asyncResult.m_MemoryBlob,
asyncResult.m_Size,
&bytesReceived,
asyncResult.m_pOverlapped);
if(errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING ||
(errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && !HttpListener.SkipIOCPCallbackOnSuccess))
{
return;
}
}
if (errorCode!=UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
asyncResult.ErrorCode = (int)errorCode;
result = new HttpListenerException((int)errorCode);
}
else {
UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.m_MemoryBlob;
if (pClientCertInfo!=null) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(httpListenerRequest) + "::ProcessClientCertificate() pClientCertInfo:" + ValidationHelper.ToString((IntPtr)pClientCertInfo)
+ " pClientCertInfo->CertFlags:" + ValidationHelper.ToString(pClientCertInfo->CertFlags)
+ " pClientCertInfo->CertEncodedSize:" + ValidationHelper.ToString(pClientCertInfo->CertEncodedSize)
+ " pClientCertInfo->pCertEncoded:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->pCertEncoded)
+ " pClientCertInfo->Token:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->Token)
+ " pClientCertInfo->CertDeniedByMapper:" + ValidationHelper.ToString(pClientCertInfo->CertDeniedByMapper));
if (pClientCertInfo->pCertEncoded!=null) {
try {
byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize];
Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length);
result = httpListenerRequest.ClientCertificate = new X509Certificate2(certEncoded);
}
catch (CryptographicException exception) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(httpListenerRequest) + "::ProcessClientCertificate() caught CryptographicException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception));
result = exception;
}
catch (SecurityException exception) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(httpListenerRequest) + "::ProcessClientCertificate() caught SecurityException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception));
result = exception;
}
}
httpListenerRequest.SetClientCertificateError((int)pClientCertInfo->CertFlags);
}
}
// complete the async IO and invoke the callback
GlobalLog.Print("ListenerClientCertAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::WaitCallback() calling Complete()");
}
catch (Exception exception)
{
if (NclUtilities.IsFatal(exception)) throw;
result = exception;
}
finally {
if(errorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING){
httpListenerRequest.ClientCertState = ListenerClientCertState.Completed;
}
}
asyncResult.InvokeCallback(result);
}
private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) {
// take the ListenerClientCertAsyncResult object from the state
Overlapped callbackOverlapped = Overlapped.Unpack(nativeOverlapped);
ListenerClientCertAsyncResult asyncResult = (ListenerClientCertAsyncResult) callbackOverlapped.AsyncResult;
GlobalLog.Print("ListenerClientCertAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::WaitCallback() errorCode:[" + errorCode.ToString() + "] numBytes:[" + numBytes.ToString() + "] nativeOverlapped:[" + ((long)nativeOverlapped).ToString() + "]");
IOCompleted(asyncResult, errorCode, numBytes);
}
// Will be called from the base class upon InvokeCallback()
protected override void Cleanup()
{
if (m_pOverlapped != null)
{
m_MemoryBlob = null;
Overlapped.Free(m_pOverlapped);
m_pOverlapped = null;
}
GC.SuppressFinalize(this);
base.Cleanup();
}
~ListenerClientCertAsyncResult()
{
if (m_pOverlapped != null && !NclUtilities.HasShutdownStarted)
{
Overlapped.Free(m_pOverlapped);
m_pOverlapped = null; // Must do this in case application calls GC.ReRegisterForFinalize().
}
}
}
public sealed unsafe class HttpListenerRequest/* BaseHttpRequest, */ {
private Uri m_RequestUri;
private ulong m_RequestId;
internal ulong m_ConnectionId;
private SslStatus m_SslStatus;
private string m_RawUrl;
private string m_CookedUrlHost;
private string m_CookedUrlPath;
private string m_CookedUrlQuery;
private long m_ContentLength;
private Stream m_RequestStream;
private string m_HttpMethod;
private TriState m_KeepAlive;
private Version m_Version;
private WebHeaderCollection m_WebHeaders;
private IPEndPoint m_LocalEndPoint;
private IPEndPoint m_RemoteEndPoint;
private BoundaryType m_BoundaryType;
private ListenerClientCertState m_ClientCertState;
private X509Certificate2 m_ClientCertificate;
private int m_ClientCertificateError;
private RequestContextBase m_MemoryBlob;
private CookieCollection m_Cookies;
private HttpListenerContext m_HttpContext;
private bool m_IsDisposed = false;
internal const uint CertBoblSize = 1500;
private string m_ServiceName;
private object m_Lock = new object();
private List<TokenBinding> m_TokenBindings = null;
private int m_TokenBindingVerifyMessageStatus = 0;
private enum SslStatus : byte
{
Insecure,
NoClientCert,
ClientCert
}
internal HttpListenerRequest(HttpListenerContext httpContext, RequestContextBase memoryBlob)
{
if (Logging.On) Logging.PrintInfo(Logging.HttpListener, this, ".ctor", "httpContext#" + ValidationHelper.HashString(httpContext) + " memoryBlob# " + ValidationHelper.HashString((IntPtr) memoryBlob.RequestBlob));
if(Logging.On)Logging.Associate(Logging.HttpListener, this, httpContext);
m_HttpContext = httpContext;
m_MemoryBlob = memoryBlob;
m_BoundaryType = BoundaryType.None;
// Set up some of these now to avoid refcounting on memory blob later.
m_RequestId = memoryBlob.RequestBlob->RequestId;
m_ConnectionId = memoryBlob.RequestBlob->ConnectionId;
m_SslStatus = memoryBlob.RequestBlob->pSslInfo == null ? SslStatus.Insecure :
memoryBlob.RequestBlob->pSslInfo->SslClientCertNegotiated == 0 ? SslStatus.NoClientCert :
SslStatus.ClientCert;
if (memoryBlob.RequestBlob->pRawUrl != null && memoryBlob.RequestBlob->RawUrlLength > 0) {
m_RawUrl = Marshal.PtrToStringAnsi((IntPtr) memoryBlob.RequestBlob->pRawUrl, memoryBlob.RequestBlob->RawUrlLength);
}
UnsafeNclNativeMethods.HttpApi.HTTP_COOKED_URL cookedUrl = memoryBlob.RequestBlob->CookedUrl;
if (cookedUrl.pHost != null && cookedUrl.HostLength > 0) {
m_CookedUrlHost = Marshal.PtrToStringUni((IntPtr)cookedUrl.pHost, cookedUrl.HostLength / 2);
}
if (cookedUrl.pAbsPath != null && cookedUrl.AbsPathLength > 0) {
m_CookedUrlPath = Marshal.PtrToStringUni((IntPtr)cookedUrl.pAbsPath, cookedUrl.AbsPathLength / 2);
}
if (cookedUrl.pQueryString != null && cookedUrl.QueryStringLength > 0) {
m_CookedUrlQuery = Marshal.PtrToStringUni((IntPtr)cookedUrl.pQueryString, cookedUrl.QueryStringLength / 2);
}
m_Version = new Version(memoryBlob.RequestBlob->Version.MajorVersion, memoryBlob.RequestBlob->Version.MinorVersion);
m_ClientCertState = ListenerClientCertState.NotInitialized;
m_KeepAlive = TriState.Unspecified;
GlobalLog.Print("HttpListenerContext#" + ValidationHelper.HashString(this) + "::.ctor() RequestId:" + RequestId + " ConnectionId:" + m_ConnectionId + " RawConnectionId:" + memoryBlob.RequestBlob->RawConnectionId + " UrlContext:" + memoryBlob.RequestBlob->UrlContext + " RawUrl:" + m_RawUrl + " Version:" + m_Version.ToString() + " Secure:" + m_SslStatus.ToString());
if(Logging.On)Logging.PrintInfo(Logging.HttpListener, this, ".ctor", "httpContext#"+ ValidationHelper.HashString(httpContext)+ " RequestUri:" + ValidationHelper.ToString(RequestUri) + " Content-Length:" + ValidationHelper.ToString(ContentLength64) + " HTTP Method:" + ValidationHelper.ToString(HttpMethod));
// Log headers
if(Logging.On) {
StringBuilder sb = new StringBuilder("HttpListenerRequest Headers:\n");
for (int i=0; i<Headers.Count; i++) {
sb.Append("\t");
sb.Append(Headers.GetKey(i));
sb.Append(" : ");
sb.Append(Headers.Get(i));
sb.Append("\n");
}
Logging.PrintInfo(Logging.HttpListener, this, ".ctor", sb.ToString());
}
}
internal HttpListenerContext HttpListenerContext {
get {
return m_HttpContext;
}
}
// Note: RequestBuffer may get moved in memory. If you dereference a pointer from inside the RequestBuffer,
// you must use 'OriginalBlobAddress' below to adjust the location of the pointer to match the location of
// RequestBuffer.
//
internal byte[] RequestBuffer
{
get
{
CheckDisposed();
return m_MemoryBlob.RequestBuffer;
}
}
internal IntPtr OriginalBlobAddress
{
get
{
CheckDisposed();
return m_MemoryBlob.OriginalBlobAddress;
}
}
// Use this to save the blob from dispose if this object was never used (never given to a user) and is about to be
// disposed.
internal void DetachBlob(RequestContextBase memoryBlob)
{
if (memoryBlob != null && (object) memoryBlob == (object) m_MemoryBlob)
{
m_MemoryBlob = null;
}
}
// Finalizes ownership of the memory blob. DetachBlob can't be called after this.
internal void ReleasePins()
{
m_MemoryBlob.ReleasePins();
}
public Guid RequestTraceIdentifier {
get {
Guid guid = new Guid();
*(1+ (ulong *) &guid) = RequestId;
return guid;
}
}
internal ulong RequestId {
get {
return m_RequestId;
}
}
public /* override */ string[] AcceptTypes {
get {
return Helpers.ParseMultivalueHeader(GetKnownHeader(HttpRequestHeader.Accept));
}
}
public /* override */ Encoding ContentEncoding {
get {
if (UserAgent!=null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP")) {
string postDataCharset = Headers["x-up-devcap-post-charset"];
if (postDataCharset!=null && postDataCharset.Length>0) {
try {
return Encoding.GetEncoding(postDataCharset);
}
catch (ArgumentException) {
}
}
}
if (HasEntityBody) {
if (ContentType!=null) {
string charSet = Helpers.GetAttributeFromHeader(ContentType, "charset");
if (charSet!=null) {
try {
return Encoding.GetEncoding(charSet);
}
catch (ArgumentException) {
}
}
}
}
return Encoding.Default;
}
}
public /* override */ long ContentLength64 {
get {
if (m_BoundaryType==BoundaryType.None) {
if (HttpWebRequest.ChunkedHeader.Equals(GetKnownHeader(HttpRequestHeader.TransferEncoding),
StringComparison.OrdinalIgnoreCase)) {
m_BoundaryType = BoundaryType.Chunked;
m_ContentLength = -1;
}
else {
m_ContentLength = 0;
m_BoundaryType = BoundaryType.ContentLength;
string length = GetKnownHeader(HttpRequestHeader.ContentLength);
if (length!=null) {
bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out m_ContentLength);
if (!success) {
m_ContentLength = 0;
m_BoundaryType = BoundaryType.Invalid;
}
}
}
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ContentLength_get() returning m_ContentLength:" + m_ContentLength + " m_BoundaryType:" + m_BoundaryType);
return m_ContentLength;
}
}
public /* override */ string ContentType {
get {
return GetKnownHeader(HttpRequestHeader.ContentType);
}
}
public /* override */ NameValueCollection Headers {
get {
if (m_WebHeaders==null) {
m_WebHeaders = UnsafeNclNativeMethods.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress);
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::Headers_get() returning#" + ValidationHelper.HashString(m_WebHeaders));
return m_WebHeaders;
}
}
public /* override */ string HttpMethod {
get {
if (m_HttpMethod==null) {
m_HttpMethod = UnsafeNclNativeMethods.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress);
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::HttpMethod_get() returning m_HttpMethod:" + ValidationHelper.ToString(m_HttpMethod));
return m_HttpMethod;
}
}
public /* override */ Stream InputStream {
get {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "InputStream_get", "");
if (m_RequestStream==null) {
m_RequestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null;
}
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "InputStream_get", "");
return m_RequestStream;
}
}
// Requires ControlPrincipal permission if the request was authenticated with Negotiate, NTLM, or Digest.
public /* override */ bool IsAuthenticated {
get {
IPrincipal user = HttpListenerContext.User;
return user != null && user.Identity != null && user.Identity.IsAuthenticated;
}
}
public /* override */ bool IsLocal {
get {
return LocalEndPoint.Address.Equals(RemoteEndPoint.Address);
}
}
public /* override */ bool IsSecureConnection {
get {
return m_SslStatus != SslStatus.Insecure;
}
}
public bool IsWebSocketRequest
{
get
{
if (!WebSocketProtocolComponent.IsSupported)
{
return false;
}
bool foundConnectionUpgradeHeader = false;
if (string.IsNullOrEmpty(this.Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(this.Headers[HttpKnownHeaderNames.Upgrade]))
{
return false;
}
foreach (string connection in this.Headers.GetValues(HttpKnownHeaderNames.Connection))
{
if (string.Compare(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase) == 0)
{
foundConnectionUpgradeHeader = true;
break;
}
}
if (!foundConnectionUpgradeHeader)
{
return false;
}
foreach (string upgrade in this.Headers.GetValues(HttpKnownHeaderNames.Upgrade))
{
if (string.Compare(upgrade, WebSocketHelpers.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
}
return false;
}
}
public /* override */ NameValueCollection QueryString {
get {
NameValueCollection queryString = new NameValueCollection();
Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding);
return queryString;
}
}
public /* override */ string RawUrl {
get {
return m_RawUrl;
}
}
public string ServiceName
{
get { return m_ServiceName; }
internal set { m_ServiceName = value; }
}
public /* override */ Uri Url {
get {
return RequestUri;
}
}
public /* override */ Uri UrlReferrer {
get {
string referrer = GetKnownHeader(HttpRequestHeader.Referer);
if (referrer==null) {
return null;
}
Uri urlReferrer;
bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out urlReferrer);
return success ? urlReferrer : null;
}
}
public /* override */ string UserAgent {
get {
return GetKnownHeader(HttpRequestHeader.UserAgent);
}
}
public /* override */ string UserHostAddress {
get {
return LocalEndPoint.ToString();
}
}
public /* override */ string UserHostName {
get {
return GetKnownHeader(HttpRequestHeader.Host);
}
}
public /* override */ string[] UserLanguages {
get {
return Helpers.ParseMultivalueHeader(GetKnownHeader(HttpRequestHeader.AcceptLanguage));
}
}
public int ClientCertificateError {
get {
if (m_ClientCertState == ListenerClientCertState.NotInitialized)
throw new InvalidOperationException(SR.GetString(SR.net_listener_mustcall, "GetClientCertificate()/BeginGetClientCertificate()"));
else if (m_ClientCertState == ListenerClientCertState.InProgress)
throw new InvalidOperationException(SR.GetString(SR.net_listener_mustcompletecall, "GetClientCertificate()/BeginGetClientCertificate()"));
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ClientCertificateError_get() returning ClientCertificateError:" + ValidationHelper.ToString(m_ClientCertificateError));
return m_ClientCertificateError;
}
}
internal X509Certificate2 ClientCertificate {
set {
m_ClientCertificate = value;
}
}
internal ListenerClientCertState ClientCertState {
set {
m_ClientCertState = value;
}
}
internal void SetClientCertificateError(int clientCertificateError)
{
m_ClientCertificateError = clientCertificateError;
}
public X509Certificate2 GetClientCertificate() {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "GetClientCertificate", "");
try {
ProcessClientCertificate();
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::GetClientCertificate() returning m_ClientCertificate:" + ValidationHelper.ToString(m_ClientCertificate));
} finally {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "GetClientCertificate", ValidationHelper.ToString(m_ClientCertificate));
}
return m_ClientCertificate;
}
public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state) {
if(Logging.On)Logging.PrintInfo(Logging.HttpListener, this, "BeginGetClientCertificate", "");
return AsyncProcessClientCertificate(requestCallback, state);
}
public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "EndGetClientCertificate", "");
X509Certificate2 clientCertificate = null;
try {
if (asyncResult==null) {
throw new ArgumentNullException("asyncResult");
}
ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult;
if (clientCertAsyncResult==null || clientCertAsyncResult.AsyncObject!=this) {
throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
}
if (clientCertAsyncResult.EndCalled) {
throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndGetClientCertificate"));
}
clientCertAsyncResult.EndCalled = true;
clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2;
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::EndGetClientCertificate() returning m_ClientCertificate:" + ValidationHelper.ToString(m_ClientCertificate));
} finally {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "EndGetClientCertificate", ValidationHelper.HashString(clientCertificate));
}
return clientCertificate;
}
//************* Task-based async public methods *************************
[HostProtection(ExternalThreading = true)]
public Task<X509Certificate2> GetClientCertificateAsync()
{
return Task<X509Certificate2>.Factory.FromAsync(BeginGetClientCertificate, EndGetClientCertificate, null);
}
public TransportContext TransportContext
{
get
{
return new HttpListenerRequestContext(this);
}
}
private CookieCollection ParseCookies(Uri uri, string setCookieHeader) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ParseCookies() uri:" + uri + " setCookieHeader:" + setCookieHeader);
CookieCollection cookies = new CookieCollection();
CookieParser parser = new CookieParser(setCookieHeader);
for (;;) {
Cookie cookie = parser.GetServer();
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ParseCookies() CookieParser returned cookie:" + ValidationHelper.ToString(cookie));
if (cookie==null) {
// EOF, done.
break;
}
if (cookie.Name.Length==0) {
continue;
}
cookies.InternalAdd(cookie, true);
}
return cookies;
}
public CookieCollection Cookies {
get {
if (m_Cookies==null) {
string cookieString = GetKnownHeader(HttpRequestHeader.Cookie);
if (cookieString!=null && cookieString.Length>0) {
m_Cookies = ParseCookies(RequestUri, cookieString);
}
if (m_Cookies==null) {
m_Cookies = new CookieCollection();
}
if (HttpListenerContext.PromoteCookiesToRfc2965) {
for (int index=0; index<m_Cookies.Count; index++) {
if (m_Cookies[index].Variant==CookieVariant.Rfc2109) {
m_Cookies[index].Variant = CookieVariant.Rfc2965;
}
}
}
}
return m_Cookies;
}
}
public Version ProtocolVersion {
get {
return m_Version;
}
}
public /* override */ bool HasEntityBody {
get {
// accessing the ContentLength property delay creates m_BoundaryType
return (ContentLength64 > 0 && m_BoundaryType == BoundaryType.ContentLength) ||
m_BoundaryType == BoundaryType.Chunked || m_BoundaryType == BoundaryType.Multipart;
}
}
public /* override */ bool KeepAlive
{
get
{
if (m_KeepAlive == TriState.Unspecified)
{
string header = Headers[HttpKnownHeaderNames.ProxyConnection];
if (string.IsNullOrEmpty(header))
{
header = GetKnownHeader(HttpRequestHeader.Connection);
}
if (string.IsNullOrEmpty(header))
{
if (ProtocolVersion >= HttpVersion.Version11)
{
m_KeepAlive = TriState.True;
}
else
{
header = GetKnownHeader(HttpRequestHeader.KeepAlive);
m_KeepAlive = string.IsNullOrEmpty(header) ? TriState.False : TriState.True;
}
}
else
{
header = header.ToLower(CultureInfo.InvariantCulture);
m_KeepAlive = header.IndexOf("close") < 0 || header.IndexOf("keep-alive") >= 0 ? TriState.True : TriState.False;
}
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::KeepAlive_get() returning:" + m_KeepAlive);
return m_KeepAlive == TriState.True;
}
}
public /* override */ IPEndPoint RemoteEndPoint {
get {
if (m_RemoteEndPoint==null) {
m_RemoteEndPoint = UnsafeNclNativeMethods.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress);
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::RemoteEndPoint_get() returning:" + m_RemoteEndPoint);
return m_RemoteEndPoint;
}
}
public /* override */ IPEndPoint LocalEndPoint {
get {
if (m_LocalEndPoint==null) {
m_LocalEndPoint = UnsafeNclNativeMethods.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress);
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::LocalEndPoint_get() returning:" + m_LocalEndPoint);
return m_LocalEndPoint;
}
}
//should only be called from httplistenercontext
internal void Close() {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "Close", "");
RequestContextBase memoryBlob = m_MemoryBlob;
if (memoryBlob != null)
{
memoryBlob.Close();
m_MemoryBlob = null;
}
m_IsDisposed = true;
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "Close", "");
}
private ListenerClientCertAsyncResult AsyncProcessClientCertificate(AsyncCallback requestCallback, object state) {
if (m_ClientCertState == ListenerClientCertState.InProgress)
throw new InvalidOperationException(SR.GetString(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()"));
m_ClientCertState = ListenerClientCertState.InProgress;
HttpListenerContext.EnsureBoundHandle();
ListenerClientCertAsyncResult asyncResult = null;
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So intially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE
if (m_SslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
asyncResult = new ListenerClientCertAsyncResult(this, state, requestCallback, size);
try {
while (true)
{
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() calling UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
m_ConnectionId,
(uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE,
asyncResult.RequestBlob,
size,
&bytesReceived,
asyncResult.NativeOverlapped);
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() call to UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA)
{
UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob;
size = bytesReceived + pClientCertInfo->CertEncodedSize;
asyncResult.Reset(size);
continue;
}
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING) {
// someother bad error, possible(?) return values are:
// ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED
// Also ERROR_BAD_DATA if we got it twice or it reported smaller size buffer required.
throw new HttpListenerException((int)statusCode);
}
if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
asyncResult.IOCompleted(statusCode, bytesReceived);
}
break;
}
}
catch {
if (asyncResult!=null) {
asyncResult.InternalCleanup();
}
throw;
}
} else {
asyncResult = new ListenerClientCertAsyncResult(this, state, requestCallback, 0);
asyncResult.InvokeCallback();
}
return asyncResult;
}
private void ProcessClientCertificate() {
if (m_ClientCertState == ListenerClientCertState.InProgress)
throw new InvalidOperationException(SR.GetString(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()"));
m_ClientCertState = ListenerClientCertState.InProgress;
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate()");
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So intially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE
if (m_SslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
while (true)
{
byte[] clientCertInfoBlob = new byte[checked((int) size)];
fixed (byte* pClientCertInfoBlob = clientCertInfoBlob)
{
UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = (UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*) pClientCertInfoBlob;
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() calling UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
m_ConnectionId,
(uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE,
pClientCertInfo,
size,
&bytesReceived,
null);
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() call to UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA) {
size = bytesReceived + pClientCertInfo->CertEncodedSize;
continue;
}
else if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
if (pClientCertInfo!=null) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() pClientCertInfo:" + ValidationHelper.ToString((IntPtr)pClientCertInfo)
+ " pClientCertInfo->CertFlags:" + ValidationHelper.ToString(pClientCertInfo->CertFlags)
+ " pClientCertInfo->CertEncodedSize:" + ValidationHelper.ToString(pClientCertInfo->CertEncodedSize)
+ " pClientCertInfo->pCertEncoded:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->pCertEncoded)
+ " pClientCertInfo->Token:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->Token)
+ " pClientCertInfo->CertDeniedByMapper:" + ValidationHelper.ToString(pClientCertInfo->CertDeniedByMapper));
if (pClientCertInfo->pCertEncoded!=null) {
try {
byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize];
Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length);
m_ClientCertificate = new X509Certificate2(certEncoded);
}
catch (CryptographicException exception) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() caught CryptographicException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception));
}
catch (SecurityException exception) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() caught SecurityException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception));
}
}
m_ClientCertificateError = (int)pClientCertInfo->CertFlags;
}
}
else {
GlobalLog.Assert(statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_NOT_FOUND, "HttpListenerRequest#{0}::ProcessClientCertificate()|Call to UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate() failed with statusCode {1}.", ValidationHelper.HashString(this), statusCode);
}
}
break;
}
}
m_ClientCertState = ListenerClientCertState.Completed;
}
private string RequestScheme {
get {
return IsSecureConnection ? "https" : "http";
}
}
private Uri RequestUri {
get {
if (m_RequestUri == null) {
m_RequestUri = HttpListenerRequestUriBuilder.GetRequestUri(
m_RawUrl, RequestScheme, m_CookedUrlHost, m_CookedUrlPath, m_CookedUrlQuery);
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::RequestUri_get() returning m_RequestUri:" + ValidationHelper.ToString(m_RequestUri));
return m_RequestUri;
}
}
/*