From 86224fd11c943ebe111c602358f8b8d3c3fb7494 Mon Sep 17 00:00:00 2001 From: Prashanth Govindarajan Date: Wed, 26 Aug 2020 10:29:19 -0700 Subject: [PATCH] Nullability annotations for HttpListener (#41189) * src files annotated * ref file * Address feedback --- .../src/Interop/Windows/HttpApi/Interop.HttpApi.cs | 38 +++--- .../ref/System.Net.HttpListener.cs | 35 +++--- .../ref/System.Net.HttpListener.csproj | 1 + .../src/System.Net.HttpListener.csproj | 4 +- .../src/System/Net/HttpListener.cs | 22 ++-- .../src/System/Net/HttpListenerContext.cs | 8 +- .../src/System/Net/HttpListenerRequest.cs | 76 ++++++------ .../System/Net/HttpListenerRequestUriBuilder.cs | 29 +++-- .../src/System/Net/HttpListenerResponse.cs | 24 ++-- .../src/System/Net/HttpRequestStream.cs | 6 +- .../src/System/Net/HttpResponseStream.cs | 4 +- .../src/System/Net/Managed/ChunkStream.cs | 2 +- .../src/System/Net/Managed/ChunkedInputStream.cs | 10 +- .../src/System/Net/Managed/HttpConnection.cs | 73 ++++++------ .../src/System/Net/Managed/HttpEndPointListener.cs | 40 +++---- .../src/System/Net/Managed/HttpEndPointManager.cs | 14 +-- .../Net/Managed/HttpListener.Certificates.cs | 2 +- .../src/System/Net/Managed/HttpListener.Managed.cs | 12 +- .../Net/Managed/HttpListenerContext.Managed.cs | 11 +- .../Net/Managed/HttpListenerRequest.Managed.cs | 36 +++--- .../Net/Managed/HttpListenerResponse.Managed.cs | 16 +-- .../Net/Managed/HttpRequestStream.Managed.cs | 2 +- .../Net/Managed/HttpResponseStream.Managed.cs | 18 +-- .../System/Net/Managed/HttpStreamAsyncResult.cs | 12 +- .../Net/Managed/ListenerAsyncResult.Managed.cs | 34 +++--- .../src/System/Net/Managed/ListenerPrefix.cs | 18 +-- .../Managed/WebSockets/HttpWebSocket.Managed.cs | 22 ++-- .../src/System/Net/ServiceNameStore.cs | 24 ++-- .../Net/WebSockets/HttpListenerWebSocketContext.cs | 4 +- .../src/System/Net/WebSockets/HttpWebSocket.cs | 10 +- .../src/System/Net/Windows/AsyncRequestContext.cs | 8 +- .../src/System/Net/Windows/CookieExtensions.cs | 16 +-- .../src/System/Net/Windows/HttpListener.Windows.cs | 131 +++++++++++---------- .../Net/Windows/HttpListenerContext.Windows.cs | 18 +-- .../Net/Windows/HttpListenerRequest.Windows.cs | 56 ++++----- .../Net/Windows/HttpListenerRequestContext.cs | 2 +- .../Net/Windows/HttpListenerResponse.Windows.cs | 39 +++--- .../Net/Windows/HttpListenerSession.Windows.cs | 4 +- .../Net/Windows/HttpRequestStream.Windows.cs | 26 ++-- .../Net/Windows/HttpResponseStream.Windows.cs | 20 ++-- .../Net/Windows/HttpResponseStreamAsyncResult.cs | 20 ++-- .../Net/Windows/ListenerAsyncResult.Windows.cs | 21 ++-- .../ListenerClientCertAsyncResult.Windows.cs | 18 +-- .../Windows/WebSockets/HttpWebSocket.Windows.cs | 20 ++-- .../System/Net/Windows/WebSockets/WebSocketBase.cs | 118 +++++++++---------- .../Net/Windows/WebSockets/WebSocketBuffer.cs | 34 +++--- .../WebSocketHttpListenerDuplexStream.cs | 92 +++++++-------- .../WebSockets/WebSocketProtocolComponent.cs | 30 ++--- 48 files changed, 650 insertions(+), 630 deletions(-) diff --git a/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs b/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs index ed6e282..25b03f5 100644 --- a/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs +++ b/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs @@ -536,7 +536,7 @@ internal static partial class Interop [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, byte* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, NativeOverlapped* pOverlapped); - internal static readonly string[] HttpVerbs = new string[] + internal static readonly string?[] HttpVerbs = new string?[] { null, "Unknown", @@ -661,9 +661,9 @@ internal static partial class Interop } } - private static unsafe string GetKnownHeader(HTTP_REQUEST* request, long fixup, int headerIndex) + private static unsafe string? GetKnownHeader(HTTP_REQUEST* request, long fixup, int headerIndex) { - string header = null; + string? header = null; HTTP_KNOWN_HEADER* pKnownHeader = (&request->Headers.KnownHeaders) + headerIndex; @@ -683,14 +683,14 @@ internal static partial class Interop return header; } - internal static unsafe string GetKnownHeader(HTTP_REQUEST* request, int headerIndex) + internal static unsafe string? GetKnownHeader(HTTP_REQUEST* request, int headerIndex) { return GetKnownHeader(request, 0, headerIndex); } - private static unsafe string GetVerb(HTTP_REQUEST* request, long fixup) + private static unsafe string? GetVerb(HTTP_REQUEST* request, long fixup) { - string verb = null; + string? verb = null; if ((int)request->Verb > (int)HTTP_VERB.HttpVerbUnknown && (int)request->Verb < (int)HTTP_VERB.HttpVerbMaximum) { @@ -704,12 +704,12 @@ internal static partial class Interop return verb; } - internal static unsafe string GetVerb(HTTP_REQUEST* request) + internal static unsafe string? GetVerb(HTTP_REQUEST* request) { return GetVerb(request, 0); } - internal static unsafe string GetVerb(IntPtr memoryBlob, IntPtr originalAddress) + internal static unsafe string? GetVerb(IntPtr memoryBlob, IntPtr originalAddress) { return GetVerb((HTTP_REQUEST*)memoryBlob.ToPointer(), (byte*)memoryBlob - (byte*)originalAddress); } @@ -834,17 +834,17 @@ internal static partial class Interop return verb; } - internal static unsafe IPEndPoint GetRemoteEndPoint(IntPtr memoryBlob, IntPtr originalAddress) + internal static unsafe IPEndPoint? GetRemoteEndPoint(IntPtr memoryBlob, IntPtr originalAddress) { - SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); - SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); + SocketAddress? v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); + SocketAddress? v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); byte* pMemoryBlob = (byte*)memoryBlob; HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob; IntPtr address = request->Address.pRemoteAddress != null ? (IntPtr)(pMemoryBlob - (byte*)originalAddress + (byte*)request->Address.pRemoteAddress) : IntPtr.Zero; CopyOutAddress(address, ref v4address, ref v6address); - IPEndPoint endpoint = null; + IPEndPoint? endpoint = null; if (v4address != null) { endpoint = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort).Create(v4address) as IPEndPoint; @@ -857,17 +857,17 @@ internal static partial class Interop return endpoint; } - internal static unsafe IPEndPoint GetLocalEndPoint(IntPtr memoryBlob, IntPtr originalAddress) + internal static unsafe IPEndPoint? GetLocalEndPoint(IntPtr memoryBlob, IntPtr originalAddress) { - SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); - SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); + SocketAddress? v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); + SocketAddress? v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); byte* pMemoryBlob = (byte*)memoryBlob; HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob; IntPtr address = request->Address.pLocalAddress != null ? (IntPtr)(pMemoryBlob - (byte*)originalAddress + (byte*)request->Address.pLocalAddress) : IntPtr.Zero; CopyOutAddress(address, ref v4address, ref v6address); - IPEndPoint endpoint = null; + IPEndPoint? endpoint = null; if (v4address != null) { endpoint = s_any.Create(v4address) as IPEndPoint; @@ -880,7 +880,7 @@ internal static partial class Interop return endpoint; } - private static unsafe void CopyOutAddress(IntPtr address, ref SocketAddress v4address, ref SocketAddress v6address) + private static unsafe void CopyOutAddress(IntPtr address, ref SocketAddress? v4address, ref SocketAddress? v6address) { if (address != IntPtr.Zero) { @@ -890,7 +890,7 @@ internal static partial class Interop v6address = null; for (int index = 2; index < IPv4AddressSize; index++) { - v4address[index] = ((byte*)address)[index]; + v4address![index] = ((byte*)address)[index]; } return; } @@ -899,7 +899,7 @@ internal static partial class Interop v4address = null; for (int index = 2; index < IPv6AddressSize; index++) { - v6address[index] = ((byte*)address)[index]; + v6address![index] = ((byte*)address)[index]; } return; } diff --git a/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.cs b/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.cs index 27f33aa..10e2e36 100644 --- a/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.cs +++ b/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.cs @@ -11,15 +11,16 @@ namespace System.Net { public HttpListener() { } public System.Net.AuthenticationSchemes AuthenticationSchemes { get { throw null; } set { } } - public System.Net.AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate { get { throw null; } set { } } + public System.Net.AuthenticationSchemeSelector? AuthenticationSchemeSelectorDelegate { get { throw null; } set { } } public System.Security.Authentication.ExtendedProtection.ServiceNameCollection DefaultServiceNames { get { throw null; } } public System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy ExtendedProtectionPolicy { get { throw null; } set { } } - public System.Net.HttpListener.ExtendedProtectionSelector ExtendedProtectionSelectorDelegate { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] + public System.Net.HttpListener.ExtendedProtectionSelector? ExtendedProtectionSelectorDelegate { get { throw null; } set { } } public bool IgnoreWriteExceptions { get { throw null; } set { } } public bool IsListening { get { throw null; } } public static bool IsSupported { get { throw null; } } public System.Net.HttpListenerPrefixCollection Prefixes { get { throw null; } } - public string Realm { get { throw null; } set { } } + public string? Realm { get { throw null; } set { } } public System.Net.HttpListenerTimeoutManager TimeoutManager { get { throw null; } } public bool UnsafeConnectionNtlmAuthentication { get { throw null; } set { } } public void Abort() { } @@ -43,7 +44,7 @@ namespace System.Net internal HttpListenerContext() { } public System.Net.HttpListenerRequest Request { get { throw null; } } public System.Net.HttpListenerResponse Response { get { throw null; } } - public System.Security.Principal.IPrincipal User { get { throw null; } } + public System.Security.Principal.IPrincipal? User { get { throw null; } } public System.Threading.Tasks.Task AcceptWebSocketAsync(string subProtocol) { throw null; } public System.Threading.Tasks.Task AcceptWebSocketAsync(string subProtocol, int receiveBufferSize, System.TimeSpan keepAliveInterval) { throw null; } public System.Threading.Tasks.Task AcceptWebSocketAsync(string subProtocol, int receiveBufferSize, System.TimeSpan keepAliveInterval, System.ArraySegment internalBuffer) { throw null; } @@ -75,11 +76,11 @@ namespace System.Net public sealed partial class HttpListenerRequest { internal HttpListenerRequest() { } - public string[] AcceptTypes { get { throw null; } } + public string[]? AcceptTypes { get { throw null; } } public int ClientCertificateError { get { throw null; } } public System.Text.Encoding ContentEncoding { get { throw null; } } public long ContentLength64 { get { throw null; } } - public string ContentType { get { throw null; } } + public string? ContentType { get { throw null; } } public System.Net.CookieCollection Cookies { get { throw null; } } public bool HasEntityBody { get { throw null; } } public System.Collections.Specialized.NameValueCollection Headers { get { throw null; } } @@ -93,34 +94,34 @@ namespace System.Net public System.Net.IPEndPoint LocalEndPoint { get { throw null; } } public System.Version ProtocolVersion { get { throw null; } } public System.Collections.Specialized.NameValueCollection QueryString { get { throw null; } } - public string RawUrl { get { throw null; } } + public string? RawUrl { get { throw null; } } public System.Net.IPEndPoint RemoteEndPoint { get { throw null; } } public System.Guid RequestTraceIdentifier { get { throw null; } } - public string ServiceName { get { throw null; } } + public string? ServiceName { get { throw null; } } public System.Net.TransportContext TransportContext { get { throw null; } } - public System.Uri Url { get { throw null; } } - public System.Uri UrlReferrer { get { throw null; } } + public System.Uri? Url { get { throw null; } } + public System.Uri? UrlReferrer { get { throw null; } } public string UserAgent { get { throw null; } } public string UserHostAddress { get { throw null; } } public string UserHostName { get { throw null; } } - public string[] UserLanguages { get { throw null; } } + public string[]? UserLanguages { get { throw null; } } public System.IAsyncResult BeginGetClientCertificate(System.AsyncCallback requestCallback, object state) { throw null; } - public System.Security.Cryptography.X509Certificates.X509Certificate2 EndGetClientCertificate(System.IAsyncResult asyncResult) { throw null; } - public System.Security.Cryptography.X509Certificates.X509Certificate2 GetClientCertificate() { throw null; } - public System.Threading.Tasks.Task GetClientCertificateAsync() { throw null; } + public System.Security.Cryptography.X509Certificates.X509Certificate2? EndGetClientCertificate(System.IAsyncResult asyncResult) { throw null; } + public System.Security.Cryptography.X509Certificates.X509Certificate2? GetClientCertificate() { throw null; } + public System.Threading.Tasks.Task GetClientCertificateAsync() { throw null; } } public sealed partial class HttpListenerResponse : System.IDisposable { internal HttpListenerResponse() { } - public System.Text.Encoding ContentEncoding { get { throw null; } set { } } + public System.Text.Encoding? ContentEncoding { get { throw null; } set { } } public long ContentLength64 { get { throw null; } set { } } - public string ContentType { get { throw null; } set { } } + public string? ContentType { get { throw null; } set { } } public System.Net.CookieCollection Cookies { get { throw null; } set { } } public System.Net.WebHeaderCollection Headers { get { throw null; } set { } } public bool KeepAlive { get { throw null; } set { } } public System.IO.Stream OutputStream { get { throw null; } } public System.Version ProtocolVersion { get { throw null; } set { } } - public string RedirectLocation { get { throw null; } set { } } + public string? RedirectLocation { get { throw null; } set { } } public bool SendChunked { get { throw null; } set { } } public int StatusCode { get { throw null; } set { } } public string StatusDescription { get { throw null; } set { } } diff --git a/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.csproj b/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.csproj index 35b678e..00bc533 100644 --- a/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.csproj +++ b/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.csproj @@ -1,6 +1,7 @@ $(NetCoreAppCurrent) + enable diff --git a/src/libraries/System.Net.HttpListener/src/System.Net.HttpListener.csproj b/src/libraries/System.Net.HttpListener/src/System.Net.HttpListener.csproj index 6948d70..476f598 100644 --- a/src/libraries/System.Net.HttpListener/src/System.Net.HttpListener.csproj +++ b/src/libraries/System.Net.HttpListener/src/System.Net.HttpListener.csproj @@ -1,9 +1,9 @@ - + true false $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser - annotations + enable diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs index bde2c4e..b391474 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Security.Authentication.ExtendedProtection; using System.Text; using System.Threading.Tasks; @@ -20,10 +21,10 @@ namespace System.Net private readonly ServiceNameStore _defaultServiceNames; private readonly HttpListenerTimeoutManager _timeoutManager; private ExtendedProtectionPolicy _extendedProtectionPolicy; - private AuthenticationSchemeSelector _authenticationDelegate; + private AuthenticationSchemeSelector? _authenticationDelegate; private AuthenticationSchemes _authenticationScheme = AuthenticationSchemes.Anonymous; - private ExtendedProtectionSelector _extendedProtectionSelectorDelegate; - private string _realm; + private ExtendedProtectionSelector? _extendedProtectionSelectorDelegate; + private string? _realm; internal ICollection PrefixCollection => _uriPrefixes.Keys; @@ -41,7 +42,7 @@ namespace System.Net _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); } - public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate + public AuthenticationSchemeSelector? AuthenticationSchemeSelectorDelegate { get => _authenticationDelegate; set @@ -51,7 +52,8 @@ namespace System.Net } } - public ExtendedProtectionSelector ExtendedProtectionSelectorDelegate + [DisallowNull] + public ExtendedProtectionSelector? ExtendedProtectionSelectorDelegate { get => _extendedProtectionSelectorDelegate; set @@ -108,7 +110,7 @@ namespace System.Net internal void AddPrefix(string uriPrefix) { - string registeredPrefix = null; + string? registeredPrefix = null; try { if (uriPrefix == null) @@ -207,7 +209,7 @@ namespace System.Net if (_state == State.Started) { - RemovePrefixCore((string)_uriPrefixes[uriPrefix]); + RemovePrefixCore((string)_uriPrefixes[uriPrefix]!); } _uriPrefixes.Remove(uriPrefix); @@ -243,7 +245,7 @@ namespace System.Net } } - public string Realm + public string? Realm { get => _realm; set @@ -268,8 +270,8 @@ namespace System.Net public Task GetContextAsync() { return Task.Factory.FromAsync( - (callback, state) => ((HttpListener)state).BeginGetContext(callback, state), - iar => ((HttpListener)iar.AsyncState).EndGetContext(iar), + (callback, state) => ((HttpListener)state!).BeginGetContext(callback, state), + iar => ((HttpListener)iar!.AsyncState!).EndGetContext(iar), this); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs index 3297590..fe1a1c4 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs @@ -9,13 +9,13 @@ namespace System.Net { public sealed unsafe partial class HttpListenerContext { - internal HttpListener _listener; - private HttpListenerResponse _response; - private IPrincipal _user; + internal HttpListener? _listener; + private HttpListenerResponse? _response; + private IPrincipal? _user; public HttpListenerRequest Request { get; } - public IPrincipal User => _user; + public IPrincipal? User => _user; // This can be used to cache the results of HttpListener.AuthenticationSchemeSelectorDelegate. internal AuthenticationSchemes AuthenticationSchemes { get; set; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs index 22f1a15..2cd1587 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs @@ -15,24 +15,24 @@ namespace System.Net { public sealed unsafe partial class HttpListenerRequest { - private CookieCollection _cookies; + private CookieCollection? _cookies; private bool? _keepAlive; - private string _rawUrl; - private Uri _requestUri; + private string? _rawUrl; + private Uri? _requestUri; private Version _version; - public string[] AcceptTypes => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.Accept]); + public string[]? AcceptTypes => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.Accept]!); - public string[] UserLanguages => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.AcceptLanguage]); + public string[]? UserLanguages => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.AcceptLanguage]!); - private CookieCollection ParseCookies(Uri uri, string setCookieHeader) + private CookieCollection ParseCookies(Uri? uri, string setCookieHeader) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "uri:" + uri + " setCookieHeader:" + setCookieHeader); CookieCollection cookies = new CookieCollection(); CookieParser parser = new CookieParser(setCookieHeader); while (true) { - Cookie cookie = parser.GetServer(); + Cookie? cookie = parser.GetServer(); if (cookie == null) { // EOF, done. @@ -55,7 +55,7 @@ namespace System.Net { if (_cookies == null) { - string cookieString = Headers[HttpKnownHeaderNames.Cookie]; + string? cookieString = Headers[HttpKnownHeaderNames.Cookie]; if (!string.IsNullOrEmpty(cookieString)) { _cookies = ParseCookies(RequestUri, cookieString); @@ -75,7 +75,7 @@ namespace System.Net { if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP")) { - string postDataCharset = Headers["x-up-devcap-post-charset"]; + string? postDataCharset = Headers["x-up-devcap-post-charset"]; if (postDataCharset != null && postDataCharset.Length > 0) { try @@ -91,7 +91,7 @@ namespace System.Net { if (ContentType != null) { - string charSet = Helpers.GetCharSetValueFromHeader(ContentType); + string? charSet = Helpers.GetCharSetValueFromHeader(ContentType); if (charSet != null) { try @@ -108,9 +108,9 @@ namespace System.Net } } - public string ContentType => Headers[HttpKnownHeaderNames.ContentType]; + public string? ContentType => Headers[HttpKnownHeaderNames.ContentType]; - public bool IsLocal => LocalEndPoint.Address.Equals(RemoteEndPoint.Address); + public bool IsLocal => LocalEndPoint!.Address.Equals(RemoteEndPoint!.Address); public bool IsWebSocketRequest { @@ -127,7 +127,7 @@ namespace System.Net return false; } - foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection)) + foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection)!) { if (string.Equals(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase)) { @@ -141,7 +141,7 @@ namespace System.Net return false; } - foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade)) + foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade)!) { if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase)) { @@ -159,7 +159,7 @@ namespace System.Net { if (!_keepAlive.HasValue) { - string header = Headers[HttpKnownHeaderNames.ProxyConnection]; + string? header = Headers[HttpKnownHeaderNames.ProxyConnection]; if (string.IsNullOrEmpty(header)) { header = Headers[HttpKnownHeaderNames.Connection]; @@ -195,41 +195,41 @@ namespace System.Net get { NameValueCollection queryString = new NameValueCollection(); - Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding); + Helpers.FillFromString(queryString, Url!.Query, true, ContentEncoding); return queryString; } } - public string RawUrl => _rawUrl; + public string? RawUrl => _rawUrl; private string RequestScheme => IsSecureConnection ? UriScheme.Https : UriScheme.Http; - public string UserAgent => Headers[HttpKnownHeaderNames.UserAgent]; + public string UserAgent => Headers[HttpKnownHeaderNames.UserAgent]!; - public string UserHostAddress => LocalEndPoint.ToString(); + public string UserHostAddress => LocalEndPoint!.ToString(); - public string UserHostName => Headers[HttpKnownHeaderNames.Host]; + public string UserHostName => Headers[HttpKnownHeaderNames.Host]!; - public Uri UrlReferrer + public Uri? UrlReferrer { get { - string referrer = Headers[HttpKnownHeaderNames.Referer]; + string? referrer = Headers[HttpKnownHeaderNames.Referer]; if (referrer == null) { return null; } - bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out Uri urlReferrer); + bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out Uri? urlReferrer); return success ? urlReferrer : null; } } - public Uri Url => RequestUri; + public Uri? Url => RequestUri; public Version ProtocolVersion => _version; - public X509Certificate2 GetClientCertificate() + public X509Certificate2? GetClientCertificate() { if (ClientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, $"{nameof(GetClientCertificate)}()/{nameof(BeginGetClientCertificate)}()")); @@ -253,16 +253,16 @@ namespace System.Net return BeginGetClientCertificateCore(requestCallback, state); } - public Task GetClientCertificateAsync() + public Task GetClientCertificateAsync() { return Task.Factory.FromAsync( - (callback, state) => ((HttpListenerRequest)state).BeginGetClientCertificate(callback, state), - iar => ((HttpListenerRequest)iar.AsyncState).EndGetClientCertificate(iar), + (callback, state) => ((HttpListenerRequest)state!).BeginGetClientCertificate(callback, state), + iar => ((HttpListenerRequest)iar.AsyncState!).EndGetClientCertificate(iar), this); } internal ListenerClientCertState ClientCertState { get; set; } = ListenerClientCertState.NotInitialized; - internal X509Certificate2 ClientCertificate { get; set; } + internal X509Certificate2? ClientCertificate { get; set; } public int ClientCertificateError { @@ -282,7 +282,7 @@ namespace System.Net // // Get attribute off header value // - internal static string GetCharSetValueFromHeader(string headerValue) + internal static string? GetCharSetValueFromHeader(string headerValue) { const string AttrName = "charset"; @@ -327,7 +327,7 @@ namespace System.Net return null; // parse the value - string attrValue = null; + string? attrValue = null; int j; @@ -358,7 +358,7 @@ namespace System.Net return attrValue; } - internal static string[] ParseMultivalueHeader(string s) + internal static string[]? ParseMultivalueHeader(string s) { if (s == null) return null; @@ -481,7 +481,7 @@ namespace System.Net // Accumulate bytes for decoding into characters in a special array private int _numBytes; - private byte[] _byteBuffer; + private byte[]? _byteBuffer; // Encoding to convert chars to bytes private readonly Encoding _encoding; @@ -490,7 +490,7 @@ namespace System.Net { if (_numBytes > 0) { - _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); + _numChars += _encoding.GetChars(_byteBuffer!, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } } @@ -537,8 +537,8 @@ namespace System.Net internal static void FillFromString(NameValueCollection nvc, string s, bool urlencoded, Encoding encoding) { - int l = (s != null) ? s.Length : 0; - int i = (s.Length > 0 && s[0] == '?') ? 1 : 0; + int l = s.Length; + int i = (l > 0 && s[0] == '?') ? 1 : 0; while (i < l) { @@ -566,8 +566,8 @@ namespace System.Net // extract the name / value pair - string name = null; - string value = null; + string? name = null; + string? value = null; if (ti >= 0) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs index 45d2b85..18c6106 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs @@ -25,7 +25,7 @@ namespace System.Net private readonly string _cookedUriQuery; // This field is used to build the final request Uri string from the Uri parts passed to the ctor. - private StringBuilder _requestUriString; + private StringBuilder? _requestUriString; // The raw path is parsed by looping through all characters from left to right. 'rawOctets' // is used to store consecutive percent encoded octets as actual byte values: e.g. for path /pa%C3%84th%2F/ @@ -37,11 +37,11 @@ namespace System.Net // we reach 't', the content of rawOctets { 0xC4 } will be fed into the ANSI encoding. The resulting // string '\u00C4' will be percent encoded into UTF-8 octets and appended to requestUriString. The final // path will be '/pa%C3%84th/', where '%C3%84' is the UTF-8 percent encoded character. - private List _rawOctets; - private string _rawPath; + private List? _rawOctets; + private string? _rawPath; // Holds the final request Uri. - private Uri _requestUri; + private Uri? _requestUri; private HttpListenerRequestUriBuilder(string rawUri, string cookedUriScheme, string cookedUriHost, string cookedUriPath, string cookedUriQuery) @@ -76,7 +76,7 @@ namespace System.Net BuildRequestUriUsingCookedPath(); } - return _requestUri; + return _requestUri!; } private void BuildRequestUriUsingCookedPath() @@ -174,6 +174,7 @@ namespace System.Net int index = 0; char current = '\0'; + Debug.Assert(_rawPath != null); while (index < _rawPath.Length) { current = _rawPath[index]; @@ -220,7 +221,8 @@ namespace System.Net return ParsingResult.EncodingError; } // Append the current character to the result. - _requestUriString.Append(current); + Debug.Assert(_requestUriString != null); + _requestUriString!.Append(current); index++; } } @@ -247,11 +249,11 @@ namespace System.Net return false; } - string unicodeString = null; + string? unicodeString = null; try { unicodeString = char.ConvertFromUtf32(codePointValue); - AppendOctetsPercentEncoded(_requestUriString, s_utf8Encoding.GetBytes(unicodeString)); + AppendOctetsPercentEncoded(_requestUriString!, s_utf8Encoding.GetBytes(unicodeString)); return true; } @@ -278,19 +280,20 @@ namespace System.Net return false; } - _rawOctets.Add(encodedValue); + Debug.Assert(_rawOctets != null); + _rawOctets!.Add(encodedValue); return true; } private bool EmptyDecodeAndAppendRawOctetsList(Encoding encoding) { - if (_rawOctets.Count == 0) + if (_rawOctets!.Count == 0) { return true; } - string decodedString = null; + string? decodedString = null; try { // If the encoding can get a string out of the byte array, this is a valid string in the @@ -299,11 +302,11 @@ namespace System.Net if (encoding == s_utf8Encoding) { - AppendOctetsPercentEncoded(_requestUriString, _rawOctets.ToArray()); + AppendOctetsPercentEncoded(_requestUriString!, _rawOctets.ToArray()); } else { - AppendOctetsPercentEncoded(_requestUriString, s_utf8Encoding.GetBytes(decodedString)); + AppendOctetsPercentEncoded(_requestUriString!, s_utf8Encoding.GetBytes(decodedString)); } _rawOctets.Clear(); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs index da852b1..6b7ddc8 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs @@ -10,11 +10,11 @@ namespace System.Net public sealed unsafe partial class HttpListenerResponse : IDisposable { private BoundaryType _boundaryType = BoundaryType.None; - private CookieCollection _cookies; - private readonly HttpListenerContext _httpContext; + private CookieCollection? _cookies; + private readonly HttpListenerContext? _httpContext; private bool _keepAlive = true; - private HttpResponseStream _responseStream; - private string _statusDescription; + private HttpResponseStream? _responseStream; + private string? _statusDescription; private WebHeaderCollection _webHeaders = new WebHeaderCollection(); public WebHeaderCollection Headers @@ -30,9 +30,9 @@ namespace System.Net } } - public Encoding ContentEncoding { get; set; } + public Encoding? ContentEncoding { get; set; } - public string ContentType + public string? ContentType { get => Headers[HttpKnownHeaderNames.ContentType]; set @@ -49,9 +49,9 @@ namespace System.Net } } - private HttpListenerContext HttpListenerContext => _httpContext; + private HttpListenerContext HttpListenerContext => _httpContext!; - private HttpListenerRequest HttpListenerRequest => HttpListenerContext.Request; + private HttpListenerRequest HttpListenerRequest => HttpListenerContext!.Request; internal EntitySendFormat EntitySendFormat { @@ -134,11 +134,11 @@ namespace System.Net { CheckDisposed(); EnsureResponseStream(); - return _responseStream; + return _responseStream!; } } - public string RedirectLocation + public string? RedirectLocation { get => Headers[HttpResponseHeader.Location]; set @@ -224,7 +224,7 @@ namespace System.Net if (_cookies != null) { // now go through the collection, and concatenate all the cookies in per-variant strings - string setCookie2 = null, setCookie = null; + string? setCookie2 = null, setCookie = null; for (int index = 0; index < _cookies.Count; index++) { Cookie cookie = _cookies[index]; @@ -271,7 +271,7 @@ namespace System.Net if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"url={url}"); Headers[HttpResponseHeader.Location] = url; StatusCode = (int)HttpStatusCode.Redirect; - StatusDescription = HttpStatusDescription.Get(StatusCode); + StatusDescription = HttpStatusDescription.Get(StatusCode)!; } public void SetCookie(Cookie cookie) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs index c05875a..f889057 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs @@ -37,7 +37,7 @@ namespace System.Net return ReadCore(buffer, offset, size); } - public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset); @@ -54,7 +54,7 @@ namespace System.Net throw new ArgumentOutOfRangeException(nameof(size)); } - return BeginReadCore(buffer, offset, size, callback, state); + return BeginReadCore(buffer, offset, size, callback, state)!; } public override void Flush() { } @@ -74,7 +74,7 @@ namespace System.Net public override void Write(byte[] buffer, int offset, int size) => throw new InvalidOperationException(SR.net_readonlystream); - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { throw new InvalidOperationException(SR.net_readonlystream); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs index fea4e19..e51f802 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs @@ -33,7 +33,7 @@ namespace System.Net public override int Read(byte[] buffer, int offset, int size) => throw new InvalidOperationException(SR.net_writeonlystream); - public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { throw new InvalidOperationException(SR.net_writeonlystream); } @@ -64,7 +64,7 @@ namespace System.Net WriteCore(buffer, offset, size); } - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset); if (buffer == null) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs index 09794af..b540242 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs @@ -381,7 +381,7 @@ namespace System.Net } StringReader reader = new StringReader(_saved.ToString()); - string line; + string? line; while ((line = reader.ReadLine()) != null && line != "") _headers.Add(line); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs index a21b101..6eb6f5d 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs @@ -75,7 +75,7 @@ namespace System.Net return EndRead(ares); } - protected override IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state) + protected override IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback? cback, object? state) { HttpStreamAsyncResult ares = new HttpStreamAsyncResult(this); ares._callback = cback; @@ -113,7 +113,7 @@ namespace System.Net private void OnRead(IAsyncResult base_ares) { - ReadBufferState rb = (ReadBufferState)base_ares.AsyncState; + ReadBufferState rb = (ReadBufferState)base_ares.AsyncState!; HttpStreamAsyncResult ares = rb.Ares; try { @@ -126,7 +126,7 @@ namespace System.Net return; } - _decoder.Write(ares._buffer, ares._offset, nread); + _decoder.Write(ares._buffer!, ares._offset, nread); nread = _decoder.Read(rb.Buffer, rb.Offset, rb.Count); rb.Offset += nread; rb.Count -= nread; @@ -139,7 +139,7 @@ namespace System.Net } ares._offset = 0; ares._count = Math.Min(8192, _decoder.ChunkLeft + 6); - base.BeginReadCore(ares._buffer, ares._offset, ares._count, OnRead, rb); + base.BeginReadCore(ares._buffer!, ares._offset, ares._count, OnRead, rb); } catch (Exception e) { @@ -153,7 +153,7 @@ namespace System.Net if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); - HttpStreamAsyncResult ares = asyncResult as HttpStreamAsyncResult; + HttpStreamAsyncResult? ares = asyncResult as HttpStreamAsyncResult; if (ares == null || !ReferenceEquals(this, ares._parent)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs index 5de1605..2e7e7ae 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs @@ -29,6 +29,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net.Security; using System.Net.Sockets; @@ -43,16 +44,16 @@ namespace System.Net { private static AsyncCallback s_onreadCallback = new AsyncCallback(OnRead); private const int BufferSize = 8192; - private Socket _socket; + private Socket? _socket; private Stream _stream; private HttpEndPointListener _epl; - private MemoryStream _memoryStream; - private byte[] _buffer; + private MemoryStream? _memoryStream; + private byte[]? _buffer; private HttpListenerContext _context; - private StringBuilder _currentLine; - private ListenerPrefix _prefix; - private HttpRequestStream _requestStream; - private HttpResponseStream _responseStream; + private StringBuilder? _currentLine; + private ListenerPrefix? _prefix; + private HttpRequestStream? _requestStream; + private HttpResponseStream? _responseStream; private bool _chunked; private int _reuses; private bool _contextBound; @@ -60,11 +61,11 @@ namespace System.Net private X509Certificate _cert; private int _timeout = 90000; // 90k ms for first request, 15k ms from then on private Timer _timer; - private IPEndPoint _localEndPoint; - private HttpListener _lastListener; - private int[] _clientCertErrors; - private X509Certificate2 _clientCert; - private SslStream _sslStream; + private IPEndPoint? _localEndPoint; + private HttpListener? _lastListener; + private int[]? _clientCertErrors; + private X509Certificate2? _clientCert; + private SslStream? _sslStream; private InputState _inputState = InputState.RequestLine; private LineState _lineState = LineState.None; private int _position; @@ -111,21 +112,23 @@ namespace System.Net Init(); } - internal int[] ClientCertificateErrors + internal int[]? ClientCertificateErrors { get { return _clientCertErrors; } } - internal X509Certificate2 ClientCertificate + internal X509Certificate2? ClientCertificate { get { return _clientCert; } } - internal SslStream SslStream + internal SslStream? SslStream { get { return _sslStream; } } + [MemberNotNull(nameof(_memoryStream))] + [MemberNotNull(nameof(_context))] private void Init() { _contextBound = false; @@ -152,21 +155,21 @@ namespace System.Net get { return _reuses; } } - public IPEndPoint LocalEndPoint + public IPEndPoint? LocalEndPoint { get { if (_localEndPoint != null) return _localEndPoint; - _localEndPoint = (IPEndPoint)_socket.LocalEndPoint; + _localEndPoint = (IPEndPoint?)_socket!.LocalEndPoint; return _localEndPoint; } } - public IPEndPoint RemoteEndPoint + public IPEndPoint? RemoteEndPoint { - get { return (IPEndPoint)_socket.RemoteEndPoint; } + get { return (IPEndPoint?)_socket!.RemoteEndPoint; } } public bool IsSecure @@ -174,13 +177,13 @@ namespace System.Net get { return _secure; } } - public ListenerPrefix Prefix + public ListenerPrefix? Prefix { get { return _prefix; } set { _prefix = value; } } - private void OnTimeout(object unused) + private void OnTimeout(object? unused) { CloseSocket(); Unbind(); @@ -209,8 +212,8 @@ namespace System.Net { if (_requestStream == null) { - byte[] buffer = _memoryStream.GetBuffer(); - int length = (int)_memoryStream.Length; + byte[] buffer = _memoryStream!.GetBuffer(); + int length = (int)_memoryStream!.Length; _memoryStream = null; if (chunked) { @@ -230,7 +233,7 @@ namespace System.Net { if (_responseStream == null) { - HttpListener listener = _context._listener; + HttpListener? listener = _context._listener; if (listener == null) return new HttpResponseStream(_stream, _context.Response, true); @@ -242,7 +245,7 @@ namespace System.Net private static void OnRead(IAsyncResult ares) { - HttpConnection cnc = (HttpConnection)ares.AsyncState; + HttpConnection cnc = (HttpConnection)ares.AsyncState!; cnc.OnReadInternal(ares); } @@ -253,7 +256,7 @@ namespace System.Net try { nread = _stream.EndRead(ares); - _memoryStream.Write(_buffer, 0, nread); + _memoryStream!.Write(_buffer!, 0, nread); if (_memoryStream.Length > 32768) { SendError(HttpStatusDescription.Get(400), 400); @@ -299,7 +302,7 @@ namespace System.Net Close(true); return; } - HttpListener listener = _context._listener; + HttpListener listener = _context._listener!; if (_lastListener != listener) { RemoveConnection(); @@ -311,7 +314,7 @@ namespace System.Net listener.RegisterContext(_context); return; } - _stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this); + _stream.BeginRead(_buffer!, 0, BufferSize, s_onreadCallback, this); } private void RemoveConnection() @@ -342,7 +345,7 @@ namespace System.Net byte[] buffer = ms.GetBuffer(); int len = (int)ms.Length; int used = 0; - string line; + string? line; while (true) { @@ -359,7 +362,7 @@ namespace System.Net } catch { - _context.ErrorMessage = HttpStatusDescription.Get(400); + _context.ErrorMessage = HttpStatusDescription.Get(400)!; _context.ErrorStatus = 400; return true; } @@ -372,7 +375,7 @@ namespace System.Net if (_inputState == InputState.RequestLine) continue; _currentLine = null; - ms = null; + ms = null!; return true; } @@ -404,7 +407,7 @@ namespace System.Net return false; } - private string ReadLine(byte[] buffer, int offset, int len, ref int used) + private string? ReadLine(byte[] buffer, int offset, int len, ref int used) { if (_currentLine == null) _currentLine = new StringBuilder(128); @@ -428,7 +431,7 @@ namespace System.Net } } - string result = null; + string? result = null; if (_lineState == LineState.LF) { _lineState = LineState.None; @@ -439,14 +442,14 @@ namespace System.Net return result; } - public void SendError(string msg, int status) + public void SendError(string? msg, int status) { try { HttpListenerResponse response = _context.Response; response.StatusCode = status; response.ContentType = "text/html"; - string description = HttpStatusDescription.Get(status); + string? description = HttpStatusDescription.Get(status); string str; if (msg != null) str = string.Format("

{0} ({1})

", description, msg); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs index 7fc69e7..d780424 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs @@ -43,9 +43,9 @@ namespace System.Net private readonly Socket _socket; private readonly Dictionary _unregisteredConnections; private Dictionary _prefixes; - private List _unhandledPrefixes; // host = '*' - private List _allPrefixes; // host = '+' - private X509Certificate _cert; + private List? _unhandledPrefixes; // host = '*' + private List? _allPrefixes; // host = '+' + private X509Certificate? _cert; private bool _secure; public HttpEndPointListener(HttpListener listener, IPAddress addr, int port, bool secure) @@ -102,9 +102,9 @@ namespace System.Net private static void ProcessAccept(SocketAsyncEventArgs args) { - HttpEndPointListener epl = (HttpEndPointListener)args.UserToken; + HttpEndPointListener epl = (HttpEndPointListener)args.UserToken!; - Socket accepted = args.SocketError == SocketError.Success ? args.AcceptSocket : null; + Socket? accepted = args.SocketError == SocketError.Success ? args.AcceptSocket : null; epl.Accept(args); if (accepted == null) @@ -119,7 +119,7 @@ namespace System.Net HttpConnection conn; try { - conn = new HttpConnection(accepted, epl, epl._secure, epl._cert); + conn = new HttpConnection(accepted, epl, epl._secure, epl._cert!); } catch { @@ -134,7 +134,7 @@ namespace System.Net conn.BeginReadRequest(); } - private static void OnAccept(object sender, SocketAsyncEventArgs e) + private static void OnAccept(object? sender, SocketAsyncEventArgs e) { ProcessAccept(e); } @@ -150,8 +150,8 @@ namespace System.Net public bool BindContext(HttpListenerContext context) { HttpListenerRequest req = context.Request; - ListenerPrefix prefix; - HttpListener listener = SearchListener(req.Url, out prefix); + ListenerPrefix? prefix; + HttpListener? listener = SearchListener(req.Url, out prefix); if (listener == null) return false; @@ -165,10 +165,10 @@ namespace System.Net if (context == null || context.Request == null) return; - context._listener.UnregisterContext(context); + context._listener!.UnregisterContext(context); } - private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix) + private HttpListener? SearchListener(Uri? uri, out ListenerPrefix? prefix) { prefix = null; if (uri == null) @@ -179,7 +179,7 @@ namespace System.Net string path = WebUtility.UrlDecode(uri.AbsolutePath); string pathSlash = path[path.Length - 1] == '/' ? path : path + "/"; - HttpListener bestMatch = null; + HttpListener? bestMatch = null; int bestLength = -1; if (host != null && host != "") @@ -187,7 +187,7 @@ namespace System.Net Dictionary localPrefixes = _prefixes; foreach (ListenerPrefix p in localPrefixes.Keys) { - string ppath = p.Path; + string ppath = p.Path!; if (ppath.Length < bestLength) continue; @@ -205,7 +205,7 @@ namespace System.Net return bestMatch; } - List list = _unhandledPrefixes; + List? list = _unhandledPrefixes; bestMatch = MatchFromList(host, path, list, out prefix); if (path != pathSlash && bestMatch == null) @@ -226,18 +226,18 @@ namespace System.Net return null; } - private HttpListener MatchFromList(string host, string path, List list, out ListenerPrefix prefix) + private HttpListener? MatchFromList(string? host, string path, List? list, out ListenerPrefix? prefix) { prefix = null; if (list == null) return null; - HttpListener bestMatch = null; + HttpListener? bestMatch = null; int bestLength = -1; foreach (ListenerPrefix p in list) { - string ppath = p.Path; + string ppath = p.Path!; if (ppath.Length < bestLength) continue; @@ -288,7 +288,7 @@ namespace System.Net if (_prefixes.Count > 0) return; - List list = _unhandledPrefixes; + List? list = _unhandledPrefixes; if (list != null && list.Count > 0) return; @@ -315,7 +315,7 @@ namespace System.Net public void AddPrefix(ListenerPrefix prefix, HttpListener listener) { - List current; + List? current; List future; if (prefix.Host == "*") { @@ -356,7 +356,7 @@ namespace System.Net public void RemovePrefix(ListenerPrefix prefix, HttpListener listener) { - List current; + List? current; List future; if (prefix.Host == "*") { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs index c14013a..cf3dd38 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs @@ -95,14 +95,14 @@ namespace System.Net if (lp.Host != "*" && lp.Host != "+" && Uri.CheckHostName(lp.Host) == UriHostNameType.Unknown) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_listener_host); - if (lp.Path.Contains('%')) + if (lp.Path!.Contains('%')) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_invalid_path); if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_invalid_path); // listens on all the interfaces if host name cannot be parsed by IPAddress. - HttpEndPointListener epl = GetEPListener(lp.Host, lp.Port, listener, lp.Secure); + HttpEndPointListener epl = GetEPListener(lp.Host!, lp.Port, listener, lp.Secure); epl.AddPrefix(lp, listener); } @@ -133,7 +133,7 @@ namespace System.Net } } - Dictionary p = null; + Dictionary? p = null; if (s_ipEndPoints.ContainsKey(addr)) { p = s_ipEndPoints[addr]; @@ -144,7 +144,7 @@ namespace System.Net s_ipEndPoints[addr] = p; } - HttpEndPointListener epl = null; + HttpEndPointListener? epl = null; if (p.ContainsKey(port)) { epl = p[port]; @@ -169,7 +169,7 @@ namespace System.Net { lock ((s_ipEndPoints as ICollection).SyncRoot) { - Dictionary p = null; + Dictionary? p = null; p = s_ipEndPoints[ep.Address]; p.Remove(ep.Port); if (p.Count == 0) @@ -202,13 +202,13 @@ namespace System.Net private static void RemovePrefixInternal(string prefix, HttpListener listener) { ListenerPrefix lp = new ListenerPrefix(prefix); - if (lp.Path.Contains('%')) + if (lp.Path!.Contains('%')) return; if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1) return; - HttpEndPointListener epl = GetEPListener(lp.Host, lp.Port, listener, lp.Secure); + HttpEndPointListener epl = GetEPListener(lp.Host!, lp.Port, listener, lp.Secure); epl.RemovePrefix(lp, listener); } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs index d595af0..48f0f55 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs @@ -16,7 +16,7 @@ namespace System.Net return new SslStream(innerStream, ownsStream, callback); } - internal X509Certificate LoadCertificateAndKey(IPAddress addr, int port) + internal X509Certificate? LoadCertificateAndKey(IPAddress addr, int port) { // TODO https://github.com/dotnet/runtime/issues/19752: Implement functionality to read SSL certificate. return null; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs index 02a747e..3839b27 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs @@ -192,7 +192,7 @@ namespace System.Net _listenerContexts[context] = context; } - ListenerAsyncResult ares = null; + ListenerAsyncResult? ares = null; lock ((_asyncWaitQueue as ICollection).SyncRoot) { if (_asyncWaitQueue.Count == 0) @@ -257,7 +257,7 @@ namespace System.Net } } - private HttpListenerContext GetContextFromQueue() + private HttpListenerContext? GetContextFromQueue() { lock ((_contextQueue as ICollection).SyncRoot) { @@ -273,7 +273,7 @@ namespace System.Net } } - public IAsyncResult BeginGetContext(AsyncCallback callback, object state) + public IAsyncResult BeginGetContext(AsyncCallback? callback, object? state) { CheckDisposed(); if (_state != State.Started) @@ -288,7 +288,7 @@ namespace System.Net { lock ((_contextQueue as ICollection).SyncRoot) { - HttpListenerContext ctx = GetContextFromQueue(); + HttpListenerContext? ctx = GetContextFromQueue(); if (ctx != null) { ares.Complete(ctx, true); @@ -310,7 +310,7 @@ namespace System.Net throw new ArgumentNullException(nameof(asyncResult)); } - ListenerAsyncResult ares = asyncResult as ListenerAsyncResult; + ListenerAsyncResult? ares = asyncResult as ListenerAsyncResult; if (ares == null || !ReferenceEquals(this, ares._parent)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -332,7 +332,7 @@ namespace System.Net _asyncWaitQueue.RemoveAt(idx); } - HttpListenerContext context = ares.GetContext(); + HttpListenerContext context = ares.GetContext()!; context.ParseAuthentication(context.AuthenticationSchemes); return context; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs index b771a24..8abb640 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Net.WebSockets; using System.Security.Principal; using System.Text; @@ -23,7 +24,7 @@ namespace System.Net internal int ErrorStatus { get; set; } - internal string ErrorMessage { get; set; } + internal string? ErrorMessage { get; set; } internal bool HaveError => ErrorMessage != null; @@ -34,7 +35,7 @@ namespace System.Net if (expectedSchemes == AuthenticationSchemes.Anonymous) return; - string header = Request.Headers[HttpKnownHeaderNames.Authorization]; + string? header = Request.Headers[HttpKnownHeaderNames.Authorization]; if (string.IsNullOrEmpty(header)) return; @@ -44,8 +45,8 @@ namespace System.Net } } - internal IPrincipal ParseBasicAuthentication(string authData) => - TryParseBasicAuth(authData, out HttpStatusCode errorCode, out string username, out string password) ? + internal IPrincipal? ParseBasicAuthentication(string authData) => + TryParseBasicAuth(authData, out HttpStatusCode errorCode, out string? username, out string? password) ? new GenericPrincipal(new HttpListenerBasicIdentity(username, password), Array.Empty()) : null; @@ -54,7 +55,7 @@ namespace System.Net header[5] == ' ' && string.Compare(header, 0, AuthenticationTypes.Basic, 0, 5, StringComparison.OrdinalIgnoreCase) == 0; - internal static bool TryParseBasicAuth(string headerValue, out HttpStatusCode errorCode, out string username, out string password) + internal static bool TryParseBasicAuth(string headerValue, out HttpStatusCode errorCode, [NotNullWhen(true)] out string? username, [NotNullWhen(true)] out string? password) { errorCode = HttpStatusCode.OK; username = password = null; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs index b1ca677..d18b621 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs @@ -31,6 +31,7 @@ // using System.Collections.Specialized; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Security.Authentication.ExtendedProtection; @@ -43,7 +44,7 @@ namespace System.Net { private class Context : TransportContext { - public override ChannelBinding GetChannelBinding(ChannelBindingKind kind) + public override ChannelBinding? GetChannelBinding(ChannelBindingKind kind) { if (kind != ChannelBindingKind.Endpoint) { @@ -57,8 +58,8 @@ namespace System.Net private long _contentLength; private bool _clSet; private WebHeaderCollection _headers; - private string _method; - private Stream _inputStream; + private string? _method; + private Stream? _inputStream; private HttpListenerContext _context; private bool _isChunked; @@ -176,8 +177,9 @@ namespace System.Net } string path; - Uri raw_uri = null; - if (MaybeUri(_rawUrl.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri)) + Uri? raw_uri = null; + Debug.Assert(_rawUrl != null); + if (MaybeUri(_rawUrl!.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri)) path = raw_uri.PathAndQuery; else path = _rawUrl; @@ -192,7 +194,7 @@ namespace System.Net if (colon >= 0) host = host.Substring(0, colon); - string base_uri = string.Format("{0}://{1}:{2}", RequestScheme, host, LocalEndPoint.Port); + string base_uri = string.Format("{0}://{1}:{2}", RequestScheme, host, LocalEndPoint!.Port); if (!Uri.TryCreate(base_uri + path, UriKind.Absolute, out _requestUri)) { @@ -205,7 +207,7 @@ namespace System.Net if (_version >= HttpVersion.Version11) { - string t_encoding = Headers[HttpKnownHeaderNames.TransferEncoding]; + string? t_encoding = Headers[HttpKnownHeaderNames.TransferEncoding]; _isChunked = (t_encoding != null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase)); // 'identity' is not valid! if (t_encoding != null && !_isChunked) @@ -321,14 +323,14 @@ namespace System.Net } } - private X509Certificate2 GetClientCertificateCore() => ClientCertificate = _context.Connection.ClientCertificate; + private X509Certificate2? GetClientCertificateCore() => ClientCertificate = _context.Connection.ClientCertificate; private int GetClientCertificateErrorCore() { HttpConnection cnc = _context.Connection; if (cnc.ClientCertificate == null) return 0; - int[] errors = cnc.ClientCertificateErrors; + int[]? errors = cnc.ClientCertificateErrors; if (errors != null && errors.Length > 0) return errors[0]; return 0; @@ -349,7 +351,7 @@ namespace System.Net public NameValueCollection Headers => _headers; - public string HttpMethod => _method; + public string? HttpMethod => _method; public Stream InputStream { @@ -371,9 +373,9 @@ namespace System.Net public bool IsSecureConnection => _context.Connection.IsSecure; - public IPEndPoint LocalEndPoint => _context.Connection.LocalEndPoint; + public IPEndPoint? LocalEndPoint => _context.Connection.LocalEndPoint; - public IPEndPoint RemoteEndPoint => _context.Connection.RemoteEndPoint; + public IPEndPoint? RemoteEndPoint => _context.Connection.RemoteEndPoint; public Guid RequestTraceIdentifier { get; } = Guid.NewGuid(); @@ -389,12 +391,12 @@ namespace System.Net return asyncResult; } - public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) + public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); - GetClientCertificateAsyncResult clientCertAsyncResult = asyncResult as GetClientCertificateAsyncResult; + GetClientCertificateAsyncResult? clientCertAsyncResult = asyncResult as GetClientCertificateAsyncResult; if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -405,14 +407,14 @@ namespace System.Net } clientCertAsyncResult.EndCalled = true; - return (X509Certificate2)clientCertAsyncResult.Result; + return (X509Certificate2?)clientCertAsyncResult.Result; } - public string ServiceName => null; + public string? ServiceName => null; public TransportContext TransportContext => new Context(); - private Uri RequestUri => _requestUri; + private Uri? RequestUri => _requestUri; private bool SupportsWebSockets => true; private class GetClientCertificateAsyncResult : LazyAsyncResult diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs index ff7a1954..504c2ca 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs @@ -53,7 +53,7 @@ namespace System.Net { if (_responseStream == null) { - _responseStream = _httpContext.Connection.GetResponseStream(); + _responseStream = _httpContext!.Connection.GetResponseStream(); } } @@ -111,7 +111,7 @@ namespace System.Net private void Close(bool force) { Disposed = true; - _httpContext.Connection.Close(force); + _httpContext!.Connection.Close(force); } public void Close(byte[] responseEntity, bool willBlock) @@ -143,7 +143,7 @@ namespace System.Net { OutputStream.BeginWrite(responseEntity, 0, responseEntity.Length, iar => { - var thisRef = (HttpListenerResponse)iar.AsyncState; + var thisRef = (HttpListenerResponse)iar.AsyncState!; try { thisRef.OutputStream.EndWrite(iar); @@ -192,7 +192,7 @@ namespace System.Net _boundaryType = BoundaryType.Chunked; } - if (CanSendResponseBody(_httpContext.Response.StatusCode)) + if (CanSendResponseBody(_httpContext!.Response.StatusCode)) { _contentLength = -1; } @@ -207,7 +207,7 @@ namespace System.Net { if (_boundaryType != BoundaryType.ContentLength && closing) { - _contentLength = CanSendResponseBody(_httpContext.Response.StatusCode) ? -1 : 0; + _contentLength = CanSendResponseBody(_httpContext!.Response.StatusCode) ? -1 : 0; } if (_boundaryType == BoundaryType.ContentLength) @@ -232,7 +232,7 @@ namespace System.Net if (!conn_close) { - conn_close = !_httpContext.Request.KeepAlive; + conn_close = !_httpContext!.Request.KeepAlive; } // They sent both KeepAlive: true and Connection: close @@ -247,7 +247,7 @@ namespace System.Net _webHeaders.Set(HttpKnownHeaderNames.TransferEncoding, HttpHeaderStrings.Chunked); } - int reuses = _httpContext.Connection.Reuses; + int reuses = _httpContext!.Connection.Reuses; if (reuses >= 100) { _forceCloseChunked = true; @@ -302,7 +302,7 @@ namespace System.Net for (int i = 0; i < headers.Count; i++) { string key = headers.GetKey(i); - string[] values = headers.GetValues(i); + string[] values = headers.GetValues(i)!; int startingLength = sb.Length; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs index 72a2749..8a9acf3 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs @@ -125,7 +125,7 @@ namespace System.Net return nread; } - protected virtual IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state) + protected virtual IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback? cback, object? state) { if (size == 0 || _closed) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs index 269f83c..769a51f 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs @@ -54,8 +54,8 @@ namespace System.Net private void DisposeCore() { - byte[] bytes = null; - MemoryStream ms = GetHeaders(true); + byte[]? bytes = null; + MemoryStream? ms = GetHeaders(true); bool chunked = _response.SendChunked; if (_stream.CanWrite) { @@ -95,7 +95,7 @@ namespace System.Net if (_stream.CanWrite) { - MemoryStream ms = GetHeaders(closing: false, isWebSocketHandshake: true); + MemoryStream ms = GetHeaders(closing: false, isWebSocketHandshake: true)!; bool chunked = _response.SendChunked; long start = ms.Position; @@ -111,7 +111,7 @@ namespace System.Net } } - private MemoryStream GetHeaders(bool closing, bool isWebSocketHandshake = false) + private MemoryStream? GetHeaders(bool closing, bool isWebSocketHandshake = false) { // SendHeaders works on shared headers lock (_response._headersLock) @@ -171,8 +171,8 @@ namespace System.Net if (size == 0) return; - byte[] bytes = null; - MemoryStream ms = GetHeaders(false); + byte[]? bytes = null; + MemoryStream? ms = GetHeaders(false); bool chunked = _response.SendChunked; if (ms != null) { @@ -204,7 +204,7 @@ namespace System.Net InternalWrite(s_crlf, 0, 2); } - private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state) + private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback? cback, object? state) { if (_closed) { @@ -215,8 +215,8 @@ namespace System.Net return ares; } - byte[] bytes = null; - MemoryStream ms = GetHeaders(false); + byte[]? bytes = null; + MemoryStream? ms = GetHeaders(false); bool chunked = _response.SendChunked; if (ms != null) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs index eea8e6b..a92059b 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs @@ -36,17 +36,17 @@ namespace System.Net internal class HttpStreamAsyncResult : IAsyncResult { private object _locker = new object(); - private ManualResetEvent _handle; + private ManualResetEvent? _handle; private bool _completed; internal readonly object _parent; - internal byte[] _buffer; + internal byte[]? _buffer; internal int _offset; internal int _count; - internal AsyncCallback _callback; - internal object _state; + internal AsyncCallback? _callback; + internal object? _state; internal int _synchRead; - internal Exception _error; + internal Exception? _error; internal bool _endCalled; internal HttpStreamAsyncResult(object parent) @@ -76,7 +76,7 @@ namespace System.Net } } - public object AsyncState + public object? AsyncState { get { return _state; } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs index 2cc49a1..605a26f 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs @@ -37,20 +37,20 @@ namespace System.Net { internal class ListenerAsyncResult : IAsyncResult { - private ManualResetEvent _handle; + private ManualResetEvent? _handle; private bool _synch; private bool _completed; - private AsyncCallback _cb; - private object _state; - private Exception _exception; - private HttpListenerContext _context; + private AsyncCallback? _cb; + private object? _state; + private Exception? _exception; + private HttpListenerContext? _context; private object _locker = new object(); - private ListenerAsyncResult _forward; + private ListenerAsyncResult? _forward; internal readonly HttpListener _parent; internal bool _endCalled; internal bool _inGet; - public ListenerAsyncResult(HttpListener parent, AsyncCallback cb, object state) + public ListenerAsyncResult(HttpListener parent, AsyncCallback? cb, object? state) { _parent = parent; _cb = cb; @@ -78,10 +78,10 @@ namespace System.Net } } - private static WaitCallback s_invokeCB = new WaitCallback(InvokeCallback); + private static WaitCallback s_invokeCB = new WaitCallback(InvokeCallback!); private static void InvokeCallback(object o) { - ListenerAsyncResult ares = (ListenerAsyncResult)o; + ListenerAsyncResult ares = (ListenerAsyncResult)o!; if (ares._forward != null) { InvokeCallback(ares._forward); @@ -89,7 +89,7 @@ namespace System.Net } try { - ares._cb(ares); + ares._cb!(ares); } catch { @@ -115,7 +115,7 @@ namespace System.Net bool authFailure = false; try { - context.AuthenticationSchemes = context._listener.SelectAuthenticationScheme(context); + context.AuthenticationSchemes = context._listener!.SelectAuthenticationScheme(context); } catch (OutOfMemoryException oom) { @@ -138,17 +138,17 @@ namespace System.Net else if (context.AuthenticationSchemes == AuthenticationSchemes.Basic) { HttpStatusCode errorCode = HttpStatusCode.Unauthorized; - string authHeader = context.Request.Headers["Authorization"]; + string? authHeader = context.Request.Headers["Authorization"]; if (authHeader == null || !HttpListenerContext.IsBasicHeader(authHeader) || authHeader.Length < AuthenticationTypes.Basic.Length + 2 || - !HttpListenerContext.TryParseBasicAuth(authHeader.Substring(AuthenticationTypes.Basic.Length + 1), out errorCode, out string _, out string __)) + !HttpListenerContext.TryParseBasicAuth(authHeader.Substring(AuthenticationTypes.Basic.Length + 1), out errorCode, out _, out _)) { authFailure = true; context.Response.StatusCode = (int)errorCode; if (errorCode == HttpStatusCode.Unauthorized) { - context.Response.Headers["WWW-Authenticate"] = context.AuthenticationSchemes + " realm=\"" + context._listener.Realm + "\""; + context.Response.Headers["WWW-Authenticate"] = context.AuthenticationSchemes + " realm=\"" + context._listener!.Realm + "\""; } } } @@ -156,7 +156,7 @@ namespace System.Net if (authFailure) { context.Response.OutputStream.Close(); - IAsyncResult ares = context._listener.BeginGetContext(_cb, _state); + IAsyncResult ares = context._listener!.BeginGetContext(_cb, _state); _forward = (ListenerAsyncResult)ares; lock (_forward._locker) { @@ -185,7 +185,7 @@ namespace System.Net } } - internal HttpListenerContext GetContext() + internal HttpListenerContext? GetContext() { if (_forward != null) { @@ -200,7 +200,7 @@ namespace System.Net return _context; } - public object AsyncState + public object? AsyncState { get { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs index a0b19d6..576e345 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs @@ -34,12 +34,12 @@ namespace System.Net internal sealed class ListenerPrefix { private string _original; - private string _host; + private string? _host; private ushort _port; - private string _path; + private string? _path; private bool _secure; - private IPAddress[] _addresses; - internal HttpListener _listener; + private IPAddress[]? _addresses; + internal HttpListener? _listener; public ListenerPrefix(string prefix) { @@ -52,7 +52,7 @@ namespace System.Net return _original; } - public IPAddress[] Addresses + public IPAddress[]? Addresses { get { return _addresses; } set { _addresses = value; } @@ -62,7 +62,7 @@ namespace System.Net get { return _secure; } } - public string Host + public string? Host { get { return _host; } } @@ -72,15 +72,15 @@ namespace System.Net get { return _port; } } - public string Path + public string? Path { get { return _path; } } // Equals and GetHashCode are required to detect duplicates in HttpListenerPrefixCollection. - public override bool Equals(object o) + public override bool Equals(object? o) { - ListenerPrefix other = o as ListenerPrefix; + ListenerPrefix? other = o as ListenerPrefix; if (other == null) return false; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs index 2f7d076..bd3e392 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs @@ -22,12 +22,12 @@ namespace System.Net.WebSockets HttpListenerRequest request = context.Request; ValidateWebSocketHeaders(context); - string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; + string? secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; // Optional for non-browser client - string origin = request.Headers[HttpKnownHeaderNames.Origin]; + string? origin = request.Headers[HttpKnownHeaderNames.Origin]; - string[] secWebSocketProtocols = null; + string[]? secWebSocketProtocols = null; string outgoingSecWebSocketProtocolString; bool shouldSendSecWebSocketProtocolHeader = ProcessWebSocketProtocolHeader( @@ -42,7 +42,7 @@ namespace System.Net.WebSockets } // negotiate the websocket key return value - string secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; + string? secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey); response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade); @@ -50,9 +50,9 @@ namespace System.Net.WebSockets response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept); response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101 - response.StatusDescription = HttpStatusDescription.Get(HttpStatusCode.SwitchingProtocols); + response.StatusDescription = HttpStatusDescription.Get(HttpStatusCode.SwitchingProtocols)!; - HttpResponseStream responseStream = response.OutputStream as HttpResponseStream; + HttpResponseStream responseStream = (response.OutputStream as HttpResponseStream)!; // Send websocket handshake headers await responseStream.WriteWebSocketHandshakeHeadersAsync().ConfigureAwait(false); @@ -60,17 +60,17 @@ namespace System.Net.WebSockets WebSocket webSocket = WebSocket.CreateFromStream(context.Connection.ConnectedStream, isServer:true, subProtocol, keepAliveInterval); HttpListenerWebSocketContext webSocketContext = new HttpListenerWebSocketContext( - request.Url, + request.Url!, request.Headers, request.Cookies, - context.User, + context.User!, request.IsAuthenticated, request.IsLocal, request.IsSecureConnection, - origin, + origin!, secWebSocketProtocols != null ? secWebSocketProtocols : Array.Empty(), - secWebSocketVersion, - secWebSocketKey, + secWebSocketVersion!, + secWebSocketKey!, webSocket); return webSocketContext; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs index 15cd3db..9c92cf2 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs @@ -12,7 +12,7 @@ namespace System.Net internal class ServiceNameStore { private readonly List _serviceNames; - private ServiceNameCollection _serviceNameCollection; + private ServiceNameCollection? _serviceNameCollection; public ServiceNameCollection ServiceNames { @@ -32,7 +32,7 @@ namespace System.Net _serviceNameCollection = null; // set only when needed (due to expensive item-by-item copy) } - private static string NormalizeServiceName(string inputServiceName) + private static string? NormalizeServiceName(string? inputServiceName) { if (string.IsNullOrWhiteSpace(inputServiceName)) { @@ -108,7 +108,7 @@ namespace System.Net // Now we have a valid DNS host, normalize it. - Uri constructedUri; + Uri? constructedUri; // This shouldn't fail, but we need to avoid any unexpected exceptions on this code path. if (!Uri.TryCreate(Uri.UriSchemeHttp + Uri.SchemeDelimiter + host, UriKind.Absolute, out constructedUri)) { @@ -132,7 +132,7 @@ namespace System.Net private bool AddSingleServiceName(string spn) { - spn = NormalizeServiceName(spn); + spn = NormalizeServiceName(spn)!; if (Contains(spn)) { return false; @@ -177,13 +177,13 @@ namespace System.Net { Debug.Assert(!string.IsNullOrEmpty(uriPrefix)); - string newServiceName = BuildSimpleServiceName(uriPrefix); + string? newServiceName = BuildSimpleServiceName(uriPrefix); newServiceName = NormalizeServiceName(newServiceName); bool needToRemove = Contains(newServiceName); if (needToRemove) { - _serviceNames.Remove(newServiceName); + _serviceNames.Remove(newServiceName!); _serviceNameCollection = null; //invalidate (readonly) ServiceNameCollection } @@ -203,7 +203,7 @@ namespace System.Net } // Assumes already normalized - private bool Contains(string newServiceName) + private bool Contains(string? newServiceName) { if (newServiceName == null) { @@ -227,7 +227,7 @@ namespace System.Net _serviceNameCollection = null; //invalidate (readonly) ServiceNameCollection } - private string ExtractHostname(string uriPrefix, bool allowInvalidUriStrings) + private string? ExtractHostname(string uriPrefix, bool allowInvalidUriStrings) { if (Uri.IsWellFormedUriString(uriPrefix, UriKind.Absolute)) { @@ -264,9 +264,9 @@ namespace System.Net return null; } - public string BuildSimpleServiceName(string uriPrefix) + public string? BuildSimpleServiceName(string uriPrefix) { - string hostname = ExtractHostname(uriPrefix, false); + string? hostname = ExtractHostname(uriPrefix, false); if (hostname != null) { @@ -280,9 +280,9 @@ namespace System.Net public string[] BuildServiceNames(string uriPrefix) { - string hostname = ExtractHostname(uriPrefix, true); + string hostname = ExtractHostname(uriPrefix, true)!; - IPAddress ipAddress = null; + IPAddress? ipAddress = null; if (string.Equals(hostname, "*", StringComparison.OrdinalIgnoreCase) || string.Equals(hostname, "+", StringComparison.OrdinalIgnoreCase) || IPAddress.TryParse(hostname, out ipAddress)) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs index 7f6ea23..3113405 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs @@ -49,7 +49,7 @@ namespace System.Net.WebSockets _cookieCollection.Add(cookieCollection); _headers = new NameValueCollection(headers); - _user = CopyPrincipal(user); + _user = CopyPrincipal(user)!; _requestUri = requestUri; _isAuthenticated = isAuthenticated; @@ -86,7 +86,7 @@ namespace System.Net.WebSockets public override WebSocket WebSocket => _webSocket; - private static IPrincipal CopyPrincipal(IPrincipal user) + private static IPrincipal? CopyPrincipal(IPrincipal user) { if (user != null) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs index f89b58f..56a11e4 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs @@ -16,7 +16,7 @@ namespace System.Net.WebSockets internal const int DefaultClientSendBufferSize = 16 * 1024; [SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 used only for hashing purposes, not for crypto.")] - internal static string GetSecWebSocketAcceptString(string secWebSocketKey) + internal static string GetSecWebSocketAcceptString(string? secWebSocketKey) { string acceptString = string.Concat(secWebSocketKey, HttpWebSocket.SecWebSocketKeyGuid); byte[] toHash = Encoding.UTF8.GetBytes(acceptString); @@ -27,7 +27,7 @@ namespace System.Net.WebSockets } // return value here signifies if a Sec-WebSocket-Protocol header should be returned by the server. - internal static bool ProcessWebSocketProtocolHeader(string clientSecWebSocketProtocol, + internal static bool ProcessWebSocketProtocolHeader(string? clientSecWebSocketProtocol, string subProtocol, out string acceptProtocol) { @@ -142,7 +142,7 @@ namespace System.Net.WebSockets context.Request.Headers[HttpKnownHeaderNames.Upgrade])); } - string secWebSocketVersion = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; + string? secWebSocketVersion = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; if (string.IsNullOrEmpty(secWebSocketVersion)) { throw new WebSocketException(WebSocketError.HeaderError, @@ -160,14 +160,14 @@ namespace System.Net.WebSockets SupportedVersion)); } - string secWebSocketKey = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; + string? secWebSocketKey = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; bool isSecWebSocketKeyInvalid = string.IsNullOrWhiteSpace(secWebSocketKey); if (!isSecWebSocketKeyInvalid) { try { // key must be 16 bytes then base64-encoded - isSecWebSocketKeyInvalid = Convert.FromBase64String(secWebSocketKey).Length != 16; + isSecWebSocketKeyInvalid = Convert.FromBase64String(secWebSocketKey!).Length != 16; } catch { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs index 6ebe7a3..8af3aa4 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs @@ -10,7 +10,7 @@ namespace System.Net internal sealed unsafe class AsyncRequestContext : RequestContextBase { private NativeOverlapped* _nativeOverlapped; - private ThreadPoolBoundHandle _boundHandle; + private ThreadPoolBoundHandle? _boundHandle; private readonly ListenerAsyncResult _result; #if DEBUG @@ -46,7 +46,7 @@ namespace System.Net NativeOverlapped* nativeOverlapped = _nativeOverlapped; _nativeOverlapped = null; - _boundHandle.FreeNativeOverlapped(nativeOverlapped); + _boundHandle!.FreeNativeOverlapped(nativeOverlapped); } #if DEBUG @@ -75,7 +75,7 @@ namespace System.Net NativeOverlapped* nativeOverlapped = _nativeOverlapped; _nativeOverlapped = null; - _boundHandle.FreeNativeOverlapped(nativeOverlapped); + _boundHandle!.FreeNativeOverlapped(nativeOverlapped); } } @@ -89,7 +89,7 @@ namespace System.Net #if DEBUG DebugRefCountReleaseNativeOverlapped(); #endif - _boundHandle.FreeNativeOverlapped(_nativeOverlapped); + _boundHandle!.FreeNativeOverlapped(_nativeOverlapped); } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs index 30df21a..20e1fad 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs @@ -10,20 +10,20 @@ namespace System.Net // TODO https://github.com/dotnet/runtime/issues/19348 internal static class CookieExtensions { - private static Func s_toServerStringFunc; + private static Func? s_toServerStringFunc; public static string ToServerString(this Cookie cookie) { - s_toServerStringFunc ??= (Func)typeof(Cookie).GetMethod("ToServerString", BindingFlags.Instance | BindingFlags.NonPublic).CreateDelegate(typeof(Func)); + s_toServerStringFunc ??= (Func)typeof(Cookie).GetMethod("ToServerString", BindingFlags.Instance | BindingFlags.NonPublic)!.CreateDelegate(typeof(Func)); Debug.Assert(s_toServerStringFunc != null, "Reflection failed for Cookie.ToServerString()."); return s_toServerStringFunc(cookie); } - private static Func s_cloneFunc; + private static Func? s_cloneFunc; public static Cookie Clone(this Cookie cookie) { - s_cloneFunc ??= (Func)typeof(Cookie).GetMethod("Clone", BindingFlags.Instance | BindingFlags.NonPublic).CreateDelegate(typeof(Func)); + s_cloneFunc ??= (Func)typeof(Cookie).GetMethod("Clone", BindingFlags.Instance | BindingFlags.NonPublic)!.CreateDelegate(typeof(Func)); Debug.Assert(s_cloneFunc != null, "Reflection failed for Cookie.Clone()."); return s_cloneFunc(cookie); } @@ -37,11 +37,11 @@ namespace System.Net Default = Rfc2109 } - private static Func s_getVariantFunc; + private static Func? s_getVariantFunc; public static bool IsRfc2965Variant(this Cookie cookie) { - s_getVariantFunc ??= (Func)typeof(Cookie).GetProperty("Variant", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true).CreateDelegate(typeof(Func)); + s_getVariantFunc ??= (Func)typeof(Cookie).GetProperty("Variant", BindingFlags.Instance | BindingFlags.NonPublic)!.GetGetMethod(true)!.CreateDelegate(typeof(Func)); Debug.Assert(s_getVariantFunc != null, "Reflection failed for Cookie.Variant."); return s_getVariantFunc(cookie) == CookieVariant.Rfc2965; } @@ -49,11 +49,11 @@ namespace System.Net internal static class CookieCollectionExtensions { - private static Func s_internalAddFunc; + private static Func? s_internalAddFunc; public static int InternalAdd(this CookieCollection cookieCollection, Cookie cookie, bool isStrict) { - s_internalAddFunc ??= (Func)typeof(CookieCollection).GetMethod("InternalAdd", BindingFlags.Instance | BindingFlags.NonPublic).CreateDelegate(typeof(Func)); + s_internalAddFunc ??= (Func)typeof(CookieCollection).GetMethod("InternalAdd", BindingFlags.Instance | BindingFlags.NonPublic)!.CreateDelegate(typeof(Func)); Debug.Assert(s_internalAddFunc != null, "Reflection failed for CookieCollection.InternalAdd()."); return s_internalAddFunc(cookieCollection, cookie, isStrict); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs index 75be134..febae88 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs @@ -41,15 +41,15 @@ namespace System.Net (byte) 'e', (byte) 'n', (byte) 't', (byte) 'i', (byte) 'c', (byte) 'a', (byte) 't', (byte) 'e' }; - private HttpListenerSession _currentSession; + private HttpListenerSession? _currentSession; private bool _unsafeConnectionNtlmAuthentication; - private HttpServerSessionHandle _serverSessionHandle; + private HttpServerSessionHandle? _serverSessionHandle; private ulong _urlGroupId; private bool _V2Initialized; - private Dictionary _disconnectResults; + private Dictionary? _disconnectResults; private void ValidateV2Property() { @@ -312,7 +312,7 @@ namespace System.Net // get delivered to this request queue. Interop.HttpApi.HTTP_BINDING_INFO info = default; info.Flags = Interop.HttpApi.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT; - info.RequestQueueHandle = _currentSession.RequestQueueHandle.DangerousGetHandle(); + info.RequestQueueHandle = _currentSession!.RequestQueueHandle.DangerousGetHandle(); IntPtr infoptr = new IntPtr(&info); @@ -489,8 +489,8 @@ namespace System.Net public HttpListenerContext GetContext() { - SyncRequestContext memoryBlob = null; - HttpListenerContext httpContext = null; + SyncRequestContext? memoryBlob = null; + HttpListenerContext? httpContext = null; bool stoleBlob = false; try @@ -508,7 +508,7 @@ namespace System.Net uint size = 4096; ulong requestId = 0; memoryBlob = new SyncRequestContext((int)size); - HttpListenerSession session = _currentSession; + HttpListenerSession session = _currentSession!; while (true) { @@ -609,7 +609,7 @@ namespace System.Net public IAsyncResult BeginGetContext(AsyncCallback callback, object state) { - ListenerAsyncResult asyncResult = null; + ListenerAsyncResult? asyncResult = null; try { CheckDisposed(); @@ -620,7 +620,7 @@ namespace System.Net // prepare the ListenerAsyncResult object (this will have it's own // event that the user can wait on for IO completion - which means we // need to signal it when IO completes) - asyncResult = new ListenerAsyncResult(_currentSession, state, callback); + asyncResult = new ListenerAsyncResult(_currentSession!, state, callback); uint statusCode = asyncResult.QueueBeginGetContext(); if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_IO_PENDING) @@ -641,7 +641,7 @@ namespace System.Net public HttpListenerContext EndGetContext(IAsyncResult asyncResult) { - HttpListenerContext httpContext = null; + HttpListenerContext? httpContext = null; try { CheckDisposed(); @@ -663,7 +663,7 @@ namespace System.Net if (httpContext == null) { Debug.Assert(castedAsyncResult.Result is Exception, "EndGetContext|The result is neither a HttpListenerContext nor an Exception."); - ExceptionDispatchInfo.Throw(castedAsyncResult.Result as Exception); + ExceptionDispatchInfo.Throw((castedAsyncResult.Result as Exception)!); } } catch (Exception exception) @@ -674,15 +674,15 @@ namespace System.Net return httpContext; } - internal HttpListenerContext HandleAuthentication(HttpListenerSession session, RequestContextBase memoryBlob, out bool stoleBlob) + internal HttpListenerContext? HandleAuthentication(HttpListenerSession session, RequestContextBase memoryBlob, out bool stoleBlob) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "HandleAuthentication() memoryBlob:0x" + ((IntPtr)memoryBlob.RequestBlob).ToString("x")); - string challenge = null; + string? challenge = null; stoleBlob = false; // Some things we need right away. Lift them out now while it's convenient. - string authorizationHeader = Interop.HttpApi.GetKnownHeader(memoryBlob.RequestBlob, (int)HttpRequestHeader.Authorization); + string? authorizationHeader = Interop.HttpApi.GetKnownHeader(memoryBlob.RequestBlob, (int)HttpRequestHeader.Authorization); ulong connectionId = memoryBlob.RequestBlob->ConnectionId; ulong requestId = memoryBlob.RequestBlob->RequestId; bool isSecureConnection = memoryBlob.RequestBlob->pSslInfo != null; @@ -694,13 +694,13 @@ namespace System.Net // previously authenticated. // assurance that we do this only for NTLM/Negotiate is not here, but in the // code that caches WindowsIdentity instances in the Dictionary. - DisconnectAsyncResult disconnectResult; + DisconnectAsyncResult? disconnectResult; DisconnectResults.TryGetValue(connectionId, out disconnectResult); if (UnsafeConnectionNtlmAuthentication) { if (authorizationHeader == null) { - WindowsPrincipal principal = disconnectResult?.AuthenticatedConnection; + WindowsPrincipal? principal = disconnectResult?.AuthenticatedConnection; if (principal != null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Principal: {principal} principal.Identity.Name: {principal.Identity.Name} creating request"); @@ -724,10 +724,10 @@ namespace System.Net // Figure out what schemes we're allowing, what context we have. stoleBlob = true; - HttpListenerContext httpContext = null; - NTAuthentication oldContext = null; - NTAuthentication newContext = null; - NTAuthentication context = null; + HttpListenerContext? httpContext = null; + NTAuthentication? oldContext = null; + NTAuthentication? newContext = null; + NTAuthentication? context = null; AuthenticationSchemes headerScheme = AuthenticationSchemes.None; AuthenticationSchemes authenticationScheme = AuthenticationSchemes; ExtendedProtectionPolicy extendedProtectionPolicy = _extendedProtectionPolicy; @@ -748,7 +748,7 @@ namespace System.Net httpContext = new HttpListenerContext(session, memoryBlob); - AuthenticationSchemeSelector authenticationSelector = _authenticationDelegate; + AuthenticationSchemeSelector? authenticationSelector = _authenticationDelegate; if (authenticationSelector != null) { try @@ -778,7 +778,7 @@ namespace System.Net stoleBlob = false; } - ExtendedProtectionSelector extendedProtectionSelector = _extendedProtectionSelectorDelegate; + ExtendedProtectionSelector? extendedProtectionSelector = _extendedProtectionSelectorDelegate; if (extendedProtectionSelector != null) { extendedProtectionPolicy = extendedProtectionSelector(httpContext.Request); @@ -856,12 +856,13 @@ namespace System.Net else { // Perform Authentication - byte[] bytes = null; - byte[] decodedOutgoingBlob = null; - string outBlob = null; + byte[]? bytes = null; + byte[]? decodedOutgoingBlob = null; + string? outBlob = null; // Find the beginning of the blob. Trust that HTTP.SYS parsed out just our header ok. - for (index++; index < authorizationHeader.Length; index++) + Debug.Assert(authorizationHeader != null); + for (index++; index < authorizationHeader!.Length; index++) { if (authorizationHeader[index] != ' ' && authorizationHeader[index] != '\t' && authorizationHeader[index] != '\r' && authorizationHeader[index] != '\n') @@ -871,9 +872,9 @@ namespace System.Net } string inBlob = index < authorizationHeader.Length ? authorizationHeader.Substring(index) : ""; - IPrincipal principal = null; + IPrincipal? principal = null; SecurityStatusPal statusCodeNew; - ChannelBinding binding; + ChannelBinding? binding; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Performing Authentication headerScheme: {headerScheme}"); switch (headerScheme) { @@ -934,7 +935,7 @@ namespace System.Net { if (context.IsCompleted) { - SecurityContextTokenHandle userContext = null; + SecurityContextTokenHandle? userContext = null; try { if (!CheckSpn(context, isSecureConnection, extendedProtectionPolicy)) @@ -945,7 +946,7 @@ namespace System.Net { httpContext.Request.ServiceName = context.ClientSpecifiedSpn; - SafeDeleteContext securityContext = context.GetContext(out statusCodeNew); + SafeDeleteContext securityContext = context.GetContext(out statusCodeNew)!; if (statusCodeNew.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.Log.IsEnabled()) @@ -1063,7 +1064,7 @@ namespace System.Net { if (NetEventSource.Log.IsEnabled()) { - NetEventSource.Info(this, $"Got principal: {principal}, IdentityName: {principal.Identity.Name} for creating request."); + NetEventSource.Info(this, $"Got principal: {principal}, IdentityName: {principal!.Identity!.Name} for creating request."); } httpContext.SetIdentity(principal, outBlob); @@ -1080,7 +1081,7 @@ namespace System.Net } // if we're not giving a request to the application, we need to send an error - ArrayList challenges = null; + ArrayList? challenges = null; if (httpContext == null) { // If we already have a challenge, just use it. Otherwise put a challenge for each acceptable scheme. @@ -1166,9 +1167,11 @@ namespace System.Net context = null; } - NTAuthentication toClose = oldContext; + NTAuthentication? toClose = oldContext; oldContext = newContext; - disconnectResult.Session = newContext; + // TODO: Can disconnectResult be null here? + Debug.Assert(disconnectResult != null); + disconnectResult!.Session = newContext; if (toClose != null) { @@ -1249,7 +1252,7 @@ namespace System.Net } } - private static void FreeContext(ref HttpListenerContext httpContext, RequestContextBase memoryBlob) + private static void FreeContext(ref HttpListenerContext? httpContext, RequestContextBase memoryBlob) { if (httpContext != null) { @@ -1270,8 +1273,8 @@ namespace System.Net HttpListenerResponse response = context.Response; // We use the cached results from the delegates so that we don't have to call them again here. - NTAuthentication newContext; - ArrayList challenges = BuildChallenge(context.AuthenticationSchemes, request._connectionId, + NTAuthentication? newContext; + ArrayList? challenges = BuildChallenge(context.AuthenticationSchemes, request._connectionId, out newContext, context.ExtendedProtectionPolicy, request.IsSecureConnection); // Setting 401 without setting WWW-Authenticate is a protocol violation @@ -1286,7 +1289,7 @@ namespace System.Net } } - private ChannelBinding GetChannelBinding(HttpListenerSession session, ulong connectionId, bool isSecureConnection, ExtendedProtectionPolicy policy) + private ChannelBinding? GetChannelBinding(HttpListenerSession session, ulong connectionId, bool isSecureConnection, ExtendedProtectionPolicy policy) { if (policy.PolicyEnforcement == PolicyEnforcement.Never) { @@ -1306,7 +1309,7 @@ namespace System.Net return null; } - ChannelBinding result = GetChannelBindingFromTls(session, connectionId); + ChannelBinding? result = GetChannelBindingFromTls(session, connectionId); if (NetEventSource.Log.IsEnabled() && result != null) NetEventSource.Info(this, "GetChannelBindingFromTls returned null even though OS supposedly supports Extended Protection"); @@ -1345,7 +1348,7 @@ namespace System.Net return true; } - string clientSpn = context.ClientSpecifiedSpn; + string? clientSpn = context.ClientSpecifiedSpn; // An empty SPN is only allowed in the WhenSupported case if (string.IsNullOrEmpty(clientSpn)) @@ -1512,7 +1515,7 @@ namespace System.Net error == SecurityStatusPalErrorCode.UnsupportedPreauth; } - private static void AddChallenge(ref ArrayList challenges, string challenge) + private static void AddChallenge(ref ArrayList? challenges, string challenge) { if (challenge != null) { @@ -1529,11 +1532,11 @@ namespace System.Net } } - private ArrayList BuildChallenge(AuthenticationSchemes authenticationScheme, ulong connectionId, - out NTAuthentication newContext, ExtendedProtectionPolicy policy, bool isSecureConnection) + private ArrayList? BuildChallenge(AuthenticationSchemes authenticationScheme, ulong connectionId, + out NTAuthentication? newContext, ExtendedProtectionPolicy policy, bool isSecureConnection) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "AuthenticationScheme:" + authenticationScheme.ToString()); - ArrayList challenges = null; + ArrayList? challenges = null; newContext = null; if ((authenticationScheme & AuthenticationSchemes.Negotiate) != 0) @@ -1554,7 +1557,7 @@ namespace System.Net return challenges; } - private static void RegisterForDisconnectNotification(HttpListenerSession session, ulong connectionId, ref DisconnectAsyncResult disconnectResult) + private static void RegisterForDisconnectNotification(HttpListenerSession session, ulong connectionId, ref DisconnectAsyncResult? disconnectResult) { Debug.Assert(disconnectResult == null); @@ -1593,7 +1596,7 @@ namespace System.Net } } - private static void SendError(HttpListenerSession session, ulong requestId, HttpStatusCode httpStatusCode, ArrayList challenges) + private static void SendError(HttpListenerSession session, ulong requestId, HttpStatusCode httpStatusCode, ArrayList? challenges) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(session.Listener, $"RequestId: {requestId}"); Interop.HttpApi.HTTP_RESPONSE httpResponse = default; @@ -1601,10 +1604,10 @@ namespace System.Net httpResponse.Version.MajorVersion = (ushort)1; httpResponse.Version.MinorVersion = (ushort)1; httpResponse.StatusCode = (ushort)httpStatusCode; - string statusDescription = HttpStatusDescription.Get(httpStatusCode); + string? statusDescription = HttpStatusDescription.Get(httpStatusCode); uint DataWritten = 0; uint statusCode; - byte[] byteReason = Encoding.Default.GetBytes(statusDescription); + byte[] byteReason = Encoding.Default.GetBytes(statusDescription!); fixed (byte* pReason = byteReason) { httpResponse.pReason = (sbyte*)pReason; @@ -1617,8 +1620,8 @@ namespace System.Net (&httpResponse.Headers.KnownHeaders)[(int)HttpResponseHeader.ContentLength].RawValueLength = (ushort)byteContentLength.Length; httpResponse.Headers.UnknownHeaderCount = checked((ushort)(challenges == null ? 0 : challenges.Count)); - GCHandle[] challengeHandles = null; - Interop.HttpApi.HTTP_UNKNOWN_HEADER[] headersArray = null; + GCHandle[]? challengeHandles = null; + Interop.HttpApi.HTTP_UNKNOWN_HEADER[]? headersArray = null; GCHandle headersArrayHandle = default; GCHandle wwwAuthenticateHandle = default; if (httpResponse.Headers.UnknownHeaderCount > 0) @@ -1632,15 +1635,15 @@ namespace System.Net if (httpResponse.Headers.UnknownHeaderCount > 0) { headersArrayHandle = GCHandle.Alloc(headersArray, GCHandleType.Pinned); - httpResponse.Headers.pUnknownHeaders = (Interop.HttpApi.HTTP_UNKNOWN_HEADER*)Marshal.UnsafeAddrOfPinnedArrayElement(headersArray, 0); + httpResponse.Headers.pUnknownHeaders = (Interop.HttpApi.HTTP_UNKNOWN_HEADER*)Marshal.UnsafeAddrOfPinnedArrayElement(headersArray!, 0); wwwAuthenticateHandle = GCHandle.Alloc(s_wwwAuthenticateBytes, GCHandleType.Pinned); sbyte* wwwAuthenticate = (sbyte*)Marshal.UnsafeAddrOfPinnedArrayElement(s_wwwAuthenticateBytes, 0); - for (int i = 0; i < challengeHandles.Length; i++) + for (int i = 0; i < challengeHandles!.Length; i++) { - byte[] byteChallenge = Encoding.Default.GetBytes((string)challenges[i]); + byte[] byteChallenge = Encoding.Default.GetBytes((string)challenges![i]!); challengeHandles[i] = GCHandle.Alloc(byteChallenge, GCHandleType.Pinned); - headersArray[i].pName = wwwAuthenticate; + headersArray![i].pName = wwwAuthenticate; headersArray[i].NameLength = (ushort)s_wwwAuthenticateBytes.Length; headersArray[i].pRawValue = (sbyte*)Marshal.UnsafeAddrOfPinnedArrayElement(byteChallenge, 0); headersArray[i].RawValueLength = checked((ushort)byteChallenge.Length); @@ -1708,7 +1711,7 @@ namespace System.Net return (int)((Interop.HttpApi.HTTP_REQUEST_CHANNEL_BIND_STATUS*)blob)->ChannelTokenSize; } - internal static ChannelBinding GetChannelBindingFromTls(HttpListenerSession session, ulong connectionId) + internal static ChannelBinding? GetChannelBindingFromTls(HttpListenerSession session, ulong connectionId) { // +128 since a CBT is usually <128 thus we need to call HRCC just once. If the CBT // is >128 we will get ERROR_MORE_DATA and call again @@ -1716,8 +1719,8 @@ namespace System.Net Debug.Assert(size > 0); - byte[] blob = null; - Interop.HttpApi.SafeLocalFreeChannelBinding token = null; + byte[]? blob = null; + Interop.HttpApi.SafeLocalFreeChannelBinding? token = null; uint bytesReceived = 0; uint statusCode; @@ -1786,8 +1789,8 @@ namespace System.Net private readonly NativeOverlapped* _nativeOverlapped; private int _ownershipState; // 0 = normal, 1 = in HandleAuthentication(), 2 = disconnected, 3 = cleaned up - private WindowsPrincipal _authenticatedConnection; - private NTAuthentication _session; + private WindowsPrincipal? _authenticatedConnection; + private NTAuthentication? _session; internal NativeOverlapped* NativeOverlapped { @@ -1882,7 +1885,7 @@ namespace System.Net { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode: {errorCode}, numBytes: {numBytes}, nativeOverlapped: {((IntPtr)nativeOverlapped).ToString("x")}"); // take the DisconnectAsyncResult object from the state - DisconnectAsyncResult asyncResult = (DisconnectAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); + DisconnectAsyncResult asyncResult = (DisconnectAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; IOCompleted(asyncResult, errorCode, numBytes, nativeOverlapped); } @@ -1900,9 +1903,9 @@ namespace System.Net // Clean up the identity. This is for scenarios where identity was not cleaned up before due to // identity caching for unsafe ntlm authentication - IDisposable identity = _authenticatedConnection == null ? null : _authenticatedConnection.Identity as IDisposable; + IDisposable? identity = _authenticatedConnection == null ? null : _authenticatedConnection.Identity as IDisposable; if ((identity != null) && - (_authenticatedConnection.Identity.AuthenticationType == AuthenticationTypes.NTLM) && + (_authenticatedConnection!.Identity.AuthenticationType == AuthenticationTypes.NTLM) && (listener.UnsafeConnectionNtlmAuthentication)) { identity.Dispose(); @@ -1912,7 +1915,7 @@ namespace System.Net Debug.Assert(oldValue == 2, $"Expected OwnershipState of 2, saw {oldValue}."); } - internal WindowsPrincipal AuthenticatedConnection + internal WindowsPrincipal? AuthenticatedConnection { get { @@ -1926,7 +1929,7 @@ namespace System.Net } } - internal NTAuthentication Session + internal NTAuthentication? Session { get { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs index e2bb4b9..e3ff629 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs @@ -13,7 +13,7 @@ namespace System.Net { public sealed unsafe partial class HttpListenerContext { - private string _mutualAuthentication; + private string? _mutualAuthentication; internal HttpListenerSession ListenerSession { get; private set; } internal HttpListenerContext(HttpListenerSession session, RequestContextBase memoryBlob) @@ -28,7 +28,7 @@ namespace System.Net } // Call this right after construction, and only once! Not after it's been handed to a user. - internal void SetIdentity(IPrincipal principal, string mutualAuthentication) + internal void SetIdentity(IPrincipal principal, string? mutualAuthentication) { _mutualAuthentication = mutualAuthentication; _user = principal; @@ -38,9 +38,9 @@ namespace System.Net // This can be used to cache the results of HttpListener.ExtendedProtectionSelectorDelegate. internal ExtendedProtectionPolicy ExtendedProtectionPolicy { get; set; } - internal string MutualAuthentication => _mutualAuthentication; + internal string? MutualAuthentication => _mutualAuthentication; - internal HttpListener Listener => _listener; + internal HttpListener? Listener => _listener; internal SafeHandle RequestQueueHandle => ListenerSession.RequestQueueHandle; @@ -88,12 +88,12 @@ namespace System.Net } finally { - IDisposable user = _user == null ? null : _user.Identity as IDisposable; + IDisposable? user = _user == null ? null : _user.Identity as IDisposable; // For unsafe connection ntlm auth we dont dispose this identity as yet since its cached if ((user != null) && - (_user.Identity.AuthenticationType != NegotiationInfoClass.NTLM) && - (!_listener.UnsafeConnectionNtlmAuthentication)) + (_user!.Identity!.AuthenticationType != NegotiationInfoClass.NTLM) && + (!_listener!.UnsafeConnectionNtlmAuthentication)) { user.Dispose(); } @@ -139,13 +139,13 @@ namespace System.Net // The only way to cancel now is with CancelIoEx. if (statusCode == Interop.HttpApi.ERROR_CONNECTION_INVALID) { - _response.CancelLastWrite(requestQueueHandle); + _response!.CancelLastWrite(requestQueueHandle); } } internal void SetAuthenticationHeaders() { - Listener.SetAuthenticationHeaders(this); + Listener!.SetAuthenticationHeaders(this); } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs index 86629c7..5000795 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs @@ -21,22 +21,22 @@ namespace System.Net private readonly ulong _requestId; internal ulong _connectionId; private readonly SslStatus _sslStatus; - private readonly string _cookedUrlHost; - private readonly string _cookedUrlPath; - private readonly string _cookedUrlQuery; + private readonly string? _cookedUrlHost; + private readonly string? _cookedUrlPath; + private readonly string? _cookedUrlQuery; private long _contentLength; - private Stream _requestStream; - private string _httpMethod; - private WebHeaderCollection _webHeaders; - private IPEndPoint _localEndPoint; - private IPEndPoint _remoteEndPoint; + private Stream? _requestStream; + private string? _httpMethod; + private WebHeaderCollection? _webHeaders; + private IPEndPoint? _localEndPoint; + private IPEndPoint? _remoteEndPoint; private BoundaryType _boundaryType; private int _clientCertificateError; - private RequestContextBase _memoryBlob; + private RequestContextBase? _memoryBlob; private readonly HttpListenerContext _httpContext; private bool _isDisposed; internal const uint CertBoblSize = 1500; - private string _serviceName; + private string? _serviceName; private enum SslStatus : byte { @@ -112,7 +112,7 @@ namespace System.Net get { CheckDisposed(); - return _memoryBlob.RequestBuffer; + return _memoryBlob!.RequestBuffer; } } @@ -121,7 +121,7 @@ namespace System.Net get { CheckDisposed(); - return _memoryBlob.OriginalBlobAddress; + return _memoryBlob!.OriginalBlobAddress; } } @@ -129,7 +129,7 @@ namespace System.Net // disposed. internal void DetachBlob(RequestContextBase memoryBlob) { - if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob) + if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob!) { _memoryBlob = null; } @@ -138,7 +138,7 @@ namespace System.Net // Finalizes ownership of the memory blob. DetachBlob can't be called after this. internal void ReleasePins() { - _memoryBlob.ReleasePins(); + _memoryBlob!.ReleasePins(); } internal ulong RequestId => _requestId; @@ -159,7 +159,7 @@ namespace System.Net { if (_boundaryType == BoundaryType.None) { - string transferEncodingHeader = Headers[HttpKnownHeaderNames.TransferEncoding]; + string? transferEncodingHeader = Headers[HttpKnownHeaderNames.TransferEncoding]; if (transferEncodingHeader != null && transferEncodingHeader.Equals("chunked", StringComparison.OrdinalIgnoreCase)) { _boundaryType = BoundaryType.Chunked; @@ -169,7 +169,7 @@ namespace System.Net { _contentLength = 0; _boundaryType = BoundaryType.ContentLength; - string length = Headers[HttpKnownHeaderNames.ContentLength]; + string? length = Headers[HttpKnownHeaderNames.ContentLength]; if (length != null) { bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out _contentLength); @@ -208,7 +208,7 @@ namespace System.Net _httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_httpMethod:{_httpMethod}"); - return _httpMethod; + return _httpMethod!; } } @@ -228,14 +228,14 @@ namespace System.Net { get { - IPrincipal user = HttpListenerContext.User; + IPrincipal? user = HttpListenerContext.User; return user != null && user.Identity != null && user.Identity.IsAuthenticated; } } public bool IsSecureConnection => _sslStatus != SslStatus.Insecure; - public string ServiceName + public string? ServiceName { get => _serviceName; internal set => _serviceName = value; @@ -252,15 +252,15 @@ namespace System.Net _clientCertificateError = clientCertificateError; } - public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) + public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult) { - X509Certificate2 clientCertificate = null; + X509Certificate2? clientCertificate = null; if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } - ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult; + ListenerClientCertAsyncResult? clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult; if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -297,7 +297,7 @@ namespace System.Net _remoteEndPoint = Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "_remoteEndPoint" + _remoteEndPoint); - return _remoteEndPoint; + return _remoteEndPoint!; } } @@ -310,14 +310,14 @@ namespace System.Net _localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_localEndPoint={_localEndPoint}"); - return _localEndPoint; + return _localEndPoint!; } } //should only be called from httplistenercontext internal void Close() { - RequestContextBase memoryBlob = _memoryBlob; + RequestContextBase? memoryBlob = _memoryBlob; if (memoryBlob != null) { memoryBlob.Close(); @@ -328,7 +328,7 @@ namespace System.Net private ListenerClientCertAsyncResult BeginGetClientCertificateCore(AsyncCallback requestCallback, object state) { - ListenerClientCertAsyncResult asyncResult = null; + ListenerClientCertAsyncResult? asyncResult = null; //-------------------------------------------------------------------- //When you configure the HTTP.SYS with a flag value 2 //which means require client certificates, when the client makes the @@ -534,7 +534,7 @@ namespace System.Net if (_requestUri == null) { _requestUri = HttpListenerRequestUriBuilder.GetRequestUri( - _rawUrl, RequestScheme, _cookedUrlHost, _cookedUrlPath, _cookedUrlQuery); + _rawUrl!, RequestScheme, _cookedUrlHost!, _cookedUrlPath!, _cookedUrlQuery!); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_requestUri:{_requestUri}"); @@ -542,7 +542,7 @@ namespace System.Net } } - internal ChannelBinding GetChannelBinding() + internal ChannelBinding? GetChannelBinding() { return HttpListener.GetChannelBindingFromTls(HttpListenerContext.ListenerSession, _connectionId); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs index 97d2759..d49bc4a 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs @@ -24,7 +24,7 @@ namespace System.Net throw new NotSupportedException(SR.Format( SR.net_listener_invalid_cbt_type, kind.ToString())); } - return _request.GetChannelBinding(); + return _request.GetChannelBinding()!; } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs index 3dcc2d7..0c4b36a 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs @@ -131,25 +131,26 @@ namespace System.Net ContentLength64 = responseEntity.Length; } EnsureResponseStream(); + Debug.Assert(_responseStream != null); if (willBlock) { try { - _responseStream.Write(responseEntity, 0, responseEntity.Length); + _responseStream!.Write(responseEntity, 0, responseEntity.Length); } catch (Win32Exception) { } finally { - _responseStream.Close(); + _responseStream!.Close(); _responseState = ResponseState.Closed; - HttpListenerContext.Close(); + HttpListenerContext!.Close(); } } else { - _responseStream.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null); + _responseStream!.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null); } } @@ -160,10 +161,10 @@ namespace System.Net return; } EnsureResponseStream(); - _responseStream.Close(); + _responseStream!.Close(); _responseState = ResponseState.Closed; - HttpListenerContext.Close(); + HttpListenerContext!.Close(); } internal BoundaryType BoundaryType => _boundaryType; @@ -172,7 +173,7 @@ namespace System.Net { if (_responseStream == null) { - _responseStream = new HttpResponseStream(HttpListenerContext); + _responseStream = new HttpResponseStream(HttpListenerContext!); } } @@ -180,14 +181,14 @@ namespace System.Net { try { - _responseStream.EndWrite(asyncResult); + _responseStream!.EndWrite(asyncResult); } catch (Win32Exception) { } finally { - _responseStream.Close(); + _responseStream!.Close(); HttpListenerContext.Close(); _responseState = ResponseState.Closed; } @@ -217,7 +218,7 @@ namespace System.Net not after. Thus, flag is not applicable to HttpSendHttpResponse. */ internal unsafe uint SendHeaders(Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunk, - HttpResponseStreamAsyncResult asyncResult, + HttpResponseStreamAsyncResult? asyncResult, Interop.HttpApi.HTTP_FLAGS flags, bool isWebSocketHandshake) { @@ -251,7 +252,7 @@ namespace System.Net uint statusCode; uint bytesSent; - List pinnedHeaders = SerializeHeaders(ref _nativeResponse.Headers, isWebSocketHandshake); + List? pinnedHeaders = SerializeHeaders(ref _nativeResponse.Headers, isWebSocketHandshake); try { if (pDataChunk != null) @@ -360,7 +361,7 @@ $"flags: {flags} _boundaryType: {_boundaryType} _contentLength: {_contentLength} { _boundaryType = BoundaryType.Chunked; } - if (CanSendResponseBody(_httpContext.Response.StatusCode)) + if (CanSendResponseBody(_httpContext!.Response.StatusCode)) { _contentLength = -1; } @@ -420,10 +421,10 @@ $"flags: {flags} _boundaryType: {_boundaryType} _contentLength: {_contentLength} ComputeCookies(); } - private List SerializeHeaders(ref Interop.HttpApi.HTTP_RESPONSE_HEADERS headers, + private List? SerializeHeaders(ref Interop.HttpApi.HTTP_RESPONSE_HEADERS headers, bool isWebSocketHandshake) { - Interop.HttpApi.HTTP_UNKNOWN_HEADER[] unknownHeaders = null; + Interop.HttpApi.HTTP_UNKNOWN_HEADER[]? unknownHeaders = null; List pinnedHeaders; GCHandle gcHandle; @@ -435,7 +436,7 @@ $"flags: {flags} _boundaryType: {_boundaryType} _contentLength: {_contentLength} string headerName; string headerValue; int lookup; - byte[] bytes = null; + byte[]? bytes = null; pinnedHeaders = new List(); //--------------------------------------------------- @@ -490,7 +491,7 @@ $"flags: {flags} _boundaryType: {_boundaryType} _contentLength: {_contentLength} if (lookup == -1) { - string[] headerValues = Headers.GetValues(index); + string[] headerValues = Headers.GetValues(index)!; numUnknownHeaders += headerValues.Length; } } @@ -502,7 +503,7 @@ $"flags: {flags} _boundaryType: {_boundaryType} _contentLength: {_contentLength} for (int index = 0; index < Headers.Count; index++) { headerName = Headers.GetKey(index) as string; - headerValue = Headers.Get(index) as string; + headerValue = (Headers.Get(index) as string)!; lookup = Interop.HttpApi.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerName); if (lookup == (int)HttpResponseHeader.SetCookie || isWebSocketHandshake && lookup == (int)HttpResponseHeader.Connection) @@ -526,7 +527,7 @@ $"flags: {flags} _boundaryType: {_boundaryType} _contentLength: {_contentLength} //FOR UNKNOWN HEADERS //ALLOW MULTIPLE HEADERS to be added //--------------------------------------- - string[] headerValues = Headers.GetValues(index); + string[] headerValues = Headers.GetValues(index)!; for (int headerValueIndex = 0; headerValueIndex < headerValues.Length; headerValueIndex++) { //Add Name @@ -577,7 +578,7 @@ $"flags: {flags} _boundaryType: {_boundaryType} _contentLength: {_contentLength} return pinnedHeaders; } - private void FreePinnedHeaders(List pinnedHeaders) + private void FreePinnedHeaders(List? pinnedHeaders) { if (pinnedHeaders != null) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs index 729f613..777335b 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs @@ -10,7 +10,7 @@ namespace System.Net { public readonly HttpListener Listener; public readonly SafeHandle RequestQueueHandle; - private ThreadPoolBoundHandle _requestQueueBoundHandle; + private ThreadPoolBoundHandle? _requestQueueBoundHandle; public ThreadPoolBoundHandle RequestQueueBoundHandle { @@ -38,7 +38,7 @@ namespace System.Net uint statusCode = Interop.HttpApi.HttpCreateRequestQueue( - Interop.HttpApi.s_version, null, null, 0, out HttpRequestQueueV2Handle requestQueueHandle); + Interop.HttpApi.s_version, null!, null, 0, out HttpRequestQueueV2Handle requestQueueHandle); if (statusCode != Interop.HttpApi.ERROR_SUCCESS) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs index 6bc057e..3eadb3c 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs @@ -117,7 +117,7 @@ namespace System.Net if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "statusCode:" + statusCode + " _closed:" + _closed); } - public IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public IAsyncResult? BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { if (size == 0 || _closed) { @@ -126,7 +126,7 @@ namespace System.Net return result; } - HttpRequestStreamAsyncResult asyncResult = null; + HttpRequestStreamAsyncResult? asyncResult = null; uint dataRead = 0; if (_dataChunkIndex != -1) @@ -223,7 +223,7 @@ namespace System.Net { throw new ArgumentNullException(nameof(asyncResult)); } - HttpRequestStreamAsyncResult castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult; + HttpRequestStreamAsyncResult? castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -234,8 +234,8 @@ namespace System.Net } castedAsyncResult.EndCalled = true; // wait & then check for errors - object returnValue = castedAsyncResult.InternalWaitForCompletion(); - Exception exception = returnValue as Exception; + object? returnValue = castedAsyncResult.InternalWaitForCompletion(); + Exception? exception = returnValue as Exception; if (exception != null) { if (NetEventSource.Log.IsEnabled()) @@ -246,7 +246,7 @@ namespace System.Net ExceptionDispatchInfo.Throw(exception); } - uint dataRead = (uint)returnValue; + uint dataRead = (uint)returnValue!; UpdateAfterRead((uint)castedAsyncResult.ErrorCode, dataRead); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"returnValue:{returnValue}"); @@ -275,23 +275,23 @@ namespace System.Net private sealed unsafe class HttpRequestStreamAsyncResult : LazyAsyncResult { - private readonly ThreadPoolBoundHandle _boundHandle; + private readonly ThreadPoolBoundHandle? _boundHandle; internal NativeOverlapped* _pOverlapped; internal void* _pPinnedBuffer; internal uint _dataAlreadyRead; private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(Callback); - internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback) : base(asyncObject, userState, callback) + internal HttpRequestStreamAsyncResult(object asyncObject, object? userState, AsyncCallback? callback) : base(asyncObject, userState, callback) { } - internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback, uint dataAlreadyRead) : base(asyncObject, userState, callback) + internal HttpRequestStreamAsyncResult(object asyncObject, object? userState, AsyncCallback? callback, uint dataAlreadyRead) : base(asyncObject, userState, callback) { _dataAlreadyRead = dataAlreadyRead; } - internal HttpRequestStreamAsyncResult(ThreadPoolBoundHandle boundHandle, object asyncObject, object userState, AsyncCallback callback, byte[] buffer, int offset, uint size, uint dataAlreadyRead) : base(asyncObject, userState, callback) + internal HttpRequestStreamAsyncResult(ThreadPoolBoundHandle boundHandle, object asyncObject, object? userState, AsyncCallback? callback, byte[] buffer, int offset, uint size, uint dataAlreadyRead) : base(asyncObject, userState, callback) { _dataAlreadyRead = dataAlreadyRead; _boundHandle = boundHandle; @@ -307,7 +307,7 @@ namespace System.Net private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint errorCode, uint numBytes) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes}"); - object result = null; + object? result = null; try { if (errorCode != Interop.HttpApi.ERROR_SUCCESS && errorCode != Interop.HttpApi.ERROR_HANDLE_EOF) @@ -331,7 +331,7 @@ namespace System.Net private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { - HttpRequestStreamAsyncResult asyncResult = (HttpRequestStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); + HttpRequestStreamAsyncResult asyncResult = (HttpRequestStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes} nativeOverlapped:0x {((IntPtr)nativeOverlapped).ToString("x8")}"); @@ -344,7 +344,7 @@ namespace System.Net base.Cleanup(); if (_pOverlapped != null) { - _boundHandle.FreeNativeOverlapped(_pOverlapped); + _boundHandle!.FreeNativeOverlapped(_pOverlapped); } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs index 4f2e22c..6ab2f5b 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs @@ -15,7 +15,7 @@ namespace System.Net private long _leftToWrite = long.MinValue; private bool _inOpaqueMode; // The last write needs special handling to cancel. - private HttpResponseStreamAsyncResult _lastWrite; + private HttpResponseStreamAsyncResult? _lastWrite; internal HttpResponseStream(HttpListenerContext httpContext) { @@ -61,7 +61,7 @@ namespace System.Net uint statusCode; uint dataToWrite = (uint)size; - SafeLocalAllocHandle bufferAsIntPtr = null; + SafeLocalAllocHandle? bufferAsIntPtr = null; IntPtr pBufferAsIntPtr = IntPtr.Zero; bool sentHeaders = _httpContext.Response.SentHeaders; try @@ -119,7 +119,7 @@ namespace System.Net null); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpSendResponseEntityBody returned:" + statusCode); - if (_httpContext.Listener.IgnoreWriteExceptions) + if (_httpContext.Listener!.IgnoreWriteExceptions) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Write() suppressing error"); statusCode = Interop.HttpApi.ERROR_SUCCESS; @@ -146,7 +146,7 @@ namespace System.Net if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer, offset, (int)dataToWrite); } - private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { Interop.HttpApi.HTTP_FLAGS flags = ComputeLeftToWrite(); if (_closed || (size == 0 && _leftToWrite != 0)) @@ -207,7 +207,7 @@ namespace System.Net if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_IO_PENDING) { asyncResult.InternalCleanup(); - if (_httpContext.Listener.IgnoreWriteExceptions && sentHeaders) + if (_httpContext.Listener!.IgnoreWriteExceptions && sentHeaders) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "BeginWrite() Suppressing error"); } @@ -238,7 +238,7 @@ namespace System.Net private void EndWriteCore(IAsyncResult asyncResult) { - HttpResponseStreamAsyncResult castedAsyncResult = asyncResult as HttpResponseStreamAsyncResult; + HttpResponseStreamAsyncResult? castedAsyncResult = asyncResult as HttpResponseStreamAsyncResult; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -249,9 +249,9 @@ namespace System.Net } castedAsyncResult.EndCalled = true; // wait & then check for errors - object returnValue = castedAsyncResult.InternalWaitForCompletion(); + object? returnValue = castedAsyncResult.InternalWaitForCompletion(); - Exception exception = returnValue as Exception; + Exception? exception = returnValue as Exception; if (exception != null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, "Rethrowing exception:" + exception); @@ -338,7 +338,7 @@ namespace System.Net if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpSendResponseEntityBody returned:" + statusCode); - if (_httpContext.Listener.IgnoreWriteExceptions) + if (_httpContext.Listener!.IgnoreWriteExceptions) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Suppressing error"); @@ -376,7 +376,7 @@ namespace System.Net // Sync can only be cancelled by CancelSynchronousIo, but we don't attempt this right now. internal void CancelLastWrite(SafeHandle requestQueueHandle) { - HttpResponseStreamAsyncResult asyncState = _lastWrite; + HttpResponseStreamAsyncResult? asyncState = _lastWrite; if (asyncState != null && !asyncState.IsCompleted) { // It is safe to ignore the return value on a cancel operation because the connection is being closed diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs index bab0370..5a41b0d 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs @@ -8,9 +8,9 @@ namespace System.Net { internal sealed unsafe class HttpResponseStreamAsyncResult : LazyAsyncResult { - private readonly ThreadPoolBoundHandle _boundHandle; + private readonly ThreadPoolBoundHandle? _boundHandle; internal NativeOverlapped* _pOverlapped; - private readonly Interop.HttpApi.HTTP_DATA_CHUNK[] _dataChunks; + private readonly Interop.HttpApi.HTTP_DATA_CHUNK[]? _dataChunks; internal bool _sentHeaders; private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(Callback); @@ -45,7 +45,7 @@ namespace System.Net } } - internal HttpResponseStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback) : base(asyncObject, userState, callback) + internal HttpResponseStreamAsyncResult(object asyncObject, object? userState, AsyncCallback? callback) : base(asyncObject, userState, callback) { } @@ -109,7 +109,7 @@ namespace System.Net private static readonly byte[] s_CRLFArray = new byte[] { (byte)'\r', (byte)'\n' }; - internal HttpResponseStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback, byte[] buffer, int offset, int size, bool chunked, bool sentHeaders, ThreadPoolBoundHandle boundHandle) : base(asyncObject, userState, callback) + internal HttpResponseStreamAsyncResult(object asyncObject, object? userState, AsyncCallback? callback, byte[] buffer, int offset, int size, bool chunked, bool sentHeaders, ThreadPoolBoundHandle boundHandle) : base(asyncObject, userState, callback) { _boundHandle = boundHandle; _sentHeaders = sentHeaders; @@ -130,7 +130,7 @@ namespace System.Net int chunkHeaderOffset = 0; - byte[] chunkHeaderBuffer = null; + byte[]? chunkHeaderBuffer = null; if (chunked) { chunkHeaderBuffer = GetChunkHeader(size, out chunkHeaderOffset); @@ -167,7 +167,7 @@ namespace System.Net if (chunked) { - _dataChunks[0].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(chunkHeaderBuffer, chunkHeaderOffset)); + _dataChunks[0].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(chunkHeaderBuffer!, chunkHeaderOffset)); _dataChunks[1].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset)); _dataChunks[2].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(s_CRLFArray, 0)); } @@ -186,7 +186,7 @@ namespace System.Net private static void IOCompleted(HttpResponseStreamAsyncResult asyncResult, uint errorCode, uint numBytes) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes}"); - object result = null; + object? result = null; try { if (errorCode != Interop.HttpApi.ERROR_SUCCESS && errorCode != Interop.HttpApi.ERROR_HANDLE_EOF) @@ -219,8 +219,8 @@ namespace System.Net private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { - object state = ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); - HttpResponseStreamAsyncResult asyncResult = state as HttpResponseStreamAsyncResult; + object state = ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; + HttpResponseStreamAsyncResult asyncResult = (state as HttpResponseStreamAsyncResult)!; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, "errorCode:0x" + errorCode.ToString("x8") + " numBytes:" + numBytes + " nativeOverlapped:0x" + ((IntPtr)nativeOverlapped).ToString("x8")); IOCompleted(asyncResult, errorCode, numBytes); @@ -232,7 +232,7 @@ namespace System.Net base.Cleanup(); if (_pOverlapped != null) { - _boundHandle.FreeNativeOverlapped(_pOverlapped); + _boundHandle!.FreeNativeOverlapped(_pOverlapped); } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs index 1539301..ff0af80 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics; using System.Threading; namespace System.Net @@ -8,7 +9,7 @@ namespace System.Net internal sealed unsafe class ListenerAsyncResult : LazyAsyncResult { private static readonly IOCompletionCallback s_ioCallback = new IOCompletionCallback(WaitCallback); - private AsyncRequestContext _requestContext; + private AsyncRequestContext? _requestContext; internal static IOCompletionCallback IOCallback => s_ioCallback; @@ -20,7 +21,7 @@ namespace System.Net private static void IOCompleted(ListenerAsyncResult asyncResult, uint errorCode, uint numBytes) { - object result = null; + object? result = null; try { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:[{errorCode}] numBytes:[{numBytes}]"); @@ -33,7 +34,7 @@ namespace System.Net } else { - HttpListenerSession listenerSession = asyncResult.AsyncObject as HttpListenerSession; + HttpListenerSession listenerSession = (asyncResult.AsyncObject! as HttpListenerSession)!; if (errorCode == Interop.HttpApi.ERROR_SUCCESS) { // at this point we have received an unmanaged HTTP_REQUEST and memoryBlob @@ -41,9 +42,9 @@ namespace System.Net bool stoleBlob = false; try { - if (HttpListener.ValidateRequest(listenerSession, asyncResult._requestContext)) + if (HttpListener.ValidateRequest(listenerSession, asyncResult._requestContext!)) { - result = listenerSession.Listener.HandleAuthentication(listenerSession, asyncResult._requestContext, out stoleBlob); + result = listenerSession.Listener.HandleAuthentication(listenerSession, asyncResult._requestContext!, out stoleBlob); } } finally @@ -55,13 +56,13 @@ namespace System.Net } else { - asyncResult._requestContext.Reset(listenerSession.RequestQueueBoundHandle, 0, 0); + asyncResult._requestContext!.Reset(listenerSession.RequestQueueBoundHandle, 0, 0); } } } else { - asyncResult._requestContext.Reset(listenerSession.RequestQueueBoundHandle, asyncResult._requestContext.RequestBlob->RequestId, numBytes); + asyncResult._requestContext!.Reset(listenerSession.RequestQueueBoundHandle, asyncResult._requestContext.RequestBlob->RequestId, numBytes); } // We need to issue a new request, either because auth failed, or because our buffer was too small the first time. @@ -95,7 +96,7 @@ namespace System.Net private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { - ListenerAsyncResult asyncResult = (ListenerAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); + ListenerAsyncResult asyncResult = (ListenerAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; IOCompleted(asyncResult, errorCode, numBytes); } @@ -104,9 +105,11 @@ namespace System.Net uint statusCode = Interop.HttpApi.ERROR_SUCCESS; while (true) { + Debug.Assert(_requestContext != null); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Calling Interop.HttpApi.HttpReceiveHttpRequest RequestId: {_requestContext.RequestBlob->RequestId}Buffer:0x {((IntPtr)_requestContext.RequestBlob).ToString("x")} Size: {_requestContext.Size}"); uint bytesTransferred = 0; - HttpListenerSession listenerSession = (HttpListenerSession)AsyncObject; + Debug.Assert(AsyncObject != null); + HttpListenerSession listenerSession = (HttpListenerSession)AsyncObject!; statusCode = Interop.HttpApi.HttpReceiveHttpRequest( listenerSession.RequestQueueHandle, _requestContext.RequestBlob->RequestId, diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs index 8febf53..e1969fa 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs @@ -11,9 +11,9 @@ namespace System.Net { internal unsafe class ListenerClientCertAsyncResult : LazyAsyncResult { - private ThreadPoolBoundHandle _boundHandle; + private ThreadPoolBoundHandle? _boundHandle; private NativeOverlapped* _pOverlapped; - private byte[] _backingBuffer; + private byte[]? _backingBuffer; private Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* _memoryBlob; private uint _size; @@ -51,7 +51,7 @@ namespace System.Net } if (_size != 0) { - _boundHandle.FreeNativeOverlapped(_pOverlapped); + _boundHandle!.FreeNativeOverlapped(_pOverlapped); } _size = size; if (size == 0) @@ -62,7 +62,7 @@ namespace System.Net return; } _backingBuffer = new byte[checked((int)size)]; - _pOverlapped = _boundHandle.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: _backingBuffer); + _pOverlapped = _boundHandle!.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: _backingBuffer); _memoryBlob = (Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*)Marshal.UnsafeAddrOfPinnedArrayElement(_backingBuffer, 0); } @@ -73,8 +73,8 @@ namespace System.Net private static unsafe void IOCompleted(ListenerClientCertAsyncResult asyncResult, uint errorCode, uint numBytes) { - HttpListenerRequest httpListenerRequest = (HttpListenerRequest)asyncResult.AsyncObject; - object result = null; + HttpListenerRequest httpListenerRequest = (HttpListenerRequest)asyncResult.AsyncObject!; + object? result = null; try { if (errorCode == Interop.HttpApi.ERROR_MORE_DATA) @@ -162,7 +162,7 @@ namespace System.Net private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { - ListenerClientCertAsyncResult asyncResult = (ListenerClientCertAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); + ListenerClientCertAsyncResult asyncResult = (ListenerClientCertAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:[{errorCode}] numBytes:[{numBytes}] nativeOverlapped:[{((long)nativeOverlapped)}]"); IOCompleted(asyncResult, errorCode, numBytes); } @@ -173,7 +173,7 @@ namespace System.Net if (_pOverlapped != null) { _memoryBlob = null; - _boundHandle.FreeNativeOverlapped(_pOverlapped); + _boundHandle!.FreeNativeOverlapped(_pOverlapped); _pOverlapped = null; _boundHandle = null; } @@ -185,7 +185,7 @@ namespace System.Net { if (_pOverlapped != null && !Environment.HasShutdownStarted) { - _boundHandle.FreeNativeOverlapped(_pOverlapped); + _boundHandle!.FreeNativeOverlapped(_pOverlapped); _pOverlapped = null; // Must do this in case application calls GC.ReRegisterForFinalize(). _boundHandle = null; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs index fbf3d12..18c1787 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs @@ -32,7 +32,7 @@ namespace System.Net.WebSockets TimeSpan keepAliveInterval, ArraySegment internalBuffer) { - HttpListenerWebSocketContext webSocketContext = null; + HttpListenerWebSocketContext? webSocketContext = null; try { // get property will create a new response if one doesn't exist. @@ -40,10 +40,10 @@ namespace System.Net.WebSockets HttpListenerRequest request = context.Request; ValidateWebSocketHeaders(context); - string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; + string? secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; // Optional for non-browser client - string origin = request.Headers[HttpKnownHeaderNames.Origin]; + string? origin = request.Headers[HttpKnownHeaderNames.Origin]; List secWebSocketProtocols = new List(); string outgoingSecWebSocketProtocolString; @@ -61,7 +61,7 @@ namespace System.Net.WebSockets } // negotiate the websocket key return value - string secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; + string? secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey); response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade); @@ -91,7 +91,7 @@ namespace System.Net.WebSockets await response.OutputStream.FlushAsync().SuppressContextFlow(); - HttpResponseStream responseStream = response.OutputStream as HttpResponseStream; + HttpResponseStream responseStream = (response.OutputStream as HttpResponseStream)!; Debug.Assert(responseStream != null, "'responseStream' MUST be castable to System.Net.HttpResponseStream."); ((HttpResponseStream)response.OutputStream).SwitchToOpaqueMode(); HttpRequestStream requestStream = new HttpRequestStream(context); @@ -105,17 +105,17 @@ namespace System.Net.WebSockets internalBuffer); webSocketContext = new HttpListenerWebSocketContext( - request.Url, + request.Url!, request.Headers, request.Cookies, - context.User, + context.User!, request.IsAuthenticated, request.IsLocal, request.IsSecureConnection, - origin, + origin!, secWebSocketProtocols.AsReadOnly(), - secWebSocketVersion, - secWebSocketKey, + secWebSocketVersion!, + secWebSocketKey!, webSocket); if (NetEventSource.Log.IsEnabled()) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs index e0ea87b..ed85913 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs @@ -21,7 +21,7 @@ namespace System.Net.WebSockets private readonly OutstandingOperationHelper _receiveOutstandingOperationHelper; private readonly OutstandingOperationHelper _sendOutstandingOperationHelper; private readonly Stream _innerStream; - private readonly IWebSocketStream _innerStreamAsWebSocketStream; + private readonly IWebSocketStream? _innerStreamAsWebSocketStream; private readonly string _subProtocol; // We are not calling Dispose method on this object in Cleanup method to avoid a race condition while one thread is calling disposing on @@ -37,21 +37,21 @@ namespace System.Net.WebSockets private readonly WebSocketBuffer _internalBuffer; private readonly KeepAliveTracker _keepAliveTracker; private volatile bool _cleanedUp; - private volatile TaskCompletionSource _closeReceivedTaskCompletionSource; - private volatile Task _closeOutputTask; + private volatile TaskCompletionSource? _closeReceivedTaskCompletionSource; + private volatile Task? _closeOutputTask; private volatile bool _isDisposed; - private volatile Task _closeNetworkConnectionTask; + private volatile Task? _closeNetworkConnectionTask; private volatile bool _closeAsyncStartedReceive; private volatile WebSocketState _state; - private volatile Task _keepAliveTask; - private volatile WebSocketOperation.ReceiveOperation _receiveOperation; - private volatile WebSocketOperation.SendOperation _sendOperation; - private volatile WebSocketOperation.SendOperation _keepAliveOperation; - private volatile WebSocketOperation.CloseOutputOperation _closeOutputOperation; + private volatile Task? _keepAliveTask; + private volatile WebSocketOperation.ReceiveOperation? _receiveOperation; + private volatile WebSocketOperation.SendOperation? _sendOperation; + private volatile WebSocketOperation.SendOperation? _keepAliveOperation; + private volatile WebSocketOperation.CloseOutputOperation? _closeOutputOperation; private Nullable _closeStatus; - private string _closeStatusDescription; + private string? _closeStatusDescription; private int _receiveState; - private Exception _pendingException; + private Exception? _pendingException; protected WebSocketBase(Stream innerStream, string subProtocol, @@ -129,7 +129,7 @@ namespace System.Net.WebSockets } } - public override string CloseStatusDescription + public override string? CloseStatusDescription { get { @@ -197,11 +197,11 @@ namespace System.Net.WebSockets } EnsureReceiveOperation(); - receiveResult = await _receiveOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow(); + receiveResult = (await _receiveOperation!.Process(buffer, linkedCancellationToken).SuppressContextFlow())!; if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0) { - NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, receiveResult.Count); + NetEventSource.DumpBuffer(this, buffer.Array!, buffer.Offset, receiveResult.Count); } } catch (Exception exception) @@ -270,7 +270,7 @@ namespace System.Net.WebSockets { while (!(ownsCancellationTokenSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken))) { - Task keepAliveTask; + Task? keepAliveTask; lock (SessionHandle) { @@ -306,7 +306,7 @@ namespace System.Net.WebSockets } EnsureSendOperation(); - _sendOperation.BufferType = GetBufferType(messageType, endOfMessage); + _sendOperation!.BufferType = GetBufferType(messageType, endOfMessage); await _sendOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow(); } catch (Exception exception) @@ -341,7 +341,7 @@ namespace System.Net.WebSockets { foreach (ArraySegment buffer in sendBuffers) { - await _innerStream.WriteAsync(buffer.Array, + await _innerStream.WriteAsync(buffer.Array!, buffer.Offset, buffer.Count, cancellationToken).SuppressContextFlow(); @@ -409,12 +409,12 @@ namespace System.Net.WebSockets // MultiThreading: ThreadSafe; No-op if already in a terminal state public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, - string statusDescription, + string? statusDescription, CancellationToken cancellationToken) { WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription); - return CloseOutputAsyncCore(closeStatus, statusDescription, cancellationToken); + return CloseOutputAsyncCore(closeStatus, statusDescription!, cancellationToken); } private async Task CloseOutputAsyncCore(WebSocketCloseStatus closeStatus, @@ -458,7 +458,7 @@ namespace System.Net.WebSockets ownsCloseOutputCancellationTokenSource = _closeOutputOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken); if (!ownsCloseOutputCancellationTokenSource) { - Task closeOutputTask = _closeOutputTask; + Task? closeOutputTask = _closeOutputTask; if (closeOutputTask != null) { @@ -494,9 +494,9 @@ namespace System.Net.WebSockets } EnsureCloseOutputOperation(); - _closeOutputOperation.CloseStatus = closeStatus; - _closeOutputOperation.CloseReason = statusDescription; - _closeOutputTask = _closeOutputOperation.Process(null, linkedCancellationToken); + _closeOutputOperation!.CloseStatus = closeStatus; + _closeOutputOperation!.CloseReason = statusDescription; + _closeOutputTask = _closeOutputOperation!.Process(null, linkedCancellationToken); ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken); await _closeOutputTask.SuppressContextFlow(); @@ -637,7 +637,7 @@ namespace System.Net.WebSockets // MultiThreading: ThreadSafe; No-op if already in a terminal state public override Task CloseAsync(WebSocketCloseStatus closeStatus, - string statusDescription, + string? statusDescription, CancellationToken cancellationToken) { WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription); @@ -645,7 +645,7 @@ namespace System.Net.WebSockets } private async Task CloseAsyncCore(WebSocketCloseStatus closeStatus, - string statusDescription, + string? statusDescription, CancellationToken cancellationToken) { string inputParameter = string.Empty; @@ -679,7 +679,7 @@ namespace System.Net.WebSockets ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent); - Task closeOutputTask; + Task? closeOutputTask; ownsCloseCancellationTokenSource = _closeOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken); if (ownsCloseCancellationTokenSource) { @@ -768,11 +768,11 @@ namespace System.Net.WebSockets ArraySegment closeMessageBuffer = new ArraySegment(new byte[HttpWebSocket.MinReceiveBufferSize]); EnsureReceiveOperation(); - Task receiveAsyncTask = _receiveOperation.Process(closeMessageBuffer, + Task receiveAsyncTask = _receiveOperation!.Process(closeMessageBuffer, linkedCancellationToken); ReleaseLock(_thisLock, ref lockTaken); - WebSocketReceiveResult receiveResult = null; + WebSocketReceiveResult? receiveResult = null; try { receiveResult = await receiveAsyncTask.SuppressContextFlow(); @@ -799,7 +799,7 @@ namespace System.Net.WebSockets { if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0) { - NetEventSource.DumpBuffer(this, closeMessageBuffer.Array, closeMessageBuffer.Offset, receiveResult.Count); + NetEventSource.DumpBuffer(this, closeMessageBuffer.Array!, closeMessageBuffer.Offset, receiveResult.Count); } if (receiveResult.MessageType != WebSocketMessageType.Close) @@ -816,7 +816,7 @@ namespace System.Net.WebSockets { _receiveOutstandingOperationHelper.CompleteOperation(ownsReceiveCancellationTokenSource); ReleaseLock(_thisLock, ref lockTaken); - await _closeReceivedTaskCompletionSource.Task.SuppressContextFlow(); + await _closeReceivedTaskCompletionSource!.Task.SuppressContextFlow(); } // When ownsReceiveCancellationTokenSource is true and an exception is thrown, the lock will be taken. @@ -1124,7 +1124,7 @@ namespace System.Net.WebSockets // We only want to throw an OperationCanceledException if the CancellationToken passed // down from the caller is canceled - not when Abort is called on another thread and // the linkedCancellationToken is canceled. - private void ThrowIfConvertibleException(string methodName, + private void ThrowIfConvertibleException(string? methodName, Exception exception, CancellationToken cancellationToken, bool aborted) @@ -1136,7 +1136,7 @@ namespace System.Net.WebSockets NetEventSource.Error(this, $"methodName: {methodName}, exception: {exception}"); } - OperationCanceledException operationCanceledException = exception as OperationCanceledException; + OperationCanceledException? operationCanceledException = exception as OperationCanceledException; if (operationCanceledException != null) { if (cancellationToken.IsCancellationRequested || @@ -1147,7 +1147,7 @@ namespace System.Net.WebSockets ThrowIfAborted(aborted, exception); } - WebSocketException convertedException = exception as WebSocketException; + WebSocketException? convertedException = exception as WebSocketException; if (convertedException != null) { cancellationToken.ThrowIfCancellationRequested(); @@ -1155,19 +1155,19 @@ namespace System.Net.WebSockets return; } - SocketException socketException = exception as SocketException; + SocketException? socketException = exception as SocketException; if (socketException != null) { convertedException = new WebSocketException(socketException.NativeErrorCode, socketException); } - HttpListenerException httpListenerException = exception as HttpListenerException; + HttpListenerException? httpListenerException = exception as HttpListenerException; if (httpListenerException != null) { convertedException = new WebSocketException(httpListenerException.ErrorCode, httpListenerException); } - IOException ioException = exception as IOException; + IOException? ioException = exception as IOException; if (ioException != null) { socketException = exception.InnerException as SocketException; @@ -1184,7 +1184,7 @@ namespace System.Net.WebSockets throw convertedException; } - AggregateException aggregateException = exception as AggregateException; + AggregateException? aggregateException = exception as AggregateException; if (aggregateException != null) { // Collapse possibly nested graph into a flat list. @@ -1267,7 +1267,7 @@ namespace System.Net.WebSockets private void OnBackgroundTaskException(Exception exception) { - if (Interlocked.CompareExchange(ref _pendingException, exception, null) == null) + if (Interlocked.CompareExchange(ref _pendingException!, exception, null!) == null) { if (NetEventSource.Log.IsEnabled()) { @@ -1279,7 +1279,7 @@ namespace System.Net.WebSockets private void ThrowIfPendingException() { - Exception pendingException = Interlocked.Exchange(ref _pendingException, null); + Exception pendingException = Interlocked.Exchange(ref _pendingException!, null!); if (pendingException != null) { throw new WebSocketException(WebSocketError.Faulted, pendingException); @@ -1330,7 +1330,7 @@ namespace System.Net.WebSockets } private void FinishOnCloseReceived(WebSocketCloseStatus closeStatus, - string closeStatusDescription) + string? closeStatusDescription) { _closeReceivedTaskCompletionSource?.TrySetResult(); @@ -1347,12 +1347,12 @@ namespace System.Net.WebSockets } } - private static async void OnKeepAlive(object sender) + private static async void OnKeepAlive(object? sender) { Debug.Assert(sender != null, "'sender' MUST NOT be NULL."); Debug.Assert((sender as WebSocketBase) != null, "'sender as WebSocketBase' MUST NOT be NULL."); - WebSocketBase thisPtr = sender as WebSocketBase; + WebSocketBase? thisPtr = (sender as WebSocketBase)!; bool lockTaken = false; CancellationToken linkedCancellationToken = CancellationToken.None; @@ -1376,9 +1376,9 @@ namespace System.Net.WebSockets if (ownsCancellationTokenSource) { thisPtr.EnsureKeepAliveOperation(); - thisPtr._keepAliveTask = thisPtr._keepAliveOperation.Process(null, linkedCancellationToken); + thisPtr._keepAliveTask = thisPtr._keepAliveOperation!.Process(null, linkedCancellationToken); ReleaseLock(thisPtr.SessionHandle, ref lockTaken); - await thisPtr._keepAliveTask.SuppressContextFlow(); + await thisPtr._keepAliveTask!.SuppressContextFlow(); } } finally @@ -1427,7 +1427,7 @@ namespace System.Net.WebSockets AsyncOperationCompleted = false; } - public WebSocketReceiveResult ReceiveResult { get; protected set; } + public WebSocketReceiveResult? ReceiveResult { get; protected set; } protected abstract int BufferCount { get; } protected abstract WebSocketProtocolComponent.ActionQueue ActionQueue { get; } protected abstract void Initialize(Nullable> buffer, CancellationToken cancellationToken); @@ -1451,7 +1451,7 @@ namespace System.Net.WebSockets protected abstract void Cleanup(); - internal async Task Process(Nullable> buffer, + internal async Task Process(Nullable> buffer, CancellationToken cancellationToken) { Debug.Assert(BufferCount >= 1 && BufferCount <= 2, "'bufferCount' MUST ONLY BE '1' or '2'."); @@ -1495,7 +1495,7 @@ namespace System.Net.WebSockets { // A close frame was received - Debug.Assert(ReceiveResult.Count == 0, "'receiveResult.Count' MUST be 0."); + Debug.Assert(ReceiveResult!.Count == 0, "'receiveResult.Count' MUST be 0."); Debug.Assert(ReceiveResult.CloseStatus != null, "'receiveResult.CloseStatus' MUST NOT be NULL for message type 'Close'."); bool thisLockTaken = false; try @@ -1557,7 +1557,7 @@ namespace System.Net.WebSockets HttpWebSocket.ThrowIfConnectionAborted(_webSocket._innerStream, true); try { - Task readTask = _webSocket._innerStream.ReadAsync(payload.Array, + Task readTask = _webSocket._innerStream.ReadAsync(payload.Array!, payload.Offset, payload.Count, cancellationToken); @@ -1816,7 +1816,7 @@ namespace System.Net.WebSockets if (bufferType == WebSocketProtocolComponent.BufferType.Close) { payload = ArraySegment.Empty; - _webSocket._internalBuffer.ConvertCloseBuffer(action, dataBuffers[0], out WebSocketCloseStatus closeStatus, out string reason); + _webSocket._internalBuffer.ConvertCloseBuffer(action, dataBuffers[0], out WebSocketCloseStatus closeStatus, out string? reason); receiveResult = new WebSocketReceiveResult(bytesTransferred, messageType, true, closeStatus, reason); @@ -1840,9 +1840,9 @@ namespace System.Net.WebSockets bytesTransferred = Math.Min(payload.Count, (int)buffer.Value.Count); if (bytesTransferred > 0) { - Buffer.BlockCopy(payload.Array, + Buffer.BlockCopy(payload.Array!, payload.Offset, - buffer.Value.Array, + buffer.Value.Array!, buffer.Value.Offset, bytesTransferred); } @@ -1953,7 +1953,7 @@ namespace System.Net.WebSockets } internal WebSocketCloseStatus CloseStatus { get; set; } - internal string CloseReason { get; set; } + internal string? CloseReason { get; set; } protected override Nullable CreateBuffer(Nullable> buffer) { @@ -2039,7 +2039,7 @@ namespace System.Net.WebSockets private readonly TimeSpan _keepAliveInterval; private readonly Stopwatch _lastSendActivity; private readonly Stopwatch _lastReceiveActivity; - private Timer _keepAliveTimer; + private Timer? _keepAliveTimer; public DefaultKeepAliveTracker(TimeSpan keepAliveInterval) { @@ -2095,12 +2095,12 @@ namespace System.Net.WebSockets public override void Dispose() { - _keepAliveTimer.Dispose(); + _keepAliveTimer!.Dispose(); } private void ResetTimer(int dueInMilliseconds) { - _keepAliveTimer.Change(dueInMilliseconds, Timeout.Infinite); + _keepAliveTimer!.Change(dueInMilliseconds, Timeout.Infinite); } private TimeSpan GetIdleTime() @@ -2131,7 +2131,7 @@ namespace System.Net.WebSockets private class OutstandingOperationHelper : IDisposable { private volatile int _operationsOutstanding; - private volatile CancellationTokenSource _cancellationTokenSource; + private volatile CancellationTokenSource? _cancellationTokenSource; private volatile bool _isDisposed; private readonly object _thisLock = new object(); @@ -2163,7 +2163,7 @@ namespace System.Net.WebSockets return; } - CancellationTokenSource snapshot = null; + CancellationTokenSource? snapshot = null; lock (_thisLock) { @@ -2196,7 +2196,7 @@ namespace System.Net.WebSockets public void CancelIO() { - CancellationTokenSource cancellationTokenSourceSnapshot = null; + CancellationTokenSource? cancellationTokenSourceSnapshot = null; lock (_thisLock) { @@ -2229,7 +2229,7 @@ namespace System.Net.WebSockets return; } - CancellationTokenSource snapshot = null; + CancellationTokenSource? snapshot = null; lock (_thisLock) { if (_isDisposed) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs index 87610bf..aa21740 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs @@ -38,7 +38,7 @@ namespace System.Net.WebSockets private readonly ArraySegment _propertyBuffer; private readonly int _sendBufferSize; private volatile int _payloadOffset; - private volatile PayloadReceiveResult _bufferedPayloadReceiveResult; + private volatile PayloadReceiveResult? _bufferedPayloadReceiveResult; private long _pinnedSendBufferStartAddress; private long _pinnedSendBufferEndAddress; private ArraySegment _pinnedSendBuffer; @@ -173,7 +173,7 @@ namespace System.Net.WebSockets internal void PinSendBuffer(ArraySegment payload, out bool bufferHasBeenPinned) { bufferHasBeenPinned = false; - WebSocketValidate.ValidateBuffer(payload.Array, payload.Offset, payload.Count); + WebSocketValidate.ValidateBuffer(payload.Array!, payload.Offset, payload.Count); int previousState = Interlocked.Exchange(ref _sendBufferState, SendBufferState.SendPayloadSpecified); if (previousState != SendBufferState.None) @@ -187,14 +187,14 @@ namespace System.Net.WebSockets _pinnedSendBufferHandle = GCHandle.Alloc(_pinnedSendBuffer.Array, GCHandleType.Pinned); bufferHasBeenPinned = true; _pinnedSendBufferStartAddress = - Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array, _pinnedSendBuffer.Offset).ToInt64(); + Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array!, _pinnedSendBuffer.Offset).ToInt64(); _pinnedSendBufferEndAddress = _pinnedSendBufferStartAddress + _pinnedSendBuffer.Count; } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation internal IntPtr ConvertPinnedSendPayloadToNative(ArraySegment payload) { - return ConvertPinnedSendPayloadToNative(payload.Array, payload.Offset, payload.Count); + return ConvertPinnedSendPayloadToNative(payload.Array!, payload.Offset, payload.Count); } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation @@ -207,7 +207,7 @@ namespace System.Net.WebSockets throw new AccessViolationException(); } - Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array, + Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array!, _pinnedSendBuffer.Offset).ToInt64() == _pinnedSendBufferStartAddress, "'m_PinnedSendBuffer.Array' MUST be pinned during the entire send operation."); @@ -225,7 +225,7 @@ namespace System.Net.WebSockets throw new AccessViolationException(); } - Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array, + Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array!, _pinnedSendBuffer.Offset).ToInt64() == _pinnedSendBufferStartAddress, "'m_PinnedSendBuffer.Array' MUST be pinned during the entire send operation."); @@ -236,7 +236,7 @@ namespace System.Net.WebSockets int internalOffset = (int)(bufferData.ToInt64() - _pinnedSendBufferStartAddress); - return new ArraySegment(_pinnedSendBuffer.Array, _pinnedSendBuffer.Offset + internalOffset, (int)bufferSize); + return new ArraySegment(_pinnedSendBuffer.Array!, _pinnedSendBuffer.Offset + internalOffset, (int)bufferSize); } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation @@ -306,9 +306,9 @@ namespace System.Net.WebSockets Debug.Assert(_bufferedPayloadReceiveResult == null || _bufferedPayloadReceiveResult.Count == 0, "'_bufferedPayloadReceiveResult.Count' MUST be '0' at this point."); - Buffer.BlockCopy(payload.Array, + Buffer.BlockCopy(payload.Array!, payload.Offset + unconsumedDataOffset, - _payloadBuffer.Array, + _payloadBuffer.Array!, _payloadBuffer.Offset, bytesBuffered); @@ -323,7 +323,7 @@ namespace System.Net.WebSockets ThrowIfDisposed(); ValidateBufferedPayload(); - int bytesTransferred = Math.Min(buffer.Count, _bufferedPayloadReceiveResult.Count); + int bytesTransferred = Math.Min(buffer.Count, _bufferedPayloadReceiveResult!.Count); _bufferedPayloadReceiveResult.Count -= bytesTransferred; @@ -332,9 +332,9 @@ namespace System.Net.WebSockets _bufferedPayloadReceiveResult.MessageType, _bufferedPayloadReceiveResult.Count == 0 && _bufferedPayloadReceiveResult.EndOfMessage); - Buffer.BlockCopy(_payloadBuffer.Array, + Buffer.BlockCopy(_payloadBuffer.Array!, _payloadBuffer.Offset + _payloadOffset, - buffer.Array, + buffer.Array!, buffer.Offset, bytesTransferred); @@ -373,7 +373,7 @@ namespace System.Net.WebSockets if (this.IsNativeBuffer(bufferData, bufferLength)) { - return new ArraySegment(_internalBuffer.Array, + return new ArraySegment(_internalBuffer.Array!, this.GetOffset(bufferData), (int)bufferLength); } @@ -387,7 +387,7 @@ namespace System.Net.WebSockets internal void ConvertCloseBuffer(WebSocketProtocolComponent.Action action, Interop.WebSocket.Buffer buffer, out WebSocketCloseStatus closeStatus, - out string reason) + out string? reason) { ThrowIfDisposed(); IntPtr bufferData; @@ -405,7 +405,7 @@ namespace System.Net.WebSockets ArraySegment reasonBlob; if (this.IsNativeBuffer(bufferData, bufferLength)) { - reasonBlob = new ArraySegment(_internalBuffer.Array, + reasonBlob = new ArraySegment(_internalBuffer.Array!, this.GetOffset(bufferData), (int)bufferLength); } @@ -419,7 +419,7 @@ namespace System.Net.WebSockets // No need to wrap DecoderFallbackException for invalid UTF8 chacters, because // Encoding.UTF8 will not throw but replace invalid characters instead. - reason = Encoding.UTF8.GetString(reasonBlob.Array, reasonBlob.Offset, reasonBlob.Count); + reason = Encoding.UTF8.GetString(reasonBlob.Array!, reasonBlob.Offset, reasonBlob.Count); } } @@ -608,7 +608,7 @@ namespace System.Net.WebSockets long nativeBufferStartAddress = pBuffer.ToInt64(); long nativeBufferEndAddress = bufferSize + nativeBufferStartAddress; - Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_internalBuffer.Array, _internalBuffer.Offset).ToInt64() == _startAddress, + Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_internalBuffer.Array!, _internalBuffer.Offset).ToInt64() == _startAddress, "'m_InternalBuffer.Array' MUST be pinned for the whole lifetime of a WebSocket."); if (nativeBufferStartAddress >= _startAddress && diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs index 151a958..d9733f9 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs @@ -18,16 +18,16 @@ namespace System.Net.WebSockets private static readonly EventHandler s_OnWriteCompleted = new EventHandler(OnWriteCompleted); private static readonly Func s_CanHandleException = new Func(CanHandleException); - private static readonly Action s_OnCancel = new Action(OnCancel); + private static readonly Action s_OnCancel = new Action(OnCancel); private readonly HttpRequestStream _inputStream; private readonly HttpResponseStream _outputStream; private readonly HttpListenerContext _context; private bool _inOpaqueMode; - private WebSocketBase _webSocket; - private HttpListenerAsyncEventArgs _writeEventArgs; - private HttpListenerAsyncEventArgs _readEventArgs; - private TaskCompletionSource _writeTaskCompletionSource; - private TaskCompletionSource _readTaskCompletionSource; + private WebSocketBase? _webSocket; + private HttpListenerAsyncEventArgs? _writeEventArgs; + private HttpListenerAsyncEventArgs? _readEventArgs; + private TaskCompletionSource? _writeTaskCompletionSource; + private TaskCompletionSource? _readTaskCompletionSource; private int _cleanedUp; #if DEBUG @@ -151,7 +151,7 @@ namespace System.Net.WebSockets "Only one outstanding read allowed at any given time."); #endif _readTaskCompletionSource = new TaskCompletionSource(); - _readEventArgs.SetBuffer(buffer, offset, count); + _readEventArgs!.SetBuffer(buffer, offset, count); if (!ReadAsyncFast(_readEventArgs)) { if (_readEventArgs.Exception != null) @@ -245,7 +245,7 @@ namespace System.Net.WebSockets _inputStream.InternalHttpContext.RequestQueueHandle, _inputStream.InternalHttpContext.RequestId, flags, - (byte*)_webSocket.InternalBuffer.ToIntPtr(eventArgs.Offset), + (byte*)_webSocket!.InternalBuffer.ToIntPtr(eventArgs.Offset), (uint)eventArgs.Count, out bytesReturned, eventArgs.NativeOverlapped); @@ -276,7 +276,7 @@ namespace System.Net.WebSockets } catch (Exception e) { - _readEventArgs.FinishOperationFailure(e, true); + _readEventArgs!.FinishOperationFailure(e, true); _outputStream.SetClosedFlag(); _outputStream.InternalHttpContext.Abort(); @@ -302,8 +302,8 @@ namespace System.Net.WebSockets public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, - AsyncCallback callback, - object state) + AsyncCallback? callback, + object? state) { return _inputStream.BeginRead(buffer, offset, count, callback, state); } @@ -323,7 +323,7 @@ namespace System.Net.WebSockets if (sendBuffers.Count == 1) { ArraySegment buffer = sendBuffers[0]; - return WriteAsync(buffer.Array, buffer.Offset, buffer.Count, cancellationToken); + return WriteAsync(buffer.Array!, buffer.Offset, buffer.Count, cancellationToken); } return MultipleWriteAsyncCore(sendBuffers, cancellationToken); @@ -350,7 +350,7 @@ namespace System.Net.WebSockets "Only one outstanding write allowed at any given time."); #endif _writeTaskCompletionSource = new TaskCompletionSource(); - _writeEventArgs.SetBuffer(null, 0, 0); + _writeEventArgs!.SetBuffer(null, 0, 0); _writeEventArgs.BufferList = sendBuffers; if (WriteAsyncFast(_writeEventArgs)) { @@ -409,7 +409,7 @@ namespace System.Net.WebSockets "Only one outstanding write allowed at any given time."); #endif _writeTaskCompletionSource = new TaskCompletionSource(); - _writeEventArgs.BufferList = null; + _writeEventArgs!.BufferList = null; _writeEventArgs.SetBuffer(buffer, offset, count); if (WriteAsyncFast(_writeEventArgs)) { @@ -499,7 +499,7 @@ namespace System.Net.WebSockets } catch (Exception e) { - _writeEventArgs.FinishOperationFailure(e, true); + _writeEventArgs!.FinishOperationFailure(e, true); _outputStream.SetClosedFlag(); _outputStream.InternalHttpContext.Abort(); @@ -517,8 +517,8 @@ namespace System.Net.WebSockets public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, - AsyncCallback callback, - object state) + AsyncCallback? callback, + object? state) { return _outputStream.BeginWrite(buffer, offset, count, callback, state); } @@ -569,7 +569,7 @@ namespace System.Net.WebSockets "Only one outstanding write allowed at any given time."); #endif _writeTaskCompletionSource = new TaskCompletionSource(); - _writeEventArgs.SetShouldCloseOutput(); + _writeEventArgs!.SetShouldCloseOutput(); if (WriteAsyncFast(_writeEventArgs)) { await _writeTaskCompletionSource.Task.SuppressContextFlow(); @@ -636,10 +636,10 @@ namespace System.Net.WebSockets error is IOException; } - private static void OnCancel(object state) + private static void OnCancel(object? state) { Debug.Assert(state != null, "'state' MUST NOT be NULL."); - WebSocketHttpListenerDuplexStream thisPtr = state as WebSocketHttpListenerDuplexStream; + WebSocketHttpListenerDuplexStream thisPtr = (state as WebSocketHttpListenerDuplexStream)!; Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL."); try @@ -683,7 +683,7 @@ namespace System.Net.WebSockets } } - private static void OnWriteCompleted(object sender, HttpListenerAsyncEventArgs eventArgs) + private static void OnWriteCompleted(object? sender, HttpListenerAsyncEventArgs eventArgs) { Debug.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL."); WebSocketHttpListenerDuplexStream thisPtr = eventArgs.CurrentStream; @@ -695,15 +695,15 @@ namespace System.Net.WebSockets if (eventArgs.Exception != null) { - thisPtr._writeTaskCompletionSource.TrySetException(eventArgs.Exception); + thisPtr._writeTaskCompletionSource!.TrySetException(eventArgs.Exception); } else { - thisPtr._writeTaskCompletionSource.TrySetResult(); + thisPtr._writeTaskCompletionSource!.TrySetResult(); } } - private static void OnReadCompleted(object sender, HttpListenerAsyncEventArgs eventArgs) + private static void OnReadCompleted(object? sender, HttpListenerAsyncEventArgs eventArgs) { Debug.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL."); WebSocketHttpListenerDuplexStream thisPtr = eventArgs.CurrentStream; @@ -715,11 +715,11 @@ namespace System.Net.WebSockets if (eventArgs.Exception != null) { - thisPtr._readTaskCompletionSource.TrySetException(eventArgs.Exception); + thisPtr._readTaskCompletionSource!.TrySetException(eventArgs.Exception); } else { - thisPtr._readTaskCompletionSource.TrySetResult(eventArgs.BytesTransferred); + thisPtr._readTaskCompletionSource!.TrySetResult(eventArgs.BytesTransferred); } } @@ -732,18 +732,18 @@ namespace System.Net.WebSockets private bool _disposeCalled; private unsafe NativeOverlapped* _ptrNativeOverlapped; - private ThreadPoolBoundHandle _boundHandle; - private event EventHandler m_Completed; - private byte[] _buffer; - private IList> _bufferList; + private ThreadPoolBoundHandle? _boundHandle; + private event EventHandler? m_Completed; + private byte[]? _buffer; + private IList>? _bufferList; private int _count; private int _offset; private int _bytesTransferred; private HttpListenerAsyncOperation _completedOperation; - private Interop.HttpApi.HTTP_DATA_CHUNK[] _dataChunks; + private Interop.HttpApi.HTTP_DATA_CHUNK[]? _dataChunks; private GCHandle _dataChunksGCHandle; private ushort _dataChunkCount; - private Exception _exception; + private Exception? _exception; private bool _shouldCloseOutput; private readonly WebSocketBase _webSocket; private readonly WebSocketHttpListenerDuplexStream _currentStream; @@ -776,7 +776,7 @@ namespace System.Net.WebSockets get { return _bytesTransferred; } } - public byte[] Buffer + public byte[]? Buffer { get { return _buffer; } } @@ -784,7 +784,7 @@ namespace System.Net.WebSockets // BufferList property. // Mutually exclusive with Buffer. // Setting this property with an existing non-null Buffer will cause an assert. - public IList> BufferList + public IList>? BufferList { get { return _bufferList; } set @@ -815,7 +815,7 @@ namespace System.Net.WebSockets get { return _count; } } - public Exception Exception + public Exception? Exception { get { return _exception; } } @@ -922,7 +922,7 @@ namespace System.Net.WebSockets #if DEBUG DebugRefCountReleaseNativeOverlapped(); #endif - _boundHandle.FreeNativeOverlapped(_ptrNativeOverlapped); + _boundHandle!.FreeNativeOverlapped(_ptrNativeOverlapped); _ptrNativeOverlapped = null; } @@ -978,7 +978,7 @@ namespace System.Net.WebSockets _completedOperation = HttpListenerAsyncOperation.Send; } - public void SetBuffer(byte[] buffer, int offset, int count) + public void SetBuffer(byte[]? buffer, int offset, int count) { Debug.Assert(!_shouldCloseOutput, "'m_ShouldCloseOutput' MUST be 'false' at this point."); Debug.Assert(buffer == null || _bufferList == null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL."); @@ -1024,26 +1024,26 @@ namespace System.Net.WebSockets } } - private unsafe void UpdateDataChunk(int index, byte[] buffer, int offset, int count) + private unsafe void UpdateDataChunk(int index, byte[]? buffer, int offset, int count) { if (buffer == null) { - _dataChunks[index].pBuffer = null; - _dataChunks[index].BufferLength = 0; + _dataChunks![index].pBuffer = null; + _dataChunks![index].BufferLength = 0; return; } if (_webSocket.InternalBuffer.IsInternalBuffer(buffer, offset, count)) { - _dataChunks[index].pBuffer = (byte*)(_webSocket.InternalBuffer.ToIntPtr(offset)); + _dataChunks![index].pBuffer = (byte*)(_webSocket.InternalBuffer.ToIntPtr(offset)); } else { - _dataChunks[index].pBuffer = + _dataChunks![index].pBuffer = (byte*)_webSocket.InternalBuffer.ConvertPinnedSendPayloadToNative(buffer, offset, count); } - _dataChunks[index].BufferLength = (uint)count; + _dataChunks![index].BufferLength = (uint)count; } // Method to mark this object as no longer "in-use". @@ -1064,7 +1064,7 @@ namespace System.Net.WebSockets } // Method to update internal state after sync or async completion. - private void SetResults(Exception exception, int bytesTransferred) + private void SetResults(Exception? exception, int bytesTransferred) { _exception = exception; _bytesTransferred = bytesTransferred; @@ -1100,9 +1100,9 @@ namespace System.Net.WebSockets Debug.Assert(_completedOperation == HttpListenerAsyncOperation.Send, "'BufferList' is only supported for send operations."); - foreach (ArraySegment buffer in BufferList) + foreach (ArraySegment buffer in BufferList!) { - NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, buffer.Count, nameof(WriteAsyncFast)); + NetEventSource.DumpBuffer(this, buffer.Array!, buffer.Offset, buffer.Count, nameof(WriteAsyncFast)); } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs index 72f9f47..2402dd3 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs @@ -13,7 +13,7 @@ namespace System.Net.WebSockets { private static readonly string s_dummyWebsocketKeyBase64 = Convert.ToBase64String(new byte[16]); private static readonly IntPtr s_webSocketDllHandle; - private static readonly string s_supportedVersion; + private static readonly string? s_supportedVersion; private static readonly Interop.WebSocket.HttpHeader[] s_initialClientRequestHeaders = new Interop.WebSocket.HttpHeader[] { @@ -33,7 +33,7 @@ namespace System.Net.WebSockets } }; - private static readonly Interop.WebSocket.HttpHeader[] s_ServerFakeRequestHeaders; + private static readonly Interop.WebSocket.HttpHeader[]? s_ServerFakeRequestHeaders; internal enum Action { @@ -131,7 +131,7 @@ namespace System.Net.WebSockets HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } - return s_supportedVersion; + return s_supportedVersion!; } } @@ -150,10 +150,10 @@ namespace System.Net.WebSockets HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } - SafeWebSocketHandle webSocketHandle = null; + SafeWebSocketHandle? webSocketHandle = null; try { - int errorCode = Interop.WebSocket.WebSocketCreateClientHandle(null, 0, out webSocketHandle); + int errorCode = Interop.WebSocket.WebSocketCreateClientHandle(null!, 0, out webSocketHandle); ThrowOnError(errorCode); if (webSocketHandle == null || @@ -165,7 +165,7 @@ namespace System.Net.WebSockets IntPtr additionalHeadersPtr; uint additionalHeaderCount; - errorCode = Interop.WebSocket.WebSocketBeginClientHandshake(webSocketHandle, + errorCode = Interop.WebSocket.WebSocketBeginClientHandshake(webSocketHandle!, IntPtr.Zero, 0, IntPtr.Zero, @@ -178,7 +178,7 @@ namespace System.Net.WebSockets Interop.WebSocket.HttpHeader[] additionalHeaders = MarshalHttpHeaders(additionalHeadersPtr, (int)additionalHeaderCount); - string version = null; + string? version = null; foreach (Interop.WebSocket.HttpHeader header in additionalHeaders) { if (string.Equals(header.Name, @@ -216,7 +216,7 @@ namespace System.Net.WebSockets HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } - int errorCode = Interop.WebSocket.WebSocketCreateServerHandle(properties, (uint)propertyCount, out webSocketHandle); + int errorCode = Interop.WebSocket.WebSocketCreateServerHandle(properties!, (uint)propertyCount, out webSocketHandle); ThrowOnError(errorCode); if (webSocketHandle == null || @@ -237,18 +237,18 @@ namespace System.Net.WebSockets // just fake an HTTP handshake for the WSPC calling // WebSocketBeginServerHandshake and WebSocketEndServerHandshake // with statically defined dummy headers. - errorCode = Interop.WebSocket.WebSocketBeginServerHandshake(webSocketHandle, + errorCode = Interop.WebSocket.WebSocketBeginServerHandshake(webSocketHandle!, IntPtr.Zero, IntPtr.Zero, 0, - s_ServerFakeRequestHeaders, - (uint)s_ServerFakeRequestHeaders.Length, + s_ServerFakeRequestHeaders!, + (uint)s_ServerFakeRequestHeaders!.Length, out responseHeadersPtr, out responseHeaderCount); ThrowOnError(errorCode); - errorCode = Interop.WebSocket.WebSocketEndServerHandshake(webSocketHandle); + errorCode = Interop.WebSocket.WebSocketEndServerHandshake(webSocketHandle!); ThrowOnError(errorCode); @@ -370,7 +370,7 @@ namespace System.Net.WebSockets { errorCode = Interop.WebSocket.WebSocketGetAction(webSocket.SessionHandle, actionQueue, - dataBuffers, + dataBuffers!, ref dataBufferCount, out action, out bufferType, @@ -383,11 +383,11 @@ namespace System.Net.WebSockets } ThrowOnError(errorCode); - webSocket.ValidateNativeBuffers(action, bufferType, dataBuffers, dataBufferCount); + webSocket.ValidateNativeBuffers(action, bufferType, dataBuffers!, dataBufferCount); Debug.Assert(dataBufferCount >= 0); Debug.Assert((dataBufferCount == 0 && dataBuffers == null) || - (dataBufferCount <= dataBuffers.Length)); + (dataBufferCount <= dataBuffers!.Length)); } internal static void WebSocketCompleteAction(WebSocketBase webSocket, -- 2.7.4