Terraria v1.4.4.9
Terraria source code documentation
Loading...
Searching...
No Matches
HttpListener.cs
Go to the documentation of this file.
10using System.Text;
14
15namespace System.Net;
16
17public sealed class HttpListener : IDisposable
18{
20
21 private enum State
22 {
23 Stopped,
24 Started,
25 Closed
26 }
27
28 private sealed class DisconnectAsyncResult : IAsyncResult
29 {
30 private unsafe static readonly IOCompletionCallback s_IOCallback = WaitCallback;
31
32 private readonly ulong _connectionId;
33
35
36 private unsafe readonly NativeOverlapped* _nativeOverlapped;
37
38 private int _ownershipState;
39
41
43
45
46 public object AsyncState
47 {
48 get
49 {
51 }
52 }
53
61
69
70 public bool IsCompleted
71 {
72 get
73 {
75 }
76 }
77
79 {
80 get
81 {
83 }
84 set
85 {
87 }
88 }
89
91 {
92 get
93 {
94 return _session;
95 }
96 set
97 {
99 }
100 }
101
103 {
104 if (System.Net.NetEventSource.Log.IsEnabled())
105 {
106 System.Net.NetEventSource.Info(this, $"HttpListener: {session.Listener}, ConnectionId: {connectionId}", ".ctor");
107 }
108 _ownershipState = 1;
111 _nativeOverlapped = session.RequestQueueBoundHandle.AllocateNativeOverlapped(s_IOCallback, this, null);
112 if (System.Net.NetEventSource.Log.IsEnabled())
113 {
114 System.Net.NetEventSource.Info($"DisconnectAsyncResult: ThreadPoolBoundHandle.AllocateNativeOverlapped({session.RequestQueueBoundHandle}) -> {_nativeOverlapped->GetHashCode()}", null, ".ctor");
115 }
116 }
117
119 {
120 SpinWait spinWait = default(SpinWait);
121 int num;
122 while ((num = Interlocked.CompareExchange(ref _ownershipState, 1, 0)) == 2)
123 {
124 spinWait.SpinOnce();
125 }
126 return num < 2;
127 }
128
130 {
132 {
134 }
135 }
136
141
143 {
144 if (System.Net.NetEventSource.Log.IsEnabled())
145 {
146 System.Net.NetEventSource.Info(null, "_connectionId:" + asyncResult._connectionId, "IOCompleted");
147 }
148 asyncResult._listenerSession.RequestQueueBoundHandle.FreeNativeOverlapped(nativeOverlapped);
149 if (Interlocked.Exchange(ref asyncResult._ownershipState, 2) == 0)
150 {
151 asyncResult.HandleDisconnect();
152 }
153 }
154
155 private unsafe static void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
156 {
157 if (System.Net.NetEventSource.Log.IsEnabled())
158 {
159 System.Net.NetEventSource.Info(null, $"errorCode: {errorCode}, numBytes: {numBytes}, nativeOverlapped: {(IntPtr)nativeOverlapped:x}", "WaitCallback");
160 }
163 }
164
165 private void HandleDisconnect()
166 {
168 if (System.Net.NetEventSource.Log.IsEnabled())
169 {
170 System.Net.NetEventSource.Info(this, $"DisconnectResults {listener.DisconnectResults} removing for _connectionId: {_connectionId}", "HandleDisconnect");
171 }
173 if (_session != null)
174 {
175 _session.CloseContext();
176 }
177 IDisposable disposable = ((_authenticatedConnection == null) ? null : (_authenticatedConnection.Identity as IDisposable));
178 if (disposable != null && _authenticatedConnection.Identity.AuthenticationType == "NTLM" && listener.UnsafeConnectionNtlmAuthentication)
179 {
180 disposable.Dispose();
181 }
183 }
184 }
185
186 private readonly object _internalLock;
187
188 private volatile State _state;
189
191
193
195
197
199
201
202 private AuthenticationSchemeSelector _authenticationDelegate;
203
205
206 private ExtendedProtectionSelector _extendedProtectionSelectorDelegate;
207
208 private string _realm;
209
210 internal static readonly bool SkipIOCPCallbackOnSuccess = Environment.OSVersion.Version >= new Version(6, 2);
211
212 private static readonly byte[] s_wwwAuthenticateBytes = new byte[16]
213 {
214 87, 87, 87, 45, 65, 117, 116, 104, 101, 110,
215 116, 105, 99, 97, 116, 101
216 };
217
219
221
223
224 private ulong _urlGroupId;
225
226 private bool _V2Initialized;
227
229
231
232 public AuthenticationSchemeSelector? AuthenticationSchemeSelectorDelegate
233 {
234 get
235 {
237 }
238 set
239 {
242 }
243 }
244
245 public ExtendedProtectionSelector? ExtendedProtectionSelectorDelegate
246 {
247 get
248 {
250 }
252 set
253 {
255 if (value == null)
256 {
257 throw new ArgumentNullException("value");
258 }
260 }
261 }
262
264 {
265 get
266 {
268 }
269 set
270 {
273 }
274 }
275
277 {
278 get
279 {
281 }
282 set
283 {
285 if (value == null)
286 {
287 throw new ArgumentNullException("value");
288 }
289 if (value.CustomChannelBinding != null)
290 {
292 }
294 }
295 }
296
298
300 {
301 get
302 {
304 return _prefixes;
305 }
306 }
307
308 public string? Realm
309 {
310 get
311 {
312 return _realm;
313 }
314 set
315 {
317 _realm = value;
318 }
319 }
320
321 public bool IsListening => _state == State.Started;
322
324 {
325 get
326 {
328 }
329 set
330 {
333 }
334 }
335
336 public static bool IsSupported => global::Interop.HttpApi.s_supported;
337
339 {
340 get
341 {
343 }
344 set
345 {
348 {
349 return;
350 }
352 {
354 {
355 return;
356 }
358 if (value)
359 {
360 return;
361 }
363 {
364 value2.AuthenticatedConnection = null;
365 }
366 }
367 }
368 }
369
371
373 {
374 get
375 {
377 return _timeoutManager;
378 }
379 }
380
390
391 internal void AddPrefix(string uriPrefix)
392 {
393 string text = null;
394 try
395 {
396 if (uriPrefix == null)
397 {
398 throw new ArgumentNullException("uriPrefix");
399 }
401 int num;
402 if (string.Compare(uriPrefix, 0, "http://", 0, 7, StringComparison.OrdinalIgnoreCase) == 0)
403 {
404 num = 7;
405 }
406 else
407 {
408 if (string.Compare(uriPrefix, 0, "https://", 0, 8, StringComparison.OrdinalIgnoreCase) != 0)
409 {
410 throw new ArgumentException(System.SR.net_listener_scheme, "uriPrefix");
411 }
412 num = 8;
413 }
414 bool flag = false;
415 int i;
416 for (i = num; i < uriPrefix.Length && uriPrefix[i] != '/' && (uriPrefix[i] != ':' || flag); i++)
417 {
418 if (uriPrefix[i] == '[')
419 {
420 if (flag)
421 {
422 i = num;
423 break;
424 }
425 flag = true;
426 }
427 if (flag && uriPrefix[i] == ']')
428 {
429 flag = false;
430 }
431 }
432 if (num == i)
433 {
434 throw new ArgumentException(System.SR.net_listener_host, "uriPrefix");
435 }
436 if (uriPrefix[uriPrefix.Length - 1] != '/')
437 {
438 throw new ArgumentException(System.SR.net_listener_slash, "uriPrefix");
439 }
441 if (uriPrefix[i] == ':')
442 {
443 stringBuilder.Append(uriPrefix);
444 }
445 else
446 {
447 stringBuilder.Append(uriPrefix, 0, i);
448 stringBuilder.Append((num == 7) ? ":80" : ":443");
449 stringBuilder.Append(uriPrefix, i, uriPrefix.Length - i);
450 }
451 for (num = 0; stringBuilder[num] != ':'; num++)
452 {
454 }
455 text = stringBuilder.ToString();
456 if (System.Net.NetEventSource.Log.IsEnabled())
457 {
458 System.Net.NetEventSource.Info(this, $"mapped uriPrefix: {uriPrefix} to registeredPrefix: {text}", "AddPrefix");
459 }
460 if (_state == State.Started)
461 {
463 }
466 }
467 catch (Exception message)
468 {
469 if (System.Net.NetEventSource.Log.IsEnabled())
470 {
471 System.Net.NetEventSource.Error(this, message, "AddPrefix");
472 }
473 throw;
474 }
475 }
476
477 internal bool ContainsPrefix(string uriPrefix)
478 {
480 }
481
482 internal bool RemovePrefix(string uriPrefix)
483 {
484 try
485 {
487 if (System.Net.NetEventSource.Log.IsEnabled())
488 {
489 System.Net.NetEventSource.Info(this, $"uriPrefix: {uriPrefix}", "RemovePrefix");
490 }
491 if (uriPrefix == null)
492 {
493 throw new ArgumentNullException("uriPrefix");
494 }
496 {
497 return false;
498 }
499 if (_state == State.Started)
500 {
502 }
505 }
506 catch (Exception message)
507 {
508 if (System.Net.NetEventSource.Log.IsEnabled())
509 {
510 System.Net.NetEventSource.Error(this, message, "RemovePrefix");
511 }
512 throw;
513 }
514 return true;
515 }
516
517 internal void RemoveAll(bool clear)
518 {
520 if (_uriPrefixes.Count <= 0)
521 {
522 return;
523 }
524 if (_state == State.Started)
525 {
526 foreach (string value in _uriPrefixes.Values)
527 {
529 }
530 }
531 if (clear)
532 {
535 }
536 }
537
539 {
540 return Task.Factory.FromAsync((AsyncCallback callback, object state) => ((HttpListener)state).BeginGetContext(callback, state), (IAsyncResult iar) => ((HttpListener)iar.AsyncState).EndGetContext(iar), this);
541 }
542
543 public void Close()
544 {
545 try
546 {
547 if (System.Net.NetEventSource.Log.IsEnabled())
548 {
549 System.Net.NetEventSource.Info("HttpListenerRequest::Close()", null, "Close");
550 }
551 ((IDisposable)this).Dispose();
552 }
553 catch (Exception ex)
554 {
555 if (System.Net.NetEventSource.Log.IsEnabled())
556 {
557 System.Net.NetEventSource.Error(this, $"Close {ex}", "Close");
558 }
559 throw;
560 }
561 }
562
563 internal void CheckDisposed()
564 {
565 if (_state == State.Closed)
566 {
567 throw new ObjectDisposedException(GetType().FullName);
568 }
569 }
570
572 {
573 Dispose();
574 }
575
576 private void ValidateV2Property()
577 {
579 {
582 }
583 }
584
585 private void SetUrlGroupProperty(global::Interop.HttpApi.HTTP_SERVER_PROPERTY property, IntPtr info, uint infosize)
586 {
587 uint num = 0u;
588 num = global::Interop.HttpApi.HttpSetUrlGroupProperty(_urlGroupId, property, info, infosize);
589 if (num != 0)
590 {
592 if (System.Net.NetEventSource.Log.IsEnabled())
593 {
594 System.Net.NetEventSource.Error(this, $"HttpSetUrlGroupProperty:: Property: {property} {ex}", "SetUrlGroupProperty");
595 }
596 throw ex;
597 }
598 }
599
600 internal unsafe void SetServerTimeout(int[] timeouts, uint minSendBytesPerSecond)
601 {
603 global::Interop.HttpApi.HTTP_TIMEOUT_LIMIT_INFO hTTP_TIMEOUT_LIMIT_INFO = default(global::Interop.HttpApi.HTTP_TIMEOUT_LIMIT_INFO);
604 hTTP_TIMEOUT_LIMIT_INFO.Flags = global::Interop.HttpApi.HTTP_FLAGS.HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY;
605 hTTP_TIMEOUT_LIMIT_INFO.DrainEntityBody = (ushort)timeouts[1];
606 hTTP_TIMEOUT_LIMIT_INFO.EntityBody = (ushort)timeouts[0];
607 hTTP_TIMEOUT_LIMIT_INFO.RequestQueue = (ushort)timeouts[2];
608 hTTP_TIMEOUT_LIMIT_INFO.IdleConnection = (ushort)timeouts[3];
609 hTTP_TIMEOUT_LIMIT_INFO.HeaderWait = (ushort)timeouts[4];
610 hTTP_TIMEOUT_LIMIT_INFO.MinSendRate = minSendBytesPerSecond;
612 SetUrlGroupProperty(global::Interop.HttpApi.HTTP_SERVER_PROPERTY.HttpServerTimeoutsProperty, info, (uint)Marshal.SizeOf(typeof(global::Interop.HttpApi.HTTP_TIMEOUT_LIMIT_INFO)));
613 }
614
615 private unsafe void SetupV2Config()
616 {
617 uint num = 0u;
618 ulong num2 = 0uL;
619 if (_V2Initialized)
620 {
621 return;
622 }
623 try
624 {
625 num = global::Interop.HttpApi.HttpCreateServerSession(global::Interop.HttpApi.s_version, &num2, 0u);
626 if (num != 0)
627 {
628 throw new HttpListenerException((int)num);
629 }
631 num2 = 0uL;
632 num = global::Interop.HttpApi.HttpCreateUrlGroup(_serverSessionHandle.DangerousGetServerSessionId(), &num2, 0u);
633 if (num != 0)
634 {
635 throw new HttpListenerException((int)num);
636 }
638 _V2Initialized = true;
639 }
640 catch (Exception ex)
641 {
642 _state = State.Closed;
644 if (System.Net.NetEventSource.Log.IsEnabled())
645 {
646 System.Net.NetEventSource.Error(this, $"SetupV2Config {ex}", "SetupV2Config");
647 }
648 throw;
649 }
650 }
651
652 public void Start()
653 {
655 {
656 try
657 {
659 if (_state != State.Started)
660 {
664 try
665 {
667 }
669 {
671 throw;
672 }
673 _state = State.Started;
674 }
675 }
676 catch (Exception ex2)
677 {
678 _state = State.Closed;
681 if (System.Net.NetEventSource.Log.IsEnabled())
682 {
683 System.Net.NetEventSource.Error(this, $"Start {ex2}", "Start");
684 }
685 throw;
686 }
687 }
688 }
689
690 private void CleanupV2Config()
691 {
692 if (_V2Initialized)
693 {
694 uint num = global::Interop.HttpApi.HttpCloseUrlGroup(_urlGroupId);
695 if (num != 0 && System.Net.NetEventSource.Log.IsEnabled())
696 {
697 System.Net.NetEventSource.Error(this, $"CloseV2Config {System.SR.Format(System.SR.net_listener_close_urlgroup_error, num)}", "CleanupV2Config");
698 }
699 _urlGroupId = 0uL;
701 }
702 }
703
704 private unsafe void AttachRequestQueueToUrlGroup()
705 {
706 global::Interop.HttpApi.HTTP_BINDING_INFO hTTP_BINDING_INFO = default(global::Interop.HttpApi.HTTP_BINDING_INFO);
707 hTTP_BINDING_INFO.Flags = global::Interop.HttpApi.HTTP_FLAGS.HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY;
708 hTTP_BINDING_INFO.RequestQueueHandle = _currentSession.RequestQueueHandle.DangerousGetHandle();
710 SetUrlGroupProperty(global::Interop.HttpApi.HTTP_SERVER_PROPERTY.HttpServerBindingProperty, info, (uint)Marshal.SizeOf(typeof(global::Interop.HttpApi.HTTP_BINDING_INFO)));
711 }
712
713 private unsafe void DetachRequestQueueFromUrlGroup()
714 {
715 global::Interop.HttpApi.HTTP_BINDING_INFO hTTP_BINDING_INFO = default(global::Interop.HttpApi.HTTP_BINDING_INFO);
716 hTTP_BINDING_INFO.Flags = global::Interop.HttpApi.HTTP_FLAGS.NONE;
717 hTTP_BINDING_INFO.RequestQueueHandle = IntPtr.Zero;
718 uint num = global::Interop.HttpApi.HttpSetUrlGroupProperty(pPropertyInfo: new IntPtr(&hTTP_BINDING_INFO), urlGroupId: _urlGroupId, serverProperty: global::Interop.HttpApi.HTTP_SERVER_PROPERTY.HttpServerBindingProperty, propertyInfoLength: (uint)Marshal.SizeOf(typeof(global::Interop.HttpApi.HTTP_BINDING_INFO)));
719 if (num != 0 && System.Net.NetEventSource.Log.IsEnabled())
720 {
721 System.Net.NetEventSource.Error(this, $"DetachRequestQueueFromUrlGroup {System.SR.Format(System.SR.net_listener_detach_error, num)}", "DetachRequestQueueFromUrlGroup");
722 }
723 }
724
725 public void Stop()
726 {
727 try
728 {
730 {
732 if (_state != 0)
733 {
734 RemoveAll(clear: false);
737 _state = State.Stopped;
738 }
739 }
740 }
741 catch (Exception ex)
742 {
743 if (System.Net.NetEventSource.Log.IsEnabled())
744 {
745 System.Net.NetEventSource.Error(this, $"Stop {ex}", "Stop");
746 }
747 throw;
748 }
749 }
750
752 {
754 }
755
761
762 public void Abort()
763 {
765 {
766 try
767 {
768 if (_state != State.Closed)
769 {
770 if (_state == State.Started)
771 {
774 }
776 }
777 }
778 catch (Exception ex)
779 {
780 if (System.Net.NetEventSource.Log.IsEnabled())
781 {
782 System.Net.NetEventSource.Error(this, $"Abort {ex}", "Abort");
783 }
784 throw;
785 }
786 finally
787 {
788 _state = State.Closed;
789 }
790 }
791 }
792
793 private void Dispose()
794 {
796 {
797 try
798 {
799 if (_state != State.Closed)
800 {
801 Stop();
803 }
804 }
805 catch (Exception ex)
806 {
807 if (System.Net.NetEventSource.Log.IsEnabled())
808 {
809 System.Net.NetEventSource.Error(this, $"Dispose {ex}", "Dispose");
810 }
811 throw;
812 }
813 finally
814 {
815 _state = State.Closed;
816 }
817 }
818 }
819
820 private void RemovePrefixCore(string uriPrefix)
821 {
822 global::Interop.HttpApi.HttpRemoveUrlFromUrlGroup(_urlGroupId, uriPrefix, 0u);
823 }
824
825 private void AddAllPrefixes()
826 {
827 if (_uriPrefixes.Count <= 0)
828 {
829 return;
830 }
831 foreach (string value in _uriPrefixes.Values)
832 {
834 }
835 }
836
837 private void AddPrefixCore(string registeredPrefix)
838 {
839 if (System.Net.NetEventSource.Log.IsEnabled())
840 {
841 System.Net.NetEventSource.Info(this, "Calling Interop.HttpApi.HttpAddUrl[ToUrlGroup]", "AddPrefixCore");
842 }
843 uint num = global::Interop.HttpApi.HttpAddUrlToUrlGroup(_urlGroupId, registeredPrefix, 0uL, 0u);
844 switch (num)
845 {
846 case 183u:
848 default:
849 throw new HttpListenerException((int)num);
850 case 0u:
851 break;
852 }
853 }
854
856 {
859 bool stoleBlob = false;
860 try
861 {
863 if (_state == State.Stopped)
864 {
866 }
867 if (_uriPrefixes.Count == 0)
868 {
870 }
871 uint num = 0u;
872 uint num2 = 4096u;
873 ulong num3 = 0uL;
876 while (true)
877 {
878 if (System.Net.NetEventSource.Log.IsEnabled())
879 {
880 System.Net.NetEventSource.Info(this, $"Calling Interop.HttpApi.HttpReceiveHttpRequest RequestId: {num3}", "GetContext");
881 }
882 uint num4 = 0u;
883 num = global::Interop.HttpApi.HttpReceiveHttpRequest(currentSession.RequestQueueHandle, num3, 1u, syncRequestContext.RequestBlob, num2, &num4, null);
884 if (System.Net.NetEventSource.Log.IsEnabled())
885 {
886 System.Net.NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveHttpRequest returned:" + num, "GetContext");
887 }
888 if (num == 87 && num3 != 0L)
889 {
890 num3 = 0uL;
891 continue;
892 }
893 switch (num)
894 {
895 case 234u:
896 num2 = num4;
897 num3 = syncRequestContext.RequestBlob->RequestId;
898 syncRequestContext.Reset(checked((int)num2));
899 break;
900 default:
901 throw new HttpListenerException((int)num);
902 case 0u:
904 {
906 }
907 if (stoleBlob)
908 {
909 syncRequestContext = null;
910 stoleBlob = false;
911 }
912 if (System.Net.NetEventSource.Log.IsEnabled())
913 {
914 System.Net.NetEventSource.Info(this, ":HandleAuthentication() returned httpContext" + httpListenerContext, "GetContext");
915 }
916 if (httpListenerContext != null)
917 {
918 return httpListenerContext;
919 }
920 if (syncRequestContext == null)
921 {
923 }
924 num3 = 0uL;
925 break;
926 }
927 }
928 }
929 catch (Exception ex)
930 {
931 if (System.Net.NetEventSource.Log.IsEnabled())
932 {
933 System.Net.NetEventSource.Error(this, $"{ex}", "GetContext");
934 }
935 throw;
936 }
937 finally
938 {
939 if (syncRequestContext != null && !stoleBlob)
940 {
941 syncRequestContext.ReleasePins();
942 syncRequestContext.Close();
943 }
944 }
945 }
946
948 {
949 if (requestMemory.RequestBlob->Headers.UnknownHeaderCount > 1000)
950 {
951 SendError(session, requestMemory.RequestBlob->RequestId, HttpStatusCode.BadRequest, null);
952 return false;
953 }
954 return true;
955 }
956
957 public IAsyncResult BeginGetContext(AsyncCallback? callback, object? state)
958 {
960 try
961 {
963 if (_state == State.Stopped)
964 {
966 }
968 uint num = listenerAsyncResult.QueueBeginGetContext();
969 if (num != 0 && num != 997)
970 {
971 throw new HttpListenerException((int)num);
972 }
973 }
974 catch (Exception ex)
975 {
976 if (System.Net.NetEventSource.Log.IsEnabled())
977 {
978 System.Net.NetEventSource.Error(this, $"BeginGetContext {ex}", "BeginGetContext");
979 }
980 throw;
981 }
982 return listenerAsyncResult;
983 }
984
986 {
988 try
989 {
991 if (asyncResult == null)
992 {
993 throw new ArgumentNullException("asyncResult");
994 }
995 if (System.Net.NetEventSource.Log.IsEnabled())
996 {
997 System.Net.NetEventSource.Info(this, $"asyncResult: {asyncResult}", "EndGetContext");
998 }
1000 {
1001 throw new ArgumentException(System.SR.net_io_invalidasyncresult, "asyncResult");
1002 }
1003 if (listenerAsyncResult.EndCalled)
1004 {
1006 }
1007 listenerAsyncResult.EndCalled = true;
1008 httpListenerContext = listenerAsyncResult.InternalWaitForCompletion() as HttpListenerContext;
1009 if (httpListenerContext == null)
1010 {
1012 }
1013 }
1014 catch (Exception ex)
1015 {
1016 if (System.Net.NetEventSource.Log.IsEnabled())
1017 {
1018 System.Net.NetEventSource.Error(this, $"EndGetContext {ex}", "EndGetContext");
1019 }
1020 throw;
1021 }
1022 return httpListenerContext;
1023 }
1024
1026 {
1027 if (System.Net.NetEventSource.Log.IsEnabled())
1028 {
1029 System.Net.NetEventSource.Info(this, "HandleAuthentication() memoryBlob:0x" + ((IntPtr)memoryBlob.RequestBlob).ToString("x"), "HandleAuthentication");
1030 }
1031 string text = null;
1032 stoleBlob = false;
1033 string knownHeader = global::Interop.HttpApi.GetKnownHeader(memoryBlob.RequestBlob, 24);
1034 ulong connectionId = memoryBlob.RequestBlob->ConnectionId;
1035 ulong requestId = memoryBlob.RequestBlob->RequestId;
1036 bool isSecureConnection = memoryBlob.RequestBlob->pSslInfo != null;
1037 if (System.Net.NetEventSource.Log.IsEnabled())
1038 {
1039 System.Net.NetEventSource.Info(this, $"HandleAuthentication() authorizationHeader: ({knownHeader})", "HandleAuthentication");
1040 }
1043 {
1044 if (knownHeader == null)
1045 {
1046 WindowsPrincipal windowsPrincipal = value?.AuthenticatedConnection;
1047 if (windowsPrincipal != null)
1048 {
1049 if (System.Net.NetEventSource.Log.IsEnabled())
1050 {
1051 System.Net.NetEventSource.Info(this, $"Principal: {windowsPrincipal} principal.Identity.Name: {windowsPrincipal.Identity.Name} creating request", "HandleAuthentication");
1052 }
1053 stoleBlob = true;
1055 httpListenerContext.SetIdentity(windowsPrincipal, null);
1056 httpListenerContext.Request.ReleasePins();
1057 return httpListenerContext;
1058 }
1059 }
1060 else
1061 {
1062 if (System.Net.NetEventSource.Log.IsEnabled())
1063 {
1064 System.Net.NetEventSource.Info(this, "Clearing principal cache", "HandleAuthentication");
1065 }
1066 if (value != null)
1067 {
1068 value.AuthenticatedConnection = null;
1069 }
1070 }
1071 }
1072 stoleBlob = true;
1080 try
1081 {
1082 if (value != null && !value.StartOwningDisconnectHandling())
1083 {
1084 value = null;
1085 }
1086 if (value != null)
1087 {
1088 nTAuthentication = value.Session;
1089 }
1091 AuthenticationSchemeSelector authenticationDelegate = _authenticationDelegate;
1092 if (authenticationDelegate != null)
1093 {
1094 try
1095 {
1096 httpContext.Request.ReleasePins();
1097 authenticationSchemes2 = (httpContext.AuthenticationSchemes = authenticationDelegate(httpContext.Request));
1098 if (System.Net.NetEventSource.Log.IsEnabled())
1099 {
1100 System.Net.NetEventSource.Info(this, $"AuthenticationScheme: {authenticationSchemes2}", "HandleAuthentication");
1101 }
1102 }
1104 {
1105 if (System.Net.NetEventSource.Log.IsEnabled())
1106 {
1108 System.Net.NetEventSource.Info(this, $"authenticationScheme: {authenticationSchemes2}", "HandleAuthentication");
1109 }
1110 SendError(session, requestId, HttpStatusCode.InternalServerError, null);
1112 return null;
1113 }
1114 }
1115 else
1116 {
1117 stoleBlob = false;
1118 }
1121 {
1123 if (extendedProtectionPolicy == null)
1124 {
1126 }
1127 httpContext.ExtendedProtectionPolicy = extendedProtectionPolicy;
1128 }
1129 int i = -1;
1130 if (knownHeader != null && ((uint)authenticationSchemes2 & 0xFFFF7FFFu) != 0)
1131 {
1132 for (i = 0; i < knownHeader.Length && knownHeader[i] != ' ' && knownHeader[i] != '\t' && knownHeader[i] != '\r' && knownHeader[i] != '\n'; i++)
1133 {
1134 }
1135 if (i < knownHeader.Length)
1136 {
1137 if ((authenticationSchemes2 & AuthenticationSchemes.Negotiate) != 0 && string.Compare(knownHeader, 0, "Negotiate", 0, i, StringComparison.OrdinalIgnoreCase) == 0)
1138 {
1140 }
1141 else if ((authenticationSchemes2 & AuthenticationSchemes.Ntlm) != 0 && string.Compare(knownHeader, 0, "NTLM", 0, i, StringComparison.OrdinalIgnoreCase) == 0)
1142 {
1144 }
1145 else if ((authenticationSchemes2 & AuthenticationSchemes.Basic) != 0 && string.Compare(knownHeader, 0, "Basic", 0, i, StringComparison.OrdinalIgnoreCase) == 0)
1146 {
1148 }
1149 else if (System.Net.NetEventSource.Log.IsEnabled())
1150 {
1152 }
1153 }
1154 }
1155 HttpStatusCode httpStatusCode = HttpStatusCode.InternalServerError;
1156 bool flag = false;
1158 {
1159 if (System.Net.NetEventSource.Log.IsEnabled())
1160 {
1162 }
1163 if ((authenticationSchemes2 & AuthenticationSchemes.Anonymous) != 0)
1164 {
1165 if (!stoleBlob)
1166 {
1167 stoleBlob = true;
1168 httpContext.Request.ReleasePins();
1169 }
1170 return httpContext;
1171 }
1172 httpStatusCode = HttpStatusCode.Unauthorized;
1174 }
1175 else
1176 {
1177 byte[] array = null;
1178 byte[] array2 = null;
1179 string text2 = null;
1180 for (i++; i < knownHeader.Length && (knownHeader[i] == ' ' || knownHeader[i] == '\t' || knownHeader[i] == '\r' || knownHeader[i] == '\n'); i++)
1181 {
1182 }
1183 string s = ((i < knownHeader.Length) ? knownHeader.Substring(i) : "");
1184 IPrincipal principal = null;
1185 if (System.Net.NetEventSource.Log.IsEnabled())
1186 {
1187 System.Net.NetEventSource.Info(this, $"Performing Authentication headerScheme: {authenticationSchemes}", "HandleAuthentication");
1188 }
1189 switch (authenticationSchemes)
1190 {
1191 case AuthenticationSchemes.Negotiate:
1192 case AuthenticationSchemes.Ntlm:
1193 {
1194 if (System.Net.NetEventSource.Log.IsEnabled())
1195 {
1196 System.Net.NetEventSource.Info(this, $"context: {nTAuthentication} for connectionId: {connectionId}", "HandleAuthentication");
1197 }
1198 string text4 = ((authenticationSchemes == AuthenticationSchemes.Ntlm) ? "NTLM" : "Negotiate");
1199 if (nTAuthentication != null && nTAuthentication.Package == text4)
1200 {
1202 }
1203 else
1204 {
1208 }
1209 try
1210 {
1212 }
1213 catch (FormatException)
1214 {
1215 if (System.Net.NetEventSource.Log.IsEnabled())
1216 {
1217 System.Net.NetEventSource.Info(this, $"FormatException from FormBase64String", "HandleAuthentication");
1218 }
1219 httpStatusCode = HttpStatusCode.BadRequest;
1220 flag = true;
1221 }
1223 if (!flag)
1224 {
1225 array2 = nTAuthentication2.GetOutgoingBlob(array, throwOnError: false, out statusCode);
1226 if (System.Net.NetEventSource.Log.IsEnabled())
1227 {
1228 System.Net.NetEventSource.Info(this, $"GetOutgoingBlob returned IsCompleted: {nTAuthentication2.IsCompleted} and statusCodeNew: {statusCode}", "HandleAuthentication");
1229 }
1230 flag = !nTAuthentication2.IsValidContext;
1231 if (flag)
1232 {
1233 if (statusCode.ErrorCode == System.Net.SecurityStatusPalErrorCode.InvalidHandle && nTAuthentication == null && array != null && array.Length != 0)
1234 {
1235 statusCode = new System.Net.SecurityStatusPal(System.Net.SecurityStatusPalErrorCode.InvalidToken);
1236 }
1238 }
1239 }
1240 if (array2 != null)
1241 {
1242 text2 = ((authenticationSchemes == AuthenticationSchemes.Ntlm) ? "NTLM" : "Negotiate") + " " + Convert.ToBase64String(array2);
1243 }
1244 if (flag)
1245 {
1246 break;
1247 }
1248 if (nTAuthentication2.IsCompleted)
1249 {
1251 try
1252 {
1254 {
1255 httpStatusCode = HttpStatusCode.Unauthorized;
1256 break;
1257 }
1258 httpContext.Request.ServiceName = nTAuthentication2.ClientSpecifiedSpn;
1260 if (statusCode.ErrorCode != System.Net.SecurityStatusPalErrorCode.OK)
1261 {
1262 if (System.Net.NetEventSource.Log.IsEnabled())
1263 {
1264 System.Net.NetEventSource.Info(this, $"HandleAuthentication GetContextToken failed with statusCodeNew: {statusCode}", "HandleAuthentication");
1265 }
1267 break;
1268 }
1270 if (System.Net.NetEventSource.Log.IsEnabled())
1271 {
1272 System.Net.NetEventSource.Info(this, $"HandleAuthentication creating new WindowsIdentity from user context: {token.DangerousGetHandle():x8}", "HandleAuthentication");
1273 }
1274 WindowsPrincipal windowsPrincipal2 = new WindowsPrincipal(new WindowsIdentity(token.DangerousGetHandle(), nTAuthentication2.ProtocolName));
1276 if (!UnsafeConnectionNtlmAuthentication || !(nTAuthentication2.ProtocolName == "NTLM"))
1277 {
1278 break;
1279 }
1280 if (System.Net.NetEventSource.Log.IsEnabled())
1281 {
1282 System.Net.NetEventSource.Info(this, $"HandleAuthentication inserting principal: {principal} for connectionId: {connectionId}", "HandleAuthentication");
1283 }
1284 if (value == null)
1285 {
1287 }
1288 if (value != null)
1289 {
1290 lock (((ICollection)DisconnectResults).SyncRoot)
1291 {
1293 {
1294 value.AuthenticatedConnection = windowsPrincipal2;
1295 }
1296 }
1297 }
1298 else if (System.Net.NetEventSource.Log.IsEnabled())
1299 {
1300 System.Net.NetEventSource.Info(this, $"HandleAuthentication RegisterForDisconnectNotification failed.", "HandleAuthentication");
1301 }
1302 }
1303 finally
1304 {
1305 token?.Close();
1306 }
1307 }
1308 else
1309 {
1311 text = ((!string.IsNullOrEmpty(text2)) ? text2 : ((authenticationSchemes == AuthenticationSchemes.Ntlm) ? "NTLM" : "Negotiate"));
1312 }
1313 break;
1314 }
1315 case AuthenticationSchemes.Basic:
1316 try
1317 {
1319 s = WebHeaderEncoding.GetString(array, 0, array.Length);
1320 i = s.IndexOf(':');
1321 if (i != -1)
1322 {
1323 string text3 = s.Substring(0, i);
1324 string password = s.Substring(i + 1);
1325 if (System.Net.NetEventSource.Log.IsEnabled())
1326 {
1327 System.Net.NetEventSource.Info(this, $"Basic Identity found, userName: {text3}", "HandleAuthentication");
1328 }
1330 }
1331 else
1332 {
1333 httpStatusCode = HttpStatusCode.BadRequest;
1334 }
1335 }
1336 catch (FormatException)
1337 {
1338 if (System.Net.NetEventSource.Log.IsEnabled())
1339 {
1340 System.Net.NetEventSource.Info(this, $"FromBase64String threw a FormatException.", "HandleAuthentication");
1341 }
1342 }
1343 break;
1344 }
1345 if (principal != null)
1346 {
1347 if (System.Net.NetEventSource.Log.IsEnabled())
1348 {
1349 System.Net.NetEventSource.Info(this, $"Got principal: {principal}, IdentityName: {principal.Identity.Name} for creating request.", "HandleAuthentication");
1350 }
1351 httpContext.SetIdentity(principal, text2);
1352 }
1353 else
1354 {
1355 if (System.Net.NetEventSource.Log.IsEnabled())
1356 {
1357 System.Net.NetEventSource.Info(this, "Handshake has failed.", "HandleAuthentication");
1358 }
1360 }
1361 }
1362 ArrayList challenges = null;
1363 if (httpContext == null)
1364 {
1365 if (text != null)
1366 {
1368 }
1369 else
1370 {
1371 if (newContext != null)
1372 {
1374 {
1375 nTAuthentication2 = null;
1376 }
1378 {
1380 newContext = null;
1381 nTAuthentication3.CloseContext();
1382 }
1383 else
1384 {
1385 newContext = null;
1386 }
1387 }
1388 if (httpStatusCode != HttpStatusCode.Unauthorized)
1389 {
1390 if (System.Net.NetEventSource.Log.IsEnabled())
1391 {
1392 System.Net.NetEventSource.Info(this, "ConnectionId:" + connectionId + " because of error:" + httpStatusCode, "HandleAuthentication");
1393 }
1395 return null;
1396 }
1398 }
1399 }
1400 if (value == null && newContext != null)
1401 {
1403 if (value == null)
1404 {
1405 if (newContext != null)
1406 {
1408 {
1409 nTAuthentication2 = null;
1410 }
1412 {
1414 newContext = null;
1415 nTAuthentication4.CloseContext();
1416 }
1417 else
1418 {
1419 newContext = null;
1420 }
1421 }
1422 if (System.Net.NetEventSource.Log.IsEnabled())
1423 {
1424 System.Net.NetEventSource.Info(this, "connectionId:" + connectionId + " because of failed HttpWaitForDisconnect", "HandleAuthentication");
1425 }
1426 SendError(session, requestId, HttpStatusCode.InternalServerError, null);
1428 return null;
1429 }
1430 }
1432 {
1434 {
1435 nTAuthentication2 = null;
1436 }
1439 value.Session = newContext;
1440 nTAuthentication5?.CloseContext();
1441 }
1442 if (httpContext == null)
1443 {
1444 SendError(session, requestId, (challenges != null && challenges.Count > 0) ? HttpStatusCode.Unauthorized : HttpStatusCode.Forbidden, challenges);
1445 if (System.Net.NetEventSource.Log.IsEnabled())
1446 {
1447 System.Net.NetEventSource.Info(this, "Scheme:" + authenticationSchemes2, "HandleAuthentication");
1448 }
1449 return null;
1450 }
1451 if (!stoleBlob)
1452 {
1453 stoleBlob = true;
1454 httpContext.Request.ReleasePins();
1455 }
1456 return httpContext;
1457 }
1458 catch
1459 {
1461 if (newContext != null)
1462 {
1464 {
1465 nTAuthentication2 = null;
1466 }
1468 {
1470 newContext = null;
1471 nTAuthentication6.CloseContext();
1472 }
1473 else
1474 {
1475 newContext = null;
1476 }
1477 }
1478 throw;
1479 }
1480 finally
1481 {
1482 try
1483 {
1485 {
1486 if (newContext == null && value != null)
1487 {
1488 value.Session = null;
1489 }
1490 nTAuthentication.CloseContext();
1491 }
1493 {
1494 nTAuthentication2.CloseContext();
1495 }
1496 }
1497 finally
1498 {
1499 value?.FinishOwningDisconnectHandling();
1500 }
1501 }
1502 }
1503
1505 {
1506 if (httpContext != null)
1507 {
1508 httpContext.Request.DetachBlob(memoryBlob);
1509 httpContext.Close();
1510 httpContext = null;
1511 }
1512 }
1513
1515 {
1519 ArrayList arrayList = BuildChallenge(context.AuthenticationSchemes, request._connectionId, out newContext, context.ExtendedProtectionPolicy, request.IsSecureConnection);
1520 if (arrayList == null)
1521 {
1522 return;
1523 }
1524 foreach (string item in arrayList)
1525 {
1526 response.Headers.Add("WWW-Authenticate", item);
1527 }
1528 }
1529
1531 {
1532 if (policy.PolicyEnforcement == PolicyEnforcement.Never)
1533 {
1534 if (System.Net.NetEventSource.Log.IsEnabled())
1535 {
1537 }
1538 return null;
1539 }
1540 if (!isSecureConnection)
1541 {
1542 if (System.Net.NetEventSource.Log.IsEnabled())
1543 {
1545 }
1546 return null;
1547 }
1548 if (policy.ProtectionScenario == ProtectionScenario.TrustedProxy)
1549 {
1550 if (System.Net.NetEventSource.Log.IsEnabled())
1551 {
1553 }
1554 return null;
1555 }
1557 if (System.Net.NetEventSource.Log.IsEnabled() && channelBindingFromTls != null)
1558 {
1559 System.Net.NetEventSource.Info(this, "GetChannelBindingFromTls returned null even though OS supposedly supports Extended Protection", "GetChannelBinding");
1560 }
1561 if (System.Net.NetEventSource.Log.IsEnabled())
1562 {
1563 System.Net.NetEventSource.Info(this, System.SR.net_log_listener_cbt, "GetChannelBinding");
1564 }
1565 return channelBindingFromTls;
1566 }
1567
1569 {
1570 if (context.IsKerberos)
1571 {
1572 if (System.Net.NetEventSource.Log.IsEnabled())
1573 {
1575 }
1576 return true;
1577 }
1578 if (policy.PolicyEnforcement == PolicyEnforcement.Never)
1579 {
1580 if (System.Net.NetEventSource.Log.IsEnabled())
1581 {
1583 }
1584 return true;
1585 }
1587 {
1588 if (System.Net.NetEventSource.Log.IsEnabled())
1589 {
1591 }
1592 return true;
1593 }
1594 string clientSpecifiedSpn = context.ClientSpecifiedSpn;
1595 if (string.IsNullOrEmpty(clientSpecifiedSpn))
1596 {
1597 if (policy.PolicyEnforcement == PolicyEnforcement.WhenSupported)
1598 {
1599 if (System.Net.NetEventSource.Log.IsEnabled())
1600 {
1602 }
1603 return true;
1604 }
1605 if (System.Net.NetEventSource.Log.IsEnabled())
1606 {
1608 }
1609 return false;
1610 }
1611 if (string.Equals(clientSpecifiedSpn, "http/localhost", StringComparison.OrdinalIgnoreCase))
1612 {
1613 if (System.Net.NetEventSource.Log.IsEnabled())
1614 {
1616 }
1617 return true;
1618 }
1619 if (System.Net.NetEventSource.Log.IsEnabled())
1620 {
1622 }
1625 if (System.Net.NetEventSource.Log.IsEnabled())
1626 {
1627 if (flag)
1628 {
1630 }
1631 else
1632 {
1634 if (serviceNames.Count == 0)
1635 {
1636 if (System.Net.NetEventSource.Log.IsEnabled())
1637 {
1639 }
1640 }
1641 else
1642 {
1644 foreach (string item in serviceNames)
1645 {
1646 System.Net.NetEventSource.Info(this, "\t" + item, "CheckSpn");
1647 }
1648 }
1649 }
1650 }
1651 return flag;
1652 }
1653
1655 {
1656 if (policy.CustomServiceNames == null)
1657 {
1659 {
1661 }
1663 }
1664 return policy.CustomServiceNames;
1665 }
1666
1668 {
1670 {
1671 return scenario == ProtectionScenario.TransportSelected;
1672 }
1673 return false;
1674 }
1675
1677 {
1678 System.Net.ContextFlagsPal contextFlagsPal = System.Net.ContextFlagsPal.Connection;
1679 if (policy.PolicyEnforcement != 0)
1680 {
1681 if (policy.PolicyEnforcement == PolicyEnforcement.WhenSupported)
1682 {
1683 contextFlagsPal |= System.Net.ContextFlagsPal.AllowMissingBindings;
1684 }
1685 if (policy.ProtectionScenario == ProtectionScenario.TrustedProxy)
1686 {
1687 contextFlagsPal |= System.Net.ContextFlagsPal.ProxyBindings;
1688 }
1689 }
1690 return contextFlagsPal;
1691 }
1692
1694 {
1696 {
1697 return HttpStatusCode.Unauthorized;
1698 }
1700 {
1701 return HttpStatusCode.BadRequest;
1702 }
1703 return HttpStatusCode.InternalServerError;
1704 }
1705
1706 internal static bool IsCredentialFailure(System.Net.SecurityStatusPalErrorCode error)
1707 {
1708 if (error != System.Net.SecurityStatusPalErrorCode.LogonDenied && error != System.Net.SecurityStatusPalErrorCode.UnknownCredentials && error != System.Net.SecurityStatusPalErrorCode.NoImpersonation && error != System.Net.SecurityStatusPalErrorCode.NoAuthenticatingAuthority && error != System.Net.SecurityStatusPalErrorCode.UntrustedRoot && error != System.Net.SecurityStatusPalErrorCode.CertExpired && error != System.Net.SecurityStatusPalErrorCode.SmartcardLogonRequired)
1709 {
1710 return error == System.Net.SecurityStatusPalErrorCode.BadBinding;
1711 }
1712 return true;
1713 }
1714
1715 internal static bool IsClientFault(System.Net.SecurityStatusPalErrorCode error)
1716 {
1717 if (error != System.Net.SecurityStatusPalErrorCode.InvalidToken && error != System.Net.SecurityStatusPalErrorCode.CannotPack && error != System.Net.SecurityStatusPalErrorCode.QopNotSupported && error != System.Net.SecurityStatusPalErrorCode.NoCredentials && error != System.Net.SecurityStatusPalErrorCode.MessageAltered && error != System.Net.SecurityStatusPalErrorCode.OutOfSequence && error != System.Net.SecurityStatusPalErrorCode.IncompleteMessage && error != System.Net.SecurityStatusPalErrorCode.IncompleteCredentials && error != System.Net.SecurityStatusPalErrorCode.WrongPrincipal && error != System.Net.SecurityStatusPalErrorCode.TimeSkew && error != System.Net.SecurityStatusPalErrorCode.IllegalMessage && error != System.Net.SecurityStatusPalErrorCode.CertUnknown && error != System.Net.SecurityStatusPalErrorCode.AlgorithmMismatch && error != System.Net.SecurityStatusPalErrorCode.SecurityQosFailed)
1718 {
1719 return error == System.Net.SecurityStatusPalErrorCode.UnsupportedPreauth;
1720 }
1721 return true;
1722 }
1723
1724 private static void AddChallenge(ref ArrayList challenges, string challenge)
1725 {
1726 if (challenge == null)
1727 {
1728 return;
1729 }
1730 challenge = challenge.Trim();
1731 if (challenge.Length > 0)
1732 {
1733 if (System.Net.NetEventSource.Log.IsEnabled())
1734 {
1735 System.Net.NetEventSource.Info(null, "challenge:" + challenge, "AddChallenge");
1736 }
1737 if (challenges == null)
1738 {
1739 challenges = new ArrayList(4);
1740 }
1742 }
1743 }
1744
1746 {
1747 if (System.Net.NetEventSource.Log.IsEnabled())
1748 {
1749 System.Net.NetEventSource.Info(this, "AuthenticationScheme:" + authenticationScheme, "BuildChallenge");
1750 }
1751 ArrayList challenges = null;
1752 newContext = null;
1753 if ((authenticationScheme & AuthenticationSchemes.Negotiate) != 0)
1754 {
1755 AddChallenge(ref challenges, "Negotiate");
1756 }
1758 {
1759 AddChallenge(ref challenges, "NTLM");
1760 }
1762 {
1763 AddChallenge(ref challenges, "Basic realm=\"" + Realm + "\"");
1764 }
1765 return challenges;
1766 }
1767
1769 {
1770 try
1771 {
1772 if (System.Net.NetEventSource.Log.IsEnabled())
1773 {
1774 System.Net.NetEventSource.Info(session.Listener, "Calling Interop.HttpApi.HttpWaitForDisconnect", "RegisterForDisconnectNotification");
1775 }
1777 uint num = global::Interop.HttpApi.HttpWaitForDisconnect(session.RequestQueueHandle, connectionId, disconnectAsyncResult.NativeOverlapped);
1778 if (System.Net.NetEventSource.Log.IsEnabled())
1779 {
1780 System.Net.NetEventSource.Info(session.Listener, "Call to Interop.HttpApi.HttpWaitForDisconnect returned:" + num, "RegisterForDisconnectNotification");
1781 }
1782 if (num == 0 || num == 997)
1783 {
1785 session.Listener.DisconnectResults[connectionId] = disconnectResult;
1786 }
1787 if (num == 0 && SkipIOCPCallbackOnSuccess)
1788 {
1789 disconnectAsyncResult.IOCompleted(num, 0u, disconnectAsyncResult.NativeOverlapped);
1790 }
1791 }
1792 catch (Win32Exception ex)
1793 {
1794 uint nativeErrorCode = (uint)ex.NativeErrorCode;
1795 if (System.Net.NetEventSource.Log.IsEnabled())
1796 {
1797 System.Net.NetEventSource.Info(session.Listener, "Call to Interop.HttpApi.HttpWaitForDisconnect threw, statusCode:" + nativeErrorCode, "RegisterForDisconnectNotification");
1798 }
1799 }
1800 }
1801
1803 {
1804 if (System.Net.NetEventSource.Log.IsEnabled())
1805 {
1806 System.Net.NetEventSource.Info(session.Listener, $"RequestId: {requestId}", "SendError");
1807 }
1808 global::Interop.HttpApi.HTTP_RESPONSE hTTP_RESPONSE = default(global::Interop.HttpApi.HTTP_RESPONSE);
1809 hTTP_RESPONSE.Version = default(global::Interop.HttpApi.HTTP_VERSION);
1810 hTTP_RESPONSE.Version.MajorVersion = 1;
1811 hTTP_RESPONSE.Version.MinorVersion = 1;
1812 hTTP_RESPONSE.StatusCode = (ushort)httpStatusCode;
1814 uint num = 0u;
1815 byte[] bytes = Encoding.Default.GetBytes(s);
1816 uint num2;
1817 fixed (byte* pReason = bytes)
1818 {
1819 hTTP_RESPONSE.pReason = (sbyte*)pReason;
1820 hTTP_RESPONSE.ReasonLength = (ushort)bytes.Length;
1821 byte[] bytes2 = Encoding.Default.GetBytes("0");
1822 fixed (byte* pRawValue = &bytes2[0])
1823 {
1824 (&hTTP_RESPONSE.Headers.KnownHeaders)[11].pRawValue = (sbyte*)pRawValue;
1825 (&hTTP_RESPONSE.Headers.KnownHeaders)[11].RawValueLength = (ushort)bytes2.Length;
1826 hTTP_RESPONSE.Headers.UnknownHeaderCount = checked((ushort)(challenges?.Count ?? 0));
1827 GCHandle[] array = null;
1828 global::Interop.HttpApi.HTTP_UNKNOWN_HEADER[] array2 = null;
1829 GCHandle gCHandle = default(GCHandle);
1830 GCHandle gCHandle2 = default(GCHandle);
1831 if (hTTP_RESPONSE.Headers.UnknownHeaderCount > 0)
1832 {
1833 array = new GCHandle[hTTP_RESPONSE.Headers.UnknownHeaderCount];
1834 array2 = new global::Interop.HttpApi.HTTP_UNKNOWN_HEADER[hTTP_RESPONSE.Headers.UnknownHeaderCount];
1835 }
1836 try
1837 {
1838 if (hTTP_RESPONSE.Headers.UnknownHeaderCount > 0)
1839 {
1841 hTTP_RESPONSE.Headers.pUnknownHeaders = (global::Interop.HttpApi.HTTP_UNKNOWN_HEADER*)(void*)Marshal.UnsafeAddrOfPinnedArrayElement(array2, 0);
1843 sbyte* pName = (sbyte*)(void*)Marshal.UnsafeAddrOfPinnedArrayElement(s_wwwAuthenticateBytes, 0);
1844 for (int i = 0; i < array.Length; i++)
1845 {
1846 byte[] bytes3 = Encoding.Default.GetBytes((string)challenges[i]);
1847 array[i] = GCHandle.Alloc(bytes3, GCHandleType.Pinned);
1848 array2[i].pName = pName;
1849 array2[i].NameLength = (ushort)s_wwwAuthenticateBytes.Length;
1850 array2[i].pRawValue = (sbyte*)(void*)Marshal.UnsafeAddrOfPinnedArrayElement(bytes3, 0);
1851 array2[i].RawValueLength = checked((ushort)bytes3.Length);
1852 }
1853 }
1854 if (System.Net.NetEventSource.Log.IsEnabled())
1855 {
1856 System.Net.NetEventSource.Info(session.Listener, "Calling Interop.HttpApi.HttpSendHtthttpResponse", "SendError");
1857 }
1858 num2 = global::Interop.HttpApi.HttpSendHttpResponse(session.RequestQueueHandle, requestId, 0u, &hTTP_RESPONSE, null, &num, Microsoft.Win32.SafeHandles.SafeLocalAllocHandle.Zero, 0u, null, null);
1859 }
1860 finally
1861 {
1862 if (gCHandle.IsAllocated)
1863 {
1864 gCHandle.Free();
1865 }
1866 if (gCHandle2.IsAllocated)
1867 {
1868 gCHandle2.Free();
1869 }
1870 if (array != null)
1871 {
1872 for (int j = 0; j < array.Length; j++)
1873 {
1874 if (array[j].IsAllocated)
1875 {
1876 array[j].Free();
1877 }
1878 }
1879 }
1880 }
1881 }
1882 }
1883 if (System.Net.NetEventSource.Log.IsEnabled())
1884 {
1885 System.Net.NetEventSource.Info(session.Listener, "Call to Interop.HttpApi.HttpSendHttpResponse returned:" + num2, "SendError");
1886 }
1887 if (num2 != 0)
1888 {
1889 if (System.Net.NetEventSource.Log.IsEnabled())
1890 {
1891 System.Net.NetEventSource.Info(session.Listener, "SendUnauthorized returned:" + num2, "SendError");
1892 }
1894 }
1895 }
1896
1897 private unsafe static int GetTokenOffsetFromBlob(IntPtr blob)
1898 {
1899 IntPtr channelToken = ((global::Interop.HttpApi.HTTP_REQUEST_CHANNEL_BIND_STATUS*)(void*)blob)->ChannelToken;
1900 return (int)((byte*)(void*)channelToken - (byte*)(void*)blob);
1901 }
1902
1903 private unsafe static int GetTokenSizeFromBlob(IntPtr blob)
1904 {
1905 return (int)((global::Interop.HttpApi.HTTP_REQUEST_CHANNEL_BIND_STATUS*)(void*)blob)->ChannelTokenSize;
1906 }
1907
1909 {
1910 int num = sizeof(global::Interop.HttpApi.HTTP_REQUEST_CHANNEL_BIND_STATUS) + 128;
1911 byte[] array = null;
1912 global::Interop.HttpApi.SafeLocalFreeChannelBinding safeLocalFreeChannelBinding = null;
1913 uint num2 = 0u;
1914 uint num3;
1915 do
1916 {
1917 array = new byte[num];
1918 fixed (byte* ptr = &array[0])
1919 {
1920 num3 = global::Interop.HttpApi.HttpReceiveClientCertificate(session.RequestQueueHandle, connectionId, 1u, ptr, (uint)num, &num2, null);
1921 switch (num3)
1922 {
1923 case 0u:
1924 {
1927 safeLocalFreeChannelBinding = global::Interop.HttpApi.SafeLocalFreeChannelBinding.LocalAlloc(tokenSizeFromBlob);
1928 if (safeLocalFreeChannelBinding.IsInvalid)
1929 {
1930 throw new OutOfMemoryException();
1931 }
1933 break;
1934 }
1935 case 234u:
1936 {
1938 num = sizeof(global::Interop.HttpApi.HTTP_REQUEST_CHANNEL_BIND_STATUS) + tokenSizeFromBlob2;
1939 break;
1940 }
1941 case 87u:
1942 if (System.Net.NetEventSource.Log.IsEnabled())
1943 {
1944 System.Net.NetEventSource.Error(session.Listener, System.SR.net_ssp_dont_support_cbt, "GetChannelBindingFromTls");
1945 }
1946 return null;
1947 default:
1948 throw new HttpListenerException((int)num3);
1949 }
1950 }
1951 }
1952 while (num3 != 0);
1954 }
1955}
static readonly Microsoft.Win32.SafeHandles.SafeLocalAllocHandle Zero
bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
bool ICollection< KeyValuePair< TKey, TValue > >. Remove(KeyValuePair< TKey, TValue > keyValuePair)
bool ICollection< KeyValuePair< TKey, TValue > >. Contains(KeyValuePair< TKey, TValue > keyValuePair)
void Add(TKey key, TValue value)
virtual bool Contains(object key)
Definition Hashtable.cs:719
virtual ICollection Values
Definition Hashtable.cs:534
virtual void Remove(object key)
virtual ICollection Keys
Definition Hashtable.cs:532
static string ToBase64String(byte[] inArray)
Definition Convert.cs:2675
static unsafe byte[] FromBase64String(string s)
Definition Convert.cs:2904
static ReadOnlySpan< byte > AsciiToLower
static NetworkCredential DefaultNetworkCredentials
static bool IsFatal(Exception exception)
static readonly System.Net.SSPIAuthType SSPIAuth
Definition GlobalSSPI.cs:5
AuthenticationSchemes AuthenticationSchemes
ExtendedProtectionPolicy ExtendedProtectionPolicy
static void CancelRequest(SafeHandle requestQueueHandle, ulong requestId)
unsafe DisconnectAsyncResult(HttpListenerSession session, ulong connectionId)
unsafe void IOCompleted(uint errorCode, uint numBytes, NativeOverlapped *nativeOverlapped)
static unsafe void IOCompleted(DisconnectAsyncResult asyncResult, uint errorCode, uint numBytes, NativeOverlapped *nativeOverlapped)
static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped *nativeOverlapped)
unsafe readonly NativeOverlapped * _nativeOverlapped
readonly HttpListenerSession _listenerSession
static unsafe readonly IOCompletionCallback s_IOCallback
static bool ScenarioChecksChannelBinding(bool isSecureConnection, ProtectionScenario scenario)
readonly ServiceNameStore _defaultServiceNames
unsafe void DetachRequestQueueFromUrlGroup()
bool ContainsPrefix(string uriPrefix)
unsafe void SetServerTimeout(int[] timeouts, uint minSendBytesPerSecond)
System.Net.ContextFlagsPal GetContextFlags(ExtendedProtectionPolicy policy, bool isSecureConnection)
AuthenticationSchemeSelector? AuthenticationSchemeSelectorDelegate
void SetUrlGroupProperty(global::Interop.HttpApi.HTTP_SERVER_PROPERTY property, IntPtr info, uint infosize)
readonly HttpListenerTimeoutManager _timeoutManager
static unsafe int GetTokenOffsetFromBlob(IntPtr blob)
bool RemovePrefix(string uriPrefix)
readonly HttpListenerPrefixCollection _prefixes
AuthenticationSchemes _authenticationScheme
Dictionary< ulong, DisconnectAsyncResult > DisconnectResults
HttpListenerTimeoutManager TimeoutManager
static readonly bool SkipIOCPCallbackOnSuccess
void RemoveAll(bool clear)
IAsyncResult BeginGetContext(AsyncCallback? callback, object? state)
ExtendedProtectionSelector? ExtendedProtectionSelectorDelegate
unsafe HttpListenerContext GetContext()
static void AddChallenge(ref ArrayList challenges, string challenge)
HttpStatusCode HttpStatusFromSecurityStatus(System.Net.SecurityStatusPalErrorCode statusErrorCode)
static unsafe int GetTokenSizeFromBlob(IntPtr blob)
static unsafe void RegisterForDisconnectNotification(HttpListenerSession session, ulong connectionId, ref DisconnectAsyncResult disconnectResult)
unsafe void SetupV2Config()
ExtendedProtectionPolicy _extendedProtectionPolicy
ArrayList BuildChallenge(AuthenticationSchemes authenticationScheme, ulong connectionId, out System.Net.NTAuthentication newContext, ExtendedProtectionPolicy policy, bool isSecureConnection)
unsafe HttpListenerContext HandleAuthentication(HttpListenerSession session, RequestContextBase memoryBlob, out bool stoleBlob)
static bool IsCredentialFailure(System.Net.SecurityStatusPalErrorCode error)
void SetAuthenticationHeaders(HttpListenerContext context)
AuthenticationSchemeSelector _authenticationDelegate
bool CheckSpn(System.Net.NTAuthentication context, bool isSecureConnection, ExtendedProtectionPolicy policy)
readonly object _internalLock
static unsafe void SendError(HttpListenerSession session, ulong requestId, HttpStatusCode httpStatusCode, ArrayList challenges)
ChannelBinding GetChannelBinding(HttpListenerSession session, ulong connectionId, bool isSecureConnection, ExtendedProtectionPolicy policy)
delegate ExtendedProtectionPolicy ExtendedProtectionSelector(HttpListenerRequest request)
unsafe void AttachRequestQueueToUrlGroup()
void AddPrefix(string uriPrefix)
ExtendedProtectionPolicy ExtendedProtectionPolicy
ServiceNameCollection GetServiceNames(ExtendedProtectionPolicy policy)
AuthenticationSchemes AuthenticationSchemes
static readonly byte[] s_wwwAuthenticateBytes
Task< HttpListenerContext > GetContextAsync()
void IDisposable. Dispose()
static unsafe bool ValidateRequest(HttpListenerSession session, RequestContextBase requestMemory)
HttpListenerContext EndGetContext(IAsyncResult asyncResult)
static bool IsClientFault(System.Net.SecurityStatusPalErrorCode error)
HttpListenerSession _currentSession
ExtendedProtectionSelector _extendedProtectionSelectorDelegate
void RemovePrefixCore(string uriPrefix)
static unsafe ChannelBinding GetChannelBindingFromTls(HttpListenerSession session, ulong connectionId)
ServiceNameCollection DefaultServiceNames
Dictionary< ulong, DisconnectAsyncResult > _disconnectResults
static void FreeContext(ref HttpListenerContext httpContext, RequestContextBase memoryBlob)
void AddPrefixCore(string registeredPrefix)
HttpServerSessionHandle _serverSessionHandle
static string Get(HttpStatusCode code)
static readonly System.Net.NetEventSource Log
static void Info(object thisOrContextObject, FormattableString formattableString=null, [CallerMemberName] string memberName=null)
static void Error(object thisOrContextObject, FormattableString formattableString, [CallerMemberName] string memberName=null)
static int QuerySecurityContextToken(System.Net.ISSPIInterface secModule, System.Net.Security.SafeDeleteContext context, out System.Net.Security.SecurityContextTokenHandle token)
bool Add(string uriPrefix)
bool Remove(string uriPrefix)
ServiceNameCollection ServiceNames
static unsafe string GetString(byte[] bytes, int byteIndex, int byteCount)
static void Copy(int[] source, int startIndex, IntPtr destination, int length)
Definition Marshal.cs:800
static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
Definition Marshal.cs:775
static int SizeOf(object structure)
Definition Marshal.cs:697
static string net_log_listener_no_cbt_http
Definition SR.cs:40
static string net_log_listener_no_spn_loopback
Definition SR.cs:54
static string net_log_listener_no_spn_kerberos
Definition SR.cs:46
static string net_log_listener_unmatched_authentication_scheme
Definition SR.cs:18
static string net_log_listener_spn_failed_always
Definition SR.cs:62
static string net_listener_cannot_set_custom_cbt
Definition SR.cs:24
static string net_log_listener_no_spn_whensupported
Definition SR.cs:52
static string net_log_listener_no_cbt_trustedproxy
Definition SR.cs:42
static string net_io_invalidendcall
Definition SR.cs:22
static string Format(string resourceFormat, object p1)
Definition SR.cs:118
static string net_listener_host
Definition SR.cs:30
static string net_log_listener_no_spn_disabled
Definition SR.cs:48
static string net_log_listener_unsupported_authentication_scheme
Definition SR.cs:16
static string net_listener_slash
Definition SR.cs:34
static string net_listener_mustcall
Definition SR.cs:32
static string net_log_listener_delegate_exception
Definition SR.cs:14
static string net_log_listener_spn_failed
Definition SR.cs:60
static string net_PropertyNotImplementedException
Definition SR.cs:80
static string net_listener_scheme
Definition SR.cs:28
static string net_io_invalidasyncresult
Definition SR.cs:20
static string net_log_listener_cbt
Definition SR.cs:44
static string net_log_listener_spn_failed_empty
Definition SR.cs:64
static string net_log_listener_no_cbt_disabled
Definition SR.cs:38
static string net_log_listener_spn_failed_dump
Definition SR.cs:66
static string net_log_listener_spn_passed
Definition SR.cs:58
static string net_log_listener_no_spn_cbt
Definition SR.cs:50
static string net_listener_already
Definition SR.cs:36
static string net_ssp_dont_support_cbt
Definition SR.cs:78
static string net_log_listener_spn
Definition SR.cs:56
static string net_listener_no_spns
Definition SR.cs:76
Definition SR.cs:7
static Encoding Default
Definition Encoding.cs:345
static int CompareExchange(ref int location1, int value, int comparand)
static int Exchange(ref int location1, int value)
static new TaskFactory< TResult > Factory
Definition Task.cs:56
static unsafe? object GetNativeOverlappedState(NativeOverlapped *overlapped)
unsafe delegate void IOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped *pOVERLAP)
static readonly IntPtr Zero
Definition IntPtr.cs:18
static GCHandle Alloc(object? value)
Definition GCHandle.cs:81