They're super verbose, very inconsistent, costly, and not helpful (they appear to be trying to provide tracing of the full flow of calls, but they fail to do even that).
private static unsafe string GetKnownHeader(HTTP_REQUEST* request, long fixup, int headerIndex)
{
- if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(null); }
-
string header = null;
HTTP_KNOWN_HEADER* pKnownHeader = (&request->Headers.KnownHeaders) + headerIndex;
header = new string(pKnownHeader->pRawValue + fixup, 0, pKnownHeader->RawValueLength);
}
- if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(null, $"HttpApi::GetKnownHeader() return:{header}"); }
return header;
}
internal static unsafe WebHeaderCollection GetHeaders(IntPtr memoryBlob, IntPtr originalAddress)
{
- NetEventSource.Enter(null);
-
// Return value.
WebHeaderCollection headerCollection = new WebHeaderCollection();
byte* pMemoryBlob = (byte*)memoryBlob;
pKnownHeader++;
}
- NetEventSource.Exit(null);
return headerCollection;
}
internal static unsafe uint GetChunks(IntPtr memoryBlob, IntPtr originalAddress, ref int dataChunkIndex, ref uint dataChunkOffset, byte[] buffer, int offset, int size)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(null, $"HttpApi::GetChunks() memoryBlob:{memoryBlob}");
- }
-
// Return value.
uint dataRead = 0;
byte* pMemoryBlob = (byte*)memoryBlob;
dataChunkIndex = -1;
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(null);
- }
return dataRead;
}
internal static unsafe HTTP_VERB GetKnownVerb(IntPtr memoryBlob, IntPtr originalAddress)
{
- NetEventSource.Enter(null);
-
// Return value.
HTTP_VERB verb = HTTP_VERB.HttpVerbUnknown;
verb = request->Verb;
}
- NetEventSource.Exit(null);
return verb;
}
internal static unsafe IPEndPoint GetRemoteEndPoint(IntPtr memoryBlob, IntPtr originalAddress)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize);
SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize);
endpoint = new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort).Create(v6address) as IPEndPoint;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null);
return endpoint;
}
internal static unsafe IPEndPoint GetLocalEndPoint(IntPtr memoryBlob, IntPtr originalAddress)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize);
SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize);
endpoint = s_ipv6Any.Create(v6address) as IPEndPoint;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null);
return endpoint;
}
{
internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(ISSPIInterface secModule)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
if (secModule.SecurityPackages == null)
{
lock (secModule)
}
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null);
return secModule.SecurityPackages;
}
public static SafeFreeCredentials AcquireDefaultCredential(ISSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(null, package);
- NetEventSource.Log.AcquireDefaultCredential(package, intent);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.AcquireDefaultCredential(package, intent);
SafeFreeCredentials? outCredential = null;
int errorCode = secModule.AcquireDefaultCredential(package, intent, out outCredential);
public static SafeFreeCredentials AcquireCredentialsHandle(ISSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, Interop.SspiCli.SCHANNEL_CRED scc)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(null, package);
- NetEventSource.Log.AcquireCredentialsHandle(package, intent, scc);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.AcquireCredentialsHandle(package, intent, scc);
SafeFreeCredentials? outCredential = null;
int errorCode = secModule.AcquireCredentialsHandle(
throw new Win32Exception(errorCode);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, outCredential);
return outCredential;
}
public static SafeFreeContextBufferChannelBinding? QueryContextChannelBinding(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, contextAttribute);
-
SafeFreeContextBufferChannelBinding result;
int errorCode = secModule.QueryContextChannelBinding(securityContext, contextAttribute, out result);
if (errorCode != 0)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
return null;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, result);
return result;
}
public static bool QueryBlittableContextAttributes<T>(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, ref T attribute) where T : unmanaged
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, contextAttribute);
-
Span<T> span =
#if NETSTANDARD2_0
stackalloc T[1] { attribute };
{
if (errorCode != 0)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
return false;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, attribute);
return true;
}
}
public static bool QueryBlittableContextAttributes<T>(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, Type safeHandleType, out SafeHandle? sspiHandle, ref T attribute) where T : unmanaged
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, contextAttribute);
-
Span<T> span =
#if NETSTANDARD2_0
stackalloc T[1] { attribute };
if (errorCode != 0)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
return false;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, attribute);
return true;
}
contextAttribute == Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NAMES ||
contextAttribute == Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CLIENT_SPECIFIED_TARGET);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, contextAttribute);
Span<IntPtr> buffer = stackalloc IntPtr[1];
int errorCode = secModule.QueryContextAttributes(
{
if (errorCode != 0)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
return null;
}
string? result = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle());
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, result);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, result);
return result;
}
}
public static SafeFreeCertContext? QueryContextAttributes_SECPKG_ATTR_REMOTE_CERT_CONTEXT(ISSPIInterface secModule, SafeDeleteContext securityContext)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
Span<IntPtr> buffer = stackalloc IntPtr[1];
int errorCode = secModule.QueryContextAttributes(
securityContext,
if (errorCode != 0)
{
sspiHandle?.Dispose();
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
return null;
}
var result = (SafeFreeCertContext)sspiHandle!;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, result);
return result;
}
public static bool QueryContextAttributes_SECPKG_ATTR_ISSUER_LIST_EX(ISSPIInterface secModule, SafeDeleteContext securityContext, ref Interop.SspiCli.SecPkgContext_IssuerListInfoEx ctx, out SafeHandle? sspiHandle)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
Span<Interop.SspiCli.SecPkgContext_IssuerListInfoEx> buffer =
#if NETSTANDARD2_0
stackalloc Interop.SspiCli.SecPkgContext_IssuerListInfoEx[1] { ctx };
if (errorCode != 0)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
return false;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, ctx);
return true;
}
Interop.SspiCli.CredentialUse intent,
out SafeFreeCredentials outCredential)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, package, intent);
-
int errorCode = -1;
long timeStamp;
ref Interop.SspiCli.SCHANNEL_CRED authdata,
out SafeFreeCredentials outCredential)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, package, intent, authdata);
-
int errorCode = -1;
long timeStamp;
-
// If there is a certificate, wrap it into an array.
// Not threadsafe.
IntPtr copiedPtr = authdata.paCred;
ref SecurityBuffer outSecBuffer,
ref Interop.SspiCli.ContextFlags outFlags)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, $"credential:{inCredentials}, crefContext:{refContext}, targetName:{targetName}, inFlags:{inFlags}, endianness:{endianness}");
-
if (inCredentials == null)
{
throw new ArgumentNullException(nameof(inCredentials));
outFreeContextBuffer?.Dispose();
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
return errorCode;
}
ref SecurityBuffer outSecBuffer,
ref Interop.SspiCli.ContextFlags outFlags)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, $"credential={inCredentials}, refContext={refContext}, inFlags={inFlags}");
-
if (inCredentials == null)
{
throw new ArgumentNullException(nameof(inCredentials));
}
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
return errorCode;
}
ref SafeDeleteSslContext? refContext,
in SecurityBuffer inSecBuffer)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(null, "SafeDeleteContext::CompleteAuthToken");
- NetEventSource.Info(null, $" refContext = {refContext}");
- NetEventSource.Info(null, $" inSecBuffer = {inSecBuffer}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"refContext = {refContext}, inSecBuffer = {inSecBuffer}");
var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1);
int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle;
}
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"unmanaged CompleteAuthToken() errorCode:0x{errorCode:x8} refContext:{refContext}");
return errorCode;
}
ref SafeDeleteContext? refContext,
in SecurityBuffer inSecBuffer)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(null);
- NetEventSource.Info(null, $" refContext = {refContext}");
- NetEventSource.Info(null, $" inSecBuffer = {inSecBuffer}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"refContext = {refContext}, inSecBuffer = {inSecBuffer}");
int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle;
}
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"unmanaged ApplyControlToken() errorCode:0x{errorCode:x8} refContext: {refContext}");
return errorCode;
}
}
// Usage:
// - Operations that may allocate (e.g. boxing a value type, using string interpolation, etc.) or that may have computations
// at call sites should guard access like:
- // if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, refArg1, valueTypeArg2); // entering an instance method with a value type arg
// if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Found certificate: {cert}"); // info logging with a formattable string
// - Operations that have zero allocations / measurable computations at call sites can use a simpler pattern, calling methods like:
- // NetEventSource.Enter(this); // entering an instance method
// NetEventSource.Info(this, "literal string"); // arbitrary message with a literal string
- // NetEventSource.Enter(this, refArg1, regArg2); // entering an instance method with two reference type arguments
- // NetEventSource.Enter(null); // entering a static method
- // NetEventSource.Enter(null, refArg1); // entering a static method with one reference type argument
// Debug.Asserts inside the logging methods will help to flag some misuse if the DEBUG_NETEVENTSOURCE_MISUSE compilation constant is defined.
// However, because it can be difficult by observation to understand all of the costs involved, guarding can be done everywhere.
// - NetEventSource.Fail calls typically do not need to be prefixed with an IsEnabled check, even if they allocate, as FailMessage
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+ if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
}
/// <summary>Logs entrance to a method.</summary>
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
- if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})");
+ if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})");
}
/// <summary>Logs entrance to a method.</summary>
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
DebugValidateArg(arg1);
- if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})");
+ if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})");
}
/// <summary>Logs entrance to a method.</summary>
DebugValidateArg(arg0);
DebugValidateArg(arg1);
DebugValidateArg(arg2);
- if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})");
+ if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})");
}
[Event(EnterEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+ if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
}
/// <summary>Logs exit from a method.</summary>
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
- if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString());
+ if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString());
}
/// <summary>Logs exit from a method.</summary>
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
DebugValidateArg(arg1);
- if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}");
+ if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}");
}
[Event(ExitEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+ if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
}
/// <summary>Logs an information message.</summary>
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(message);
- if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
}
[Event(InfoEventId, Level = EventLevel.Informational, Keywords = Keywords.Default)]
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
+ if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
}
/// <summary>Logs an error message.</summary>
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(message);
- if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
}
[Event(ErrorEventId, Level = EventLevel.Error, Keywords = Keywords.Default)]
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
// that should never happen in production, and thus we don't care about extra costs.
- if (Log.IsEnabled()) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
+ if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
Debug.Fail(Format(formattableString), $"{IdOf(thisOrContextObject)}.{memberName}");
}
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
// that should never happen in production, and thus we don't care about extra costs.
- if (Log.IsEnabled()) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
Debug.Fail(Format(message).ToString(), $"{IdOf(thisOrContextObject)}.{memberName}");
}
[NonEvent]
public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string? memberName = null)
{
- if (Log.IsEnabled())
+ if (IsEnabled)
{
if (offset < 0 || offset > buffer.Length - count)
{
Debug.Assert(bufferPtr != IntPtr.Zero);
Debug.Assert(count >= 0);
- if (Log.IsEnabled())
+ if (IsEnabled)
{
var buffer = new byte[Math.Min(count, MaxDumpSize)];
fixed (byte* targetPtr = buffer)
{
DebugValidateArg(first);
DebugValidateArg(second);
- if (Log.IsEnabled()) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
+ if (IsEnabled) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
}
/// <summary>Logs a relationship between two objects.</summary>
DebugValidateArg(thisOrContextObject);
DebugValidateArg(first);
DebugValidateArg(second);
- if (Log.IsEnabled()) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
+ if (IsEnabled) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
}
[Event(AssociateEventId, Level = EventLevel.Informational, Keywords = Keywords.Default, Message = "[{2}]<-->[{3}]")]
[Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
private static void DebugValidateArg(object? arg)
{
- if (!Log.IsEnabled())
+ if (!IsEnabled)
{
Debug.Assert(!(arg is ValueType), $"Should not be passing value type {arg?.GetType()} to logging without IsEnabled check");
Debug.Assert(!(arg is FormattableString), $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
[Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
private static void DebugValidateArg(FormattableString? arg)
{
- Debug.Assert(Log.IsEnabled() || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
+ Debug.Assert(IsEnabled || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
}
+ public static new bool IsEnabled =>
+ Log.IsEnabled();
+
[NonEvent]
public static string IdOf(object? value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance;
// constructor for inbound connections
public MsQuicConnection(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, IntPtr nativeObjPtr)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
_localEndPoint = localEndPoint;
_remoteEndPoint = remoteEndPoint;
_ptr = nativeObjPtr;
SetCallbackHandler();
SetIdleTimeout(TimeSpan.FromSeconds(120));
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// constructor for outbound connections
public MsQuicConnection(QuicClientConnectionOptions options)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
// TODO need to figure out if/how we want to expose sessions
// Creating a session per connection isn't ideal.
_session = new MsQuicSession();
SetCallbackHandler();
SetIdleTimeout(options.IdleTimeout);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
internal override IPEndPoint LocalEndPoint
private uint HandleEventConnected(ConnectionEvent connectionEvent)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
SOCKADDR_INET inetAddress = MsQuicParameterHelpers.GetINetParam(MsQuicApi.Api, _ptr, (uint)QUIC_PARAM_LEVEL.CONNECTION, (uint)QUIC_PARAM_CONN.LOCAL_ADDRESS);
_localEndPoint = MsQuicAddressHelpers.INetToIPEndPoint(inetAddress);
// handle event shutdown initiated by transport
_connectTcs.Complete(MsQuicStatusCodes.Success);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return MsQuicStatusCodes.Success;
}
private uint HandleEventShutdownInitiatedByTransport(ConnectionEvent connectionEvent)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
if (!_connected)
{
_connectTcs.CompleteException(new IOException("Connection has been shutdown."));
_acceptQueue.Writer.Complete();
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return MsQuicStatusCodes.Success;
}
private uint HandleEventShutdownComplete(ConnectionEvent connectionEvent)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
_shutdownTcs.Complete(MsQuicStatusCodes.Success);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return MsQuicStatusCodes.Success;
}
private uint HandleEventNewStream(ConnectionEvent connectionEvent)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
MsQuicStream msQuicStream = new MsQuicStream(this, connectionEvent.StreamFlags, connectionEvent.Data.NewStream.Stream, inbound: true);
-
_acceptQueue.Writer.TryWrite(msQuicStream);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return MsQuicStatusCodes.Success;
}
internal override async ValueTask<QuicStreamProvider> AcceptStreamAsync(CancellationToken cancellationToken = default)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
MsQuicStream stream;
};
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return stream;
}
private MsQuicStream StreamOpen(
QUIC_STREAM_OPEN_FLAG flags)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
IntPtr streamPtr = IntPtr.Zero;
QuicExceptionHelpers.ThrowIfFailed(
MsQuicApi.Api.StreamOpenDelegate(
out streamPtr),
"Failed to open stream to peer.");
- MsQuicStream stream = new MsQuicStream(this, flags, streamPtr, inbound: false);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- return stream;
+ return new MsQuicStream(this, flags, streamPtr, inbound: false);
}
private void SetCallbackHandler()
QUIC_CONNECTION_SHUTDOWN_FLAG Flags,
long ErrorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
uint status = MsQuicApi.Api.ConnectionShutdownDelegate(
_ptr,
(uint)Flags,
ErrorCode);
QuicExceptionHelpers.ThrowIfFailed(status, "Failed to shutdown connection.");
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return _shutdownTcs.GetTypelessValueTask();
}
return;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
if (_ptr != IntPtr.Zero)
{
MsQuicApi.Api.ConnectionCloseDelegate?.Invoke(_ptr);
}
_disposed = true;
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
internal override ValueTask CloseAsync(long errorCode, CancellationToken cancellationToken = default)
internal override async ValueTask<QuicConnectionProvider> AcceptConnectionAsync(CancellationToken cancellationToken = default)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
MsQuicConnection connection;
_options.CertificateFilePath,
_options.PrivateKeyFilePath).ConfigureAwait(false);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return connection;
}
internal override async ValueTask WriteAsync(ReadOnlySequence<byte> buffers, bool endStream, CancellationToken cancellationToken = default)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
using CancellationTokenRegistration registration = await HandleWriteStartState(cancellationToken).ConfigureAwait(false);
await SendReadOnlySequenceAsync(buffers, endStream ? QUIC_SEND_FLAG.FIN : QUIC_SEND_FLAG.NONE).ConfigureAwait(false);
HandleWriteCompletedState();
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
internal override ValueTask WriteAsync(ReadOnlyMemory<ReadOnlyMemory<byte>> buffers, CancellationToken cancellationToken = default)
internal override async ValueTask WriteAsync(ReadOnlyMemory<ReadOnlyMemory<byte>> buffers, bool endStream, CancellationToken cancellationToken = default)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
using CancellationTokenRegistration registration = await HandleWriteStartState(cancellationToken).ConfigureAwait(false);
await SendReadOnlyMemoryListAsync(buffers, endStream ? QUIC_SEND_FLAG.FIN : QUIC_SEND_FLAG.NONE).ConfigureAwait(false);
HandleWriteCompletedState();
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
internal override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, bool endStream, CancellationToken cancellationToken = default)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
using CancellationTokenRegistration registration = await HandleWriteStartState(cancellationToken).ConfigureAwait(false);
await SendReadOnlyMemoryAsync(buffer, endStream ? QUIC_SEND_FLAG.FIN : QUIC_SEND_FLAG.NONE).ConfigureAwait(false);
HandleWriteCompletedState();
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
private async ValueTask<CancellationTokenRegistration> HandleWriteStartState(CancellationToken cancellationToken)
internal override async ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
if (!_canRead)
{
if (_readState == ReadState.ReadsCompleted)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return 0;
}
else if (_readState == ReadState.Aborted)
}
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return actual;
}
// If so, we need to complete the read here as well.
internal override void AbortRead(long errorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
lock (_sync)
MsQuicApi.Api.StreamShutdownDelegate(_ptr, (uint)QUIC_STREAM_SHUTDOWN_FLAG.ABORT_RECV, errorCode);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
internal override void AbortWrite(long errorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
bool shouldComplete = false;
}
MsQuicApi.Api.StreamShutdownDelegate(_ptr, (uint)QUIC_STREAM_SHUTDOWN_FLAG.ABORT_SEND, errorCode);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
internal override ValueTask ShutdownWriteCompleted(CancellationToken cancellationToken = default)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
// TODO do anything to stop writes?
}
});
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return _shutdownWriteResettableCompletionSource.GetTypelessValueTask();
}
return default;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
CleanupSendState();
if (_ptr != IntPtr.Zero)
_handle.Free();
_disposed = true;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return default;
}
return;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
CleanupSendState();
if (_ptr != IntPtr.Zero)
_handle.Free();
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
_disposed = true;
}
private unsafe uint HandleEventRecv(ref MsQuicNativeMethods.StreamEvent evt)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
StreamEventDataRecv receieveEvent = evt.Data.Recv;
for (int i = 0; i < receieveEvent.BufferCount; i++)
{
_receiveResettableCompletionSource.Complete((uint)receieveEvent.TotalBufferLength);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return MsQuicStatusCodes.Pending;
}
private uint HandleEventPeerRecvAborted(ref StreamEvent evt)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
bool shouldComplete = false;
lock (_sync)
{
_sendResettableCompletionSource.CompleteException(new QuicStreamAbortedException(_sendErrorCode));
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return MsQuicStatusCodes.Success;
}
private uint HandleStartComplete()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
bool shouldComplete = false;
lock (_sync)
{
_sendResettableCompletionSource.Complete(MsQuicStatusCodes.Success);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return MsQuicStatusCodes.Success;
}
private uint HandleEventSendShutdownComplete(ref MsQuicNativeMethods.StreamEvent evt)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
bool shouldComplete = false;
lock (_sync)
{
_shutdownWriteResettableCompletionSource.Complete(MsQuicStatusCodes.Success);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return MsQuicStatusCodes.Success;
}
private uint HandleEventShutdownComplete()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
bool shouldReadComplete = false;
bool shouldShutdownWriteComplete = false;
_shutdownWriteResettableCompletionSource.Complete(MsQuicStatusCodes.Success);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return MsQuicStatusCodes.Success;
}
private uint HandleEventPeerSendAborted(ref StreamEvent evt)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
bool shouldComplete = false;
lock (_sync)
{
_receiveResettableCompletionSource.CompleteException(new QuicStreamAbortedException(_readErrorCode));
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return MsQuicStatusCodes.Success;
}
private uint HandleEventPeerSendShutdown()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
bool shouldComplete = false;
lock (_sync)
_receiveResettableCompletionSource.Complete(0);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return MsQuicStatusCodes.Success;
}
private uint HandleEventSendComplete(ref StreamEvent evt)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
CleanupSendState();
// TODO throw if a write was canceled.
_sendResettableCompletionSource.Complete(MsQuicStatusCodes.Success);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return MsQuicStatusCodes.Success;
}
{
get
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
#if DEBUG
// Can't be called when state is protected.
if (_protectState)
LazilyCreateEvent(out asyncEvent);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncEvent);
return asyncEvent;
}
}
{
get
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
#if DEBUG
// Can't be called when state is protected.
if (_protectState)
result = Interlocked.CompareExchange(ref _intCompleted, HighBit, 0);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, result > 0);
return result > 0;
}
}
{
get
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
#if DEBUG
// Can't be called when state is protected.
if (_protectState)
// the equivalent of InvokeCallback().
protected void ProtectedInvokeCallback(object? result, IntPtr userToken)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, result, userToken);
-
// Critical to disallow DBNull here - it could result in a stuck spinlock in WaitForCompletion.
if (result == DBNull.Value)
{
sw.SpinOnce();
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, _result);
return _result;
}
// Usage:
// - Operations that may allocate (e.g. boxing a value type, using string interpolation, etc.) or that may have computations
// at call sites should guard access like:
- // if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, refArg1, valueTypeArg2); // entering an instance method with a value type arg
// if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Found certificate: {cert}"); // info logging with a formattable string
// - Operations that have zero allocations / measurable computations at call sites can use a simpler pattern, calling methods like:
- // NetEventSource.Enter(this); // entering an instance method
// NetEventSource.Info(this, "literal string"); // arbitrary message with a literal string
- // NetEventSource.Enter(this, refArg1, regArg2); // entering an instance method with two reference type arguments
- // NetEventSource.Enter(null); // entering a static method
- // NetEventSource.Enter(null, refArg1); // entering a static method with one reference type argument
// Debug.Asserts inside the logging methods will help to flag some misuse if the DEBUG_NETEVENTSOURCE_MISUSE compilation constant is defined.
// However, because it can be difficult by observation to understand all of the costs involved, guarding can be done everywhere.
// - NetEventSource.Fail calls typically do not need to be prefixed with an IsEnabled check, even if they allocate, as FailMessage
{
public const EventKeywords Default = (EventKeywords)0x0001;
public const EventKeywords Debug = (EventKeywords)0x0002;
- public const EventKeywords EnterExit = (EventKeywords)0x0004;
+
+ // No longer used:
+ // EnterExit = (EventKeywords)0x0004;
}
private const string MissingMember = "(?)";
private const string NoParameters = "";
private const int MaxDumpSize = 1024;
- private const int EnterEventId = 1;
- private const int ExitEventId = 2;
+ // No longer used:
+ // EnterEventId = 1;
+ // ExitEventId = 2;
+
private const int AssociateEventId = 3;
private const int InfoEventId = 4;
private const int ErrorEventId = 5;
#endregion
#region Events
- #region Enter
- /// <summary>Logs entrance to a method.</summary>
- /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
- /// <param name="formattableString">A description of the entrance, including any arguments to the call.</param>
- /// <param name="memberName">The calling member.</param>
- [NonEvent]
- public static void Enter(object? thisOrContextObject, FormattableString? formattableString = null, [CallerMemberName] string? memberName = null)
- {
- DebugValidateArg(thisOrContextObject);
- DebugValidateArg(formattableString);
- if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
- }
-
- /// <summary>Logs entrance to a method.</summary>
- /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
- /// <param name="arg0">The object to log.</param>
- /// <param name="memberName">The calling member.</param>
- [NonEvent]
- public static void Enter(object? thisOrContextObject, object? arg0, [CallerMemberName] string? memberName = null)
- {
- DebugValidateArg(thisOrContextObject);
- DebugValidateArg(arg0);
- if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})");
- }
-
- /// <summary>Logs entrance to a method.</summary>
- /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
- /// <param name="arg0">The first object to log.</param>
- /// <param name="arg1">The second object to log.</param>
- /// <param name="memberName">The calling member.</param>
- [NonEvent]
- public static void Enter(object? thisOrContextObject, object? arg0, object? arg1, [CallerMemberName] string? memberName = null)
- {
- DebugValidateArg(thisOrContextObject);
- DebugValidateArg(arg0);
- DebugValidateArg(arg1);
- if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})");
- }
-
- /// <summary>Logs entrance to a method.</summary>
- /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
- /// <param name="arg0">The first object to log.</param>
- /// <param name="arg1">The second object to log.</param>
- /// <param name="arg2">The third object to log.</param>
- /// <param name="memberName">The calling member.</param>
- [NonEvent]
- public static void Enter(object? thisOrContextObject, object? arg0, object? arg1, object? arg2, [CallerMemberName] string? memberName = null)
- {
- DebugValidateArg(thisOrContextObject);
- DebugValidateArg(arg0);
- DebugValidateArg(arg1);
- DebugValidateArg(arg2);
- if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})");
- }
-
- [Event(EnterEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
- private void Enter(string thisOrContextObject, string? memberName, string parameters) =>
- WriteEvent(EnterEventId, thisOrContextObject, memberName ?? MissingMember, parameters);
- #endregion
-
- #region Exit
- /// <summary>Logs exit from a method.</summary>
- /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
- /// <param name="formattableString">A description of the exit operation, including any return values.</param>
- /// <param name="memberName">The calling member.</param>
- [NonEvent]
- public static void Exit(object? thisOrContextObject, FormattableString? formattableString = null, [CallerMemberName] string? memberName = null)
- {
- DebugValidateArg(thisOrContextObject);
- DebugValidateArg(formattableString);
- if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
- }
-
- /// <summary>Logs exit from a method.</summary>
- /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
- /// <param name="arg0">A return value from the member.</param>
- /// <param name="memberName">The calling member.</param>
- [NonEvent]
- public static void Exit(object? thisOrContextObject, object? arg0, [CallerMemberName] string? memberName = null)
- {
- DebugValidateArg(thisOrContextObject);
- DebugValidateArg(arg0);
- if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString());
- }
-
- /// <summary>Logs exit from a method.</summary>
- /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
- /// <param name="arg0">A return value from the member.</param>
- /// <param name="arg1">A second return value from the member.</param>
- /// <param name="memberName">The calling member.</param>
- [NonEvent]
- public static void Exit(object? thisOrContextObject, object? arg0, object? arg1, [CallerMemberName] string? memberName = null)
- {
- DebugValidateArg(thisOrContextObject);
- DebugValidateArg(arg0);
- DebugValidateArg(arg1);
- if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}");
- }
-
- [Event(ExitEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
- private void Exit(string thisOrContextObject, string? memberName, string? result) =>
- WriteEvent(ExitEventId, thisOrContextObject, memberName ?? MissingMember, result);
- #endregion
-
#region Info
/// <summary>Logs an information message.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+ if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
}
/// <summary>Logs an information message.</summary>
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(message);
- if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
}
[Event(InfoEventId, Level = EventLevel.Informational, Keywords = Keywords.Default)]
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
+ if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
}
/// <summary>Logs an error message.</summary>
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(message);
- if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
}
[Event(ErrorEventId, Level = EventLevel.Error, Keywords = Keywords.Default)]
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
// that should never happen in production, and thus we don't care about extra costs.
- if (Log.IsEnabled()) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
+ if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
Debug.Fail(Format(formattableString), $"{IdOf(thisOrContextObject)}.{memberName}");
}
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
// that should never happen in production, and thus we don't care about extra costs.
- if (Log.IsEnabled()) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
Debug.Fail(Format(message).ToString(), $"{IdOf(thisOrContextObject)}.{memberName}");
}
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
+ if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
}
/// <summary>Logs an info at verbose mode.</summary>
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(message);
- if (Log.IsEnabled()) Log.VerboseMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ if (IsEnabled) Log.VerboseMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
}
[Event(ErrorEventId, Level = EventLevel.Verbose, Keywords = Keywords.Default)]
[NonEvent]
public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string? memberName = null)
{
- if (Log.IsEnabled())
+ if (IsEnabled)
{
if (offset < 0 || offset > buffer.Length - count)
{
Debug.Assert(bufferPtr != IntPtr.Zero);
Debug.Assert(count >= 0);
- if (Log.IsEnabled())
+ if (IsEnabled)
{
var buffer = new byte[Math.Min(count, MaxDumpSize)];
fixed (byte* targetPtr = buffer)
{
DebugValidateArg(first);
DebugValidateArg(second);
- if (Log.IsEnabled()) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
+ if (IsEnabled) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
}
/// <summary>Logs a relationship between two objects.</summary>
DebugValidateArg(thisOrContextObject);
DebugValidateArg(first);
DebugValidateArg(second);
- if (Log.IsEnabled()) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
+ if (IsEnabled) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
}
[Event(AssociateEventId, Level = EventLevel.Informational, Keywords = Keywords.Default, Message = "[{2}]<-->[{3}]")]
[Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
private static void DebugValidateArg(object? arg)
{
- if (!Log.IsEnabled())
+ if (!IsEnabled)
{
Debug.Assert(!(arg is ValueType), $"Should not be passing value type {arg?.GetType()} to logging without IsEnabled check");
Debug.Assert(!(arg is FormattableString), $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
[Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
private static void DebugValidateArg(FormattableString? arg)
{
- Debug.Assert(Log.IsEnabled() || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
+ Debug.Assert(IsEnabled || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
}
+ public static new bool IsEnabled =>
+ Log.IsEnabled();
+
[NonEvent]
public static string IdOf(object? value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance;
[MemberNotNull(nameof(_package))]
private void Initialize(bool isServer, string package, NetworkCredential credential, string? spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, package, spn, requestedContextFlags);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"package={package}, spn={spn}, requestedContextFlags={requestedContextFlags}");
_tokenSize = NegotiateStreamPal.QueryMaxTokenSize(package);
_isServer = isServer;
// Accepts an incoming binary security blob and returns an outgoing binary security blob.
internal byte[]? GetOutgoingBlob(byte[]? incomingBlob, bool throwOnError, out SecurityStatusPal statusCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, incomingBlob);
-
byte[]? result = new byte[_tokenSize];
bool firstTime = _securityContext == null;
_isCompleted = true;
if (throwOnError)
{
- Exception exception = NegotiateStreamPal.CreateExceptionFromError(statusCode);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, exception);
- throw exception;
+ throw NegotiateStreamPal.CreateExceptionFromError(statusCode);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, $"null statusCode:0x{((int)statusCode.ErrorCode):x8} ({statusCode})");
return null;
}
else if (firstTime && _credentialsHandle != null)
// Success.
_isCompleted = true;
}
- else if (NetEventSource.Log.IsEnabled())
+ else
{
// We need to continue.
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"need continue statusCode:0x{((int)statusCode.ErrorCode):x8} ({statusCode}) _securityContext:{_securityContext}");
}
- if (NetEventSource.Log.IsEnabled())
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, $"IsCompleted: {IsCompleted}");
- }
-
return result;
}
// a pending operation, it would cause random failures in the other threads when we expect a valid handle.
private void CancelPendingResponseStreamReadOperation()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
lock (_state.Lock)
{
if (_state.AsyncReadInProgress)
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info("after dispose");
}
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
}
public void CancelPendingRequests()
{
CheckDisposed();
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
// With every request we link this cancellation token source.
- CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts,
- new CancellationTokenSource());
+ CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts, new CancellationTokenSource());
currentCts.Cancel();
currentCts.Dispose();
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
#endregion Advanced Send Overloads
protected HttpContent()
{
// Log to get an ID for the current content. This ID is used when the content gets associated to a message.
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this);
// We start with the assumption that we can calculate the content length.
_canCalculateLength = true;
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public Task<string> ReadAsStringAsync() =>
public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, handler);
-
if (handler == null)
{
throw new ArgumentNullException(nameof(handler));
_handler = handler;
_disposeHandler = disposeHandler;
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public virtual HttpResponseMessage Send(HttpRequestMessage request,
}
CheckDisposed();
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, request);
-
- HttpResponseMessage response = _handler.Send(request, cancellationToken);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, response);
-
- return response;
+ return _handler.Send(request, cancellationToken);
}
public virtual Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
}
CheckDisposed();
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, request);
-
- Task<HttpResponseMessage> task = _handler.SendAsync(request, cancellationToken);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, task);
-
- return task;
+ return _handler.SendAsync(request, cancellationToken);
}
public void Dispose()
public HttpRequestMessage(HttpMethod method, Uri? requestUri)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, method, requestUri);
InitializeValues(method, requestUri);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public HttpRequestMessage(HttpMethod method, string? requestUri)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, method, requestUri);
-
// It's OK to have a 'null' request Uri. If HttpClient is used, the 'BaseAddress' will be added.
// If there is no 'BaseAddress', sending this request message will throw.
// Note that we also allow the string to be empty: null and empty are considered equivalent.
{
InitializeValues(method, new Uri(requestUri, UriKind.RelativeOrAbsolute));
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public override string ToString()
public HttpResponseMessage(HttpStatusCode statusCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, statusCode);
-
if (((int)statusCode < 0) || ((int)statusCode > 999))
{
throw new ArgumentOutOfRangeException(nameof(statusCode));
_statusCode = statusCode;
_version = HttpUtilities.DefaultResponseVersion;
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public HttpResponseMessage EnsureSuccessStatusCode()
/// <summary>Removes unusable connections from each pool, and removes stale pools entirely.</summary>
private void RemoveStalePools()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
Debug.Assert(_cleaningTimer != null);
// Iterate through each pool in the set of pools. For each, ask it to clear out
// than reused. This should be a rare occurrence, so for now we don't worry about it. In the
// future, there are a variety of possible ways to address it, such as allowing connections to
// be returned to pools they weren't associated with.
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
private static string GetIdentityIfDefaultCredentialsUsed(bool defaultCredentialsUsed)
internal override async ValueTask<HttpResponseMessage> SendAsync(HttpRequestMessage request, bool async, CancellationToken cancellationToken)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, request, cancellationToken);
-
HttpResponseMessage response = await _initialInnerHandler.SendAsync(request, async, cancellationToken).ConfigureAwait(false);
uint redirectCount = 0;
response = await _redirectInnerHandler.SendAsync(request, async, cancellationToken).ConfigureAwait(false);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
return response;
}
public HttpListener()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
_state = State.Stopped;
_internalLock = new object();
_defaultServiceNames = new ServiceNameStore();
// default: no CBT checks on any platform (appcompat reasons); applies also to PolicyEnforcement
// config element
_extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate
{
get
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
CheckDisposed();
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
return _prefixes;
}
}
internal void AddPrefix(string uriPrefix)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"uriPrefix:{uriPrefix}");
string registeredPrefix = null;
try
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, $"prefix: {registeredPrefix}");
- }
}
internal bool ContainsPrefix(string uriPrefix) => _uriPrefixes.Contains(uriPrefix);
internal bool RemovePrefix(string uriPrefix)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"uriPrefix: {uriPrefix}");
try
{
CheckDisposed();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, $"uriPrefix: {uriPrefix}");
- }
return true;
}
internal void RemoveAll(bool clear)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
- try
+ CheckDisposed();
+ // go through the uri list and unregister for each one of them
+ if (_uriPrefixes.Count > 0)
{
- CheckDisposed();
- // go through the uri list and unregister for each one of them
- if (_uriPrefixes.Count > 0)
+ if (_state == State.Started)
{
- if (_state == State.Started)
+ foreach (string registeredPrefix in _uriPrefixes.Values)
{
- foreach (string registeredPrefix in _uriPrefixes.Values)
- {
- RemovePrefixCore(registeredPrefix);
- }
+ RemovePrefixCore(registeredPrefix);
}
+ }
- if (clear)
- {
- _uriPrefixes.Clear();
- _defaultServiceNames.Clear();
- }
+ if (clear)
+ {
+ _uriPrefixes.Clear();
+ _defaultServiceNames.Clear();
}
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
}
public string Realm
public void Close()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, nameof(Close));
try
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info("HttpListenerRequest::Close()");
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Close {exception}");
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
}
internal void CheckDisposed()
public X509Certificate2 GetClientCertificate()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
- try
- {
- if (ClientCertState == ListenerClientCertState.InProgress)
- throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, $"{nameof(GetClientCertificate)}()/{nameof(BeginGetClientCertificate)}()"));
- ClientCertState = ListenerClientCertState.InProgress;
+ if (ClientCertState == ListenerClientCertState.InProgress)
+ throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, $"{nameof(GetClientCertificate)}()/{nameof(BeginGetClientCertificate)}()"));
+ ClientCertState = ListenerClientCertState.InProgress;
- GetClientCertificateCore();
+ GetClientCertificateCore();
+
+ ClientCertState = ListenerClientCertState.Completed;
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
- ClientCertState = ListenerClientCertState.Completed;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
- }
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
return ClientCertificate;
}
public override int Read(byte[] buffer, int offset, int size)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
+
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (size == 0 || _closed)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, "dataRead:0");
return 0;
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
+
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
protected override void Dispose(bool disposing)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, "_closed:" + _closed);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "_closed:" + _closed);
_closed = true;
base.Dispose(disposing);
-
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this);
}
}
}
public override void Write(byte[] buffer, int offset, int size)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
+
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (_closed)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return;
}
public override void EndWrite(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, $"asyncResult:{asyncResult}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"asyncResult:{asyncResult}");
+
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
protected override void Dispose(bool disposing)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
try
{
if (disposing)
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "_closed:" + _closed);
if (_closed)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return;
}
_closed = true;
{
base.Dispose(disposing);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
}
public void Start()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
lock (_internalLock)
{
try
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Start {exception}");
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
}
}
public void Stop()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
lock (_internalLock)
{
finally
{
_state = State.Stopped;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
}
public void Abort()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
lock (_internalLock)
{
finally
{
_state = State.Closed;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
}
private void Dispose()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
lock (_internalLock)
{
finally
{
_state = State.Closed;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
}
public void Start()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
// Make sure there are no race conditions between Start/Stop/Abort/Close/Dispose and
// calls to SetupV2Config: Start needs to setup all resources (esp. in V2 where besides
// the request handle, there is also a server session and a Url group. Abort/Stop must
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Start {exception}");
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
}
}
public void Stop()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
try
{
lock (_internalLock)
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Stop {exception}");
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
}
private unsafe void CreateRequestQueueHandle()
public void Abort()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
lock (_internalLock)
{
try
finally
{
_state = State.Closed;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
}
private void Dispose()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
lock (_internalLock)
{
try
finally
{
_state = State.Closed;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
}
public HttpListenerContext GetContext()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
SyncRequestContext memoryBlob = null;
HttpListenerContext httpContext = null;
bool stoleBlob = false;
memoryBlob.ReleasePins();
memoryBlob.Close();
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, "RequestTraceIdentifier: " + (httpContext != null ? httpContext.Request.RequestTraceIdentifier.ToString() : "<null>"));
}
}
public IAsyncResult BeginGetContext(AsyncCallback callback, object state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ListenerAsyncResult asyncResult = null;
try
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"BeginGetContext {exception}");
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
return asyncResult;
}
public HttpListenerContext EndGetContext(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
HttpListenerContext httpContext = null;
try
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"EndGetContext {exception}");
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, "EndGetContext " + httpContext == null ? "<no context>" : "HttpListenerContext" + httpContext.ToString() + " RequestTraceIdentifier#" + httpContext.Request.RequestTraceIdentifier);
- }
return httpContext;
}
internal static ChannelBinding GetChannelBindingFromTls(HttpListenerSession session, ulong connectionId)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(session.Listener, $"connectionId: {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
int size = sizeof(Interop.HttpApi.HTTP_REQUEST_CHANNEL_BIND_STATUS) + 128;
internal void Close()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
try
{
_response?.Close();
}
}
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
internal void Abort()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ForceCancelRequest(RequestQueueHandle, Request.RequestId);
try
{
{
(_user?.Identity as IDisposable)?.Dispose();
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
internal Interop.HttpApi.HTTP_VERB GetKnownMethod()
{
get
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
if (_requestStream == null)
{
_requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return _requestStream;
}
}
public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
X509Certificate2 clientCertificate = null;
- try
+
+ if (asyncResult == null)
{
- if (asyncResult == null)
- {
- throw new ArgumentNullException(nameof(asyncResult));
- }
- ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult;
- if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this)
- {
- throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
- }
- if (clientCertAsyncResult.EndCalled)
- {
- throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetClientCertificate)));
- }
- clientCertAsyncResult.EndCalled = true;
- clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
+ throw new ArgumentNullException(nameof(asyncResult));
}
- finally
+ ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult;
+ if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+ throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
+ if (clientCertAsyncResult.EndCalled)
+ {
+ throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetClientCertificate)));
+ }
+ clientCertAsyncResult.EndCalled = true;
+ clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2;
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
+
return clientCertificate;
}
//should only be called from httplistenercontext
internal void Close()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
RequestContextBase memoryBlob = _memoryBlob;
if (memoryBlob != null)
{
_memoryBlob = null;
}
_isDisposed = true;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
private ListenerClientCertAsyncResult BeginGetClientCertificateCore(AsyncCallback requestCallback, object state)
public void Abort()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
- try
- {
- if (Disposed)
- {
- return;
- }
-
- _responseState = ResponseState.Closed;
- HttpListenerContext.Abort();
- }
- finally
+ if (Disposed)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+ return;
}
+
+ _responseState = ResponseState.Closed;
+ HttpListenerContext.Abort();
}
public void Close()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
try
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this);
}
finally
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
public void Close(byte[] responseEntity, bool willBlock)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"responseEntity={responseEntity},willBlock={willBlock}");
- try
+ CheckDisposed();
+ if (responseEntity == null)
{
- CheckDisposed();
- if (responseEntity == null)
- {
- throw new ArgumentNullException(nameof(responseEntity));
- }
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ResponseState:{_responseState}, BoundaryType:{_boundaryType}, ContentLength:{_contentLength}");
- if (!SentHeaders && _boundaryType != BoundaryType.Chunked)
+ throw new ArgumentNullException(nameof(responseEntity));
+ }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ResponseState:{_responseState}, BoundaryType:{_boundaryType}, ContentLength:{_contentLength}");
+ if (!SentHeaders && _boundaryType != BoundaryType.Chunked)
+ {
+ ContentLength64 = responseEntity.Length;
+ }
+ EnsureResponseStream();
+ if (willBlock)
+ {
+ try
{
- ContentLength64 = responseEntity.Length;
+ _responseStream.Write(responseEntity, 0, responseEntity.Length);
}
- EnsureResponseStream();
- if (willBlock)
+ catch (Win32Exception)
{
- try
- {
- _responseStream.Write(responseEntity, 0, responseEntity.Length);
- }
- catch (Win32Exception)
- {
- }
- finally
- {
- _responseStream.Close();
- _responseState = ResponseState.Closed;
- HttpListenerContext.Close();
- }
}
- else
+ finally
{
- _responseStream.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null);
+ _responseStream.Close();
+ _responseState = ResponseState.Closed;
+ HttpListenerContext.Close();
}
}
- finally
+ else
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+ _responseStream.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null);
}
}
{
NetEventSource.DumpBuffer(this, buffer, offset, (int)dataRead);
NetEventSource.Info(this, "returning dataRead:" + dataRead);
- NetEventSource.Exit(this, "dataRead:" + dataRead);
}
return (int)dataRead;
}
{
if (size == 0 || _closed)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
HttpRequestStreamAsyncResult result = new HttpRequestStreamAsyncResult(this, state, callback);
result.InvokeCallback((uint)0);
return result;
asyncResult.IOCompleted(statusCode, bytesReturned);
}
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return asyncResult;
}
public override int EndRead(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, $"asyncResult: {asyncResult}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"asyncResult: {asyncResult}");
+
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
uint dataRead = (uint)returnValue;
UpdateAfterRead((uint)castedAsyncResult.ErrorCode, dataRead);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Info(this, $"returnValue:{returnValue}");
- NetEventSource.Exit(this);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"returnValue:{returnValue}");
return (int)dataRead + (int)castedAsyncResult._dataAlreadyRead;
}
Interop.HttpApi.HTTP_FLAGS flags = ComputeLeftToWrite();
if (size == 0 && _leftToWrite != 0)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return;
}
if (_leftToWrite >= 0 && size > _leftToWrite)
}
UpdateAfterWrite(dataToWrite);
if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer, offset, (int)dataToWrite);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
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))
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
HttpResponseStreamAsyncResult result = new HttpResponseStreamAsyncResult(this, state, callback);
result.InvokeCallback((uint)0);
return result;
_lastWrite = asyncResult;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return asyncResult;
}
ExceptionDispatchInfo.Throw(exception);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
private void UpdateAfterWrite(uint dataWritten)
bool sentHeaders = _httpContext.Response.SentHeaders;
if (sentHeaders && _leftToWrite == 0)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this);
return;
}
private static byte[] GetChunkHeader(int size, out int offset)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, $"size:{size}");
-
uint Mask = 0xf0000000;
byte[] Header = new byte[10];
int i;
Header[8] = (byte)'\r';
Header[9] = (byte)'\n';
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null);
return Header;
}
ArraySegment<byte> internalBuffer)
{
HttpListenerWebSocketContext webSocketContext = null;
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(null, context);
- }
-
try
{
// get property will create a new response if one doesn't exist.
}
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(context);
- }
- }
return webSocketContext;
}
keepAliveInterval,
NetEventSource.GetHashCode(innerStream),
NetEventSource.GetHashCode(internalBuffer));
-
- NetEventSource.Enter(this, parameters);
}
_thisLock = new object();
- try
+ _innerStream = innerStream;
+ _internalBuffer = internalBuffer;
+ if (NetEventSource.Log.IsEnabled())
{
- _innerStream = innerStream;
- _internalBuffer = internalBuffer;
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Associate(this, _innerStream);
- NetEventSource.Associate(this, _internalBuffer);
- }
-
- _closeOutstandingOperationHelper = new OutstandingOperationHelper();
- _closeOutputOutstandingOperationHelper = new OutstandingOperationHelper();
- _receiveOutstandingOperationHelper = new OutstandingOperationHelper();
- _sendOutstandingOperationHelper = new OutstandingOperationHelper();
- _state = WebSocketState.Open;
- _subProtocol = subProtocol;
- _sendFrameThrottle = new SemaphoreSlim(1, 1);
- _closeStatus = null;
- _closeStatusDescription = null;
- _innerStreamAsWebSocketStream = innerStream as IWebSocketStream;
- if (_innerStreamAsWebSocketStream != null)
- {
- _innerStreamAsWebSocketStream.SwitchToOpaqueMode(this);
- }
- _keepAliveTracker = KeepAliveTracker.Create(keepAliveInterval);
+ NetEventSource.Associate(this, _innerStream);
+ NetEventSource.Associate(this, _internalBuffer);
}
- finally
+
+ _closeOutstandingOperationHelper = new OutstandingOperationHelper();
+ _closeOutputOutstandingOperationHelper = new OutstandingOperationHelper();
+ _receiveOutstandingOperationHelper = new OutstandingOperationHelper();
+ _sendOutstandingOperationHelper = new OutstandingOperationHelper();
+ _state = WebSocketState.Open;
+ _subProtocol = subProtocol;
+ _sendFrameThrottle = new SemaphoreSlim(1, 1);
+ _closeStatus = null;
+ _closeStatusDescription = null;
+ _innerStreamAsWebSocketStream = innerStream as IWebSocketStream;
+ if (_innerStreamAsWebSocketStream != null)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this, parameters);
- }
+ _innerStreamAsWebSocketStream.SwitchToOpaqueMode(this);
}
+ _keepAliveTracker = KeepAliveTracker.Create(keepAliveInterval);
}
public override WebSocketState State
private async Task<WebSocketReceiveResult> ReceiveAsyncCore(ArraySegment<byte> buffer,
CancellationToken cancellationToken)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- }
-
WebSocketReceiveResult receiveResult;
+
+ ThrowIfPendingException();
+ ThrowIfDisposed();
+ ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseSent);
+
+ bool ownsCancellationTokenSource = false;
+ CancellationToken linkedCancellationToken = CancellationToken.None;
try
{
- ThrowIfPendingException();
- ThrowIfDisposed();
- ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseSent);
-
- bool ownsCancellationTokenSource = false;
- CancellationToken linkedCancellationToken = CancellationToken.None;
- try
+ ownsCancellationTokenSource = _receiveOutstandingOperationHelper.TryStartOperation(cancellationToken,
+ out linkedCancellationToken);
+ if (!ownsCancellationTokenSource)
{
- ownsCancellationTokenSource = _receiveOutstandingOperationHelper.TryStartOperation(cancellationToken,
- out linkedCancellationToken);
- if (!ownsCancellationTokenSource)
+ lock (_thisLock)
{
- lock (_thisLock)
+ if (_closeAsyncStartedReceive)
{
- if (_closeAsyncStartedReceive)
- {
- throw new InvalidOperationException(
- SR.Format(SR.net_WebSockets_ReceiveAsyncDisallowedAfterCloseAsync, nameof(CloseAsync), nameof(CloseOutputAsync)));
- }
-
throw new InvalidOperationException(
- SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(ReceiveAsync)));
+ SR.Format(SR.net_WebSockets_ReceiveAsyncDisallowedAfterCloseAsync, nameof(CloseAsync), nameof(CloseOutputAsync)));
}
- }
- EnsureReceiveOperation();
- receiveResult = await _receiveOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow();
-
- if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0)
- {
- NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, receiveResult.Count);
+ throw new InvalidOperationException(
+ SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(ReceiveAsync)));
}
}
- catch (Exception exception)
- {
- bool aborted = linkedCancellationToken.IsCancellationRequested;
- Abort();
- ThrowIfConvertibleException(nameof(ReceiveAsync), exception, cancellationToken, aborted);
- throw;
- }
- finally
+
+ EnsureReceiveOperation();
+ receiveResult = await _receiveOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow();
+
+ if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0)
{
- _receiveOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
+ NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, receiveResult.Count);
}
}
+ catch (Exception exception)
+ {
+ bool aborted = linkedCancellationToken.IsCancellationRequested;
+ Abort();
+ ThrowIfConvertibleException(nameof(ReceiveAsync), exception, cancellationToken, aborted);
+ throw;
+ }
finally
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this);
- }
+ _receiveOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
}
return receiveResult;
"messageType: {0}, endOfMessage: {1}",
messageType,
endOfMessage);
- NetEventSource.Enter(this, inputParameter);
}
+ ThrowIfPendingException();
+ ThrowIfDisposed();
+ ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived);
+ bool ownsCancellationTokenSource = false;
+ CancellationToken linkedCancellationToken = CancellationToken.None;
+
try
{
- ThrowIfPendingException();
- ThrowIfDisposed();
- ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived);
- bool ownsCancellationTokenSource = false;
- CancellationToken linkedCancellationToken = CancellationToken.None;
-
- try
+ while (!(ownsCancellationTokenSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken)))
{
- while (!(ownsCancellationTokenSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken)))
+ Task keepAliveTask;
+
+ lock (SessionHandle)
{
- Task keepAliveTask;
+ keepAliveTask = _keepAliveTask;
- lock (SessionHandle)
+ if (keepAliveTask == null)
{
- keepAliveTask = _keepAliveTask;
-
- if (keepAliveTask == null)
+ // Check whether there is still another outstanding send operation
+ // Potentially the keepAlive operation has completed before this thread
+ // was able to enter the SessionHandle-lock.
+ _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
+ if (ownsCancellationTokenSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken))
{
- // Check whether there is still another outstanding send operation
- // Potentially the keepAlive operation has completed before this thread
- // was able to enter the SessionHandle-lock.
- _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
- if (ownsCancellationTokenSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken))
- {
- break;
- }
- else
- {
- throw new InvalidOperationException(
- SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(SendAsync)));
- }
+ break;
+ }
+ else
+ {
+ throw new InvalidOperationException(
+ SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(SendAsync)));
}
}
-
- await keepAliveTask.SuppressContextFlow();
- ThrowIfPendingException();
-
- _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
}
- if (NetEventSource.Log.IsEnabled() && buffer.Count > 0)
- {
- NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, buffer.Count);
- }
+ await keepAliveTask.SuppressContextFlow();
+ ThrowIfPendingException();
- EnsureSendOperation();
- _sendOperation.BufferType = GetBufferType(messageType, endOfMessage);
- await _sendOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow();
- }
- catch (Exception exception)
- {
- bool aborted = linkedCancellationToken.IsCancellationRequested;
- Abort();
- ThrowIfConvertibleException(nameof(SendAsync), exception, cancellationToken, aborted);
- throw;
+ _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
}
- finally
+
+ if (NetEventSource.Log.IsEnabled() && buffer.Count > 0)
{
- _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
+ NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, buffer.Count);
}
+
+ EnsureSendOperation();
+ _sendOperation.BufferType = GetBufferType(messageType, endOfMessage);
+ await _sendOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow();
+ }
+ catch (Exception exception)
+ {
+ bool aborted = linkedCancellationToken.IsCancellationRequested;
+ Abort();
+ ThrowIfConvertibleException(nameof(SendAsync), exception, cancellationToken, aborted);
+ throw;
}
finally
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this, inputParameter);
- }
+ _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
}
}
// MultiThreading: ThreadSafe; No-op if already in a terminal state
public override void Abort()
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- }
-
bool thisLockTaken = false;
bool sessionHandleLockTaken = false;
try
finally
{
ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this);
- }
}
}
"closeStatus: {0}, statusDescription: {1}",
closeStatus,
statusDescription);
- NetEventSource.Enter(this, inputParameter);
}
+ ThrowIfPendingException();
+ if (IsStateTerminal(State))
+ {
+ return;
+ }
+ ThrowIfDisposed();
+
+ bool thisLockTaken = false;
+ bool sessionHandleLockTaken = false;
+ bool needToCompleteSendOperation = false;
+ bool ownsCloseOutputCancellationTokenSource = false;
+ bool ownsSendCancellationTokenSource = false;
+ CancellationToken linkedCancellationToken = CancellationToken.None;
try
{
+ TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
ThrowIfPendingException();
+ ThrowIfDisposed();
+
if (IsStateTerminal(State))
{
return;
}
- ThrowIfDisposed();
- bool thisLockTaken = false;
- bool sessionHandleLockTaken = false;
- bool needToCompleteSendOperation = false;
- bool ownsCloseOutputCancellationTokenSource = false;
- bool ownsSendCancellationTokenSource = false;
- CancellationToken linkedCancellationToken = CancellationToken.None;
- try
+ ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived);
+ ownsCloseOutputCancellationTokenSource = _closeOutputOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
+ if (!ownsCloseOutputCancellationTokenSource)
{
- TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
- ThrowIfPendingException();
- ThrowIfDisposed();
+ Task closeOutputTask = _closeOutputTask;
- if (IsStateTerminal(State))
+ if (closeOutputTask != null)
{
- return;
+ ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+ await closeOutputTask.SuppressContextFlow();
+ TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
}
-
- ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived);
- ownsCloseOutputCancellationTokenSource = _closeOutputOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
- if (!ownsCloseOutputCancellationTokenSource)
+ }
+ else
+ {
+ needToCompleteSendOperation = true;
+ while (!(ownsSendCancellationTokenSource =
+ _sendOutstandingOperationHelper.TryStartOperation(cancellationToken,
+ out linkedCancellationToken)))
{
- Task closeOutputTask = _closeOutputTask;
-
- if (closeOutputTask != null)
+ if (_keepAliveTask != null)
{
+ Task keepAliveTask = _keepAliveTask;
+
ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
- await closeOutputTask.SuppressContextFlow();
+ await keepAliveTask.SuppressContextFlow();
TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+
+ ThrowIfPendingException();
}
- }
- else
- {
- needToCompleteSendOperation = true;
- while (!(ownsSendCancellationTokenSource =
- _sendOutstandingOperationHelper.TryStartOperation(cancellationToken,
- out linkedCancellationToken)))
+ else
{
- if (_keepAliveTask != null)
- {
- Task keepAliveTask = _keepAliveTask;
-
- ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
- await keepAliveTask.SuppressContextFlow();
- TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
-
- ThrowIfPendingException();
- }
- else
- {
- throw new InvalidOperationException(
- SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(SendAsync)));
- }
-
- _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationTokenSource);
+ throw new InvalidOperationException(
+ SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(SendAsync)));
}
- EnsureCloseOutputOperation();
- _closeOutputOperation.CloseStatus = closeStatus;
- _closeOutputOperation.CloseReason = statusDescription;
- _closeOutputTask = _closeOutputOperation.Process(null, linkedCancellationToken);
+ _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationTokenSource);
+ }
- ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
- await _closeOutputTask.SuppressContextFlow();
- TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+ EnsureCloseOutputOperation();
+ _closeOutputOperation.CloseStatus = closeStatus;
+ _closeOutputOperation.CloseReason = statusDescription;
+ _closeOutputTask = _closeOutputOperation.Process(null, linkedCancellationToken);
- if (OnCloseOutputCompleted())
- {
- bool callCompleteOnCloseCompleted = false;
+ ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+ await _closeOutputTask.SuppressContextFlow();
+ TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
- try
- {
- callCompleteOnCloseCompleted = await StartOnCloseCompleted(
- thisLockTaken, sessionHandleLockTaken, linkedCancellationToken).SuppressContextFlow();
- }
- catch (Exception)
- {
- // If an exception is thrown we know that the locks have been released,
- // because we enforce IWebSocketStream.CloseNetworkConnectionAsync to yield
- ResetFlagsAndTakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
- throw;
- }
+ if (OnCloseOutputCompleted())
+ {
+ bool callCompleteOnCloseCompleted = false;
- if (callCompleteOnCloseCompleted)
- {
- ResetFlagsAndTakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
- FinishOnCloseCompleted();
- }
+ try
+ {
+ callCompleteOnCloseCompleted = await StartOnCloseCompleted(
+ thisLockTaken, sessionHandleLockTaken, linkedCancellationToken).SuppressContextFlow();
+ }
+ catch (Exception)
+ {
+ // If an exception is thrown we know that the locks have been released,
+ // because we enforce IWebSocketStream.CloseNetworkConnectionAsync to yield
+ ResetFlagsAndTakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+ throw;
}
- }
- }
- catch (Exception exception)
- {
- bool aborted = linkedCancellationToken.IsCancellationRequested;
- Abort();
- ThrowIfConvertibleException(nameof(CloseOutputAsync), exception, cancellationToken, aborted);
- throw;
- }
- finally
- {
- _closeOutputOutstandingOperationHelper.CompleteOperation(ownsCloseOutputCancellationTokenSource);
- if (needToCompleteSendOperation)
- {
- _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationTokenSource);
+ if (callCompleteOnCloseCompleted)
+ {
+ ResetFlagsAndTakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+ FinishOnCloseCompleted();
+ }
}
-
- _closeOutputTask = null;
- ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
}
}
+ catch (Exception exception)
+ {
+ bool aborted = linkedCancellationToken.IsCancellationRequested;
+ Abort();
+ ThrowIfConvertibleException(nameof(CloseOutputAsync), exception, cancellationToken, aborted);
+ throw;
+ }
finally
{
- if (NetEventSource.Log.IsEnabled())
+ _closeOutputOutstandingOperationHelper.CompleteOperation(ownsCloseOutputCancellationTokenSource);
+
+ if (needToCompleteSendOperation)
{
- NetEventSource.Exit(this, inputParameter);
+ _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationTokenSource);
}
+
+ _closeOutputTask = null;
+ ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
}
}
"closeStatus: {0}, statusDescription: {1}",
closeStatus,
statusDescription);
- NetEventSource.Enter(this, inputParameter);
}
+ ThrowIfPendingException();
+ if (IsStateTerminal(State))
+ {
+ return;
+ }
+ ThrowIfDisposed();
+
+ bool lockTaken = false;
+ Monitor.Enter(_thisLock, ref lockTaken);
+ bool ownsCloseCancellationTokenSource = false;
+ CancellationToken linkedCancellationToken = CancellationToken.None;
try
{
ThrowIfPendingException();
return;
}
ThrowIfDisposed();
+ ThrowOnInvalidState(State,
+ WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent);
- bool lockTaken = false;
- Monitor.Enter(_thisLock, ref lockTaken);
- bool ownsCloseCancellationTokenSource = false;
- CancellationToken linkedCancellationToken = CancellationToken.None;
- try
+ Task closeOutputTask;
+ ownsCloseCancellationTokenSource = _closeOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
+ if (ownsCloseCancellationTokenSource)
{
- ThrowIfPendingException();
- if (IsStateTerminal(State))
+ closeOutputTask = _closeOutputTask;
+ if (closeOutputTask == null && State != WebSocketState.CloseSent)
{
- return;
+ _closeReceivedTaskCompletionSource ??= new TaskCompletionSource();
+
+ closeOutputTask = CloseOutputAsync(closeStatus,
+ statusDescription,
+ linkedCancellationToken);
}
- ThrowIfDisposed();
- ThrowOnInvalidState(State,
- WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent);
+ }
+ else
+ {
+ Debug.Assert(_closeReceivedTaskCompletionSource != null, "'_closeReceivedTaskCompletionSource' MUST NOT be NULL.");
+ closeOutputTask = _closeReceivedTaskCompletionSource.Task;
+ }
- Task closeOutputTask;
- ownsCloseCancellationTokenSource = _closeOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
- if (ownsCloseCancellationTokenSource)
+ if (closeOutputTask != null)
+ {
+ ReleaseLock(_thisLock, ref lockTaken);
+ try
{
- closeOutputTask = _closeOutputTask;
- if (closeOutputTask == null && State != WebSocketState.CloseSent)
- {
- _closeReceivedTaskCompletionSource ??= new TaskCompletionSource();
+ await closeOutputTask.SuppressContextFlow();
+ }
+ catch (Exception closeOutputError)
+ {
+ Monitor.Enter(_thisLock, ref lockTaken);
- closeOutputTask = CloseOutputAsync(closeStatus,
- statusDescription,
- linkedCancellationToken);
+ if (!CanHandleExceptionDuringClose(closeOutputError))
+ {
+ ThrowIfConvertibleException(nameof(CloseOutputAsync),
+ closeOutputError,
+ cancellationToken,
+ linkedCancellationToken.IsCancellationRequested);
+ throw;
}
}
- else
+
+ // When closeOutputTask != null and an exception thrown from await closeOutputTask is handled,
+ // the lock will be taken in the catch-block. So the logic here avoids taking the lock twice.
+ if (!lockTaken)
{
- Debug.Assert(_closeReceivedTaskCompletionSource != null, "'_closeReceivedTaskCompletionSource' MUST NOT be NULL.");
- closeOutputTask = _closeReceivedTaskCompletionSource.Task;
+ Monitor.Enter(_thisLock, ref lockTaken);
}
+ }
- if (closeOutputTask != null)
+ if (OnCloseOutputCompleted())
+ {
+ bool callCompleteOnCloseCompleted = false;
+
+ try
{
- ReleaseLock(_thisLock, ref lockTaken);
- try
+ // linkedCancellationToken can be CancellationToken.None if ownsCloseCancellationTokenSource==false
+ // This is still ok because OnCloseOutputCompleted won't start any IO operation in this case
+ callCompleteOnCloseCompleted = await StartOnCloseCompleted(
+ lockTaken, false, linkedCancellationToken).SuppressContextFlow();
+ }
+ catch (Exception)
+ {
+ // If an exception is thrown we know that the locks have been released,
+ // because we enforce IWebSocketStream.CloseNetworkConnectionAsync to yield
+ ResetFlagAndTakeLock(_thisLock, ref lockTaken);
+ throw;
+ }
+
+ if (callCompleteOnCloseCompleted)
+ {
+ ResetFlagAndTakeLock(_thisLock, ref lockTaken);
+ FinishOnCloseCompleted();
+ }
+ }
+
+ if (IsStateTerminal(State))
+ {
+ return;
+ }
+
+ linkedCancellationToken = CancellationToken.None;
+
+ bool ownsReceiveCancellationTokenSource = _receiveOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
+ if (ownsReceiveCancellationTokenSource)
+ {
+ _closeAsyncStartedReceive = true;
+ ArraySegment<byte> closeMessageBuffer =
+ new ArraySegment<byte>(new byte[HttpWebSocket.MinReceiveBufferSize]);
+ EnsureReceiveOperation();
+ Task<WebSocketReceiveResult> receiveAsyncTask = _receiveOperation.Process(closeMessageBuffer,
+ linkedCancellationToken);
+ ReleaseLock(_thisLock, ref lockTaken);
+
+ WebSocketReceiveResult receiveResult = null;
+ try
+ {
+ receiveResult = await receiveAsyncTask.SuppressContextFlow();
+ }
+ catch (Exception receiveException)
+ {
+ Monitor.Enter(_thisLock, ref lockTaken);
+
+ if (!CanHandleExceptionDuringClose(receiveException))
{
- await closeOutputTask.SuppressContextFlow();
+ ThrowIfConvertibleException(nameof(CloseAsync),
+ receiveException,
+ cancellationToken,
+ linkedCancellationToken.IsCancellationRequested);
+ throw;
}
- catch (Exception closeOutputError)
- {
- Monitor.Enter(_thisLock, ref lockTaken);
+ }
- if (!CanHandleExceptionDuringClose(closeOutputError))
- {
- ThrowIfConvertibleException(nameof(CloseOutputAsync),
- closeOutputError,
- cancellationToken,
- linkedCancellationToken.IsCancellationRequested);
- throw;
- }
+ // receiveResult is NEVER NULL if WebSocketBase.ReceiveOperation.Process completes successfully
+ // - but in the close code path we handle some exception if another thread was able to tranistion
+ // the state into Closed successfully. In this case receiveResult can be NULL and it is safe to
+ // skip the statements in the if-block.
+ if (receiveResult != null)
+ {
+ if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0)
+ {
+ NetEventSource.DumpBuffer(this, closeMessageBuffer.Array, closeMessageBuffer.Offset, receiveResult.Count);
}
- // When closeOutputTask != null and an exception thrown from await closeOutputTask is handled,
- // the lock will be taken in the catch-block. So the logic here avoids taking the lock twice.
- if (!lockTaken)
+ if (receiveResult.MessageType != WebSocketMessageType.Close)
{
- Monitor.Enter(_thisLock, ref lockTaken);
+ throw new WebSocketException(WebSocketError.InvalidMessageType,
+ SR.Format(SR.net_WebSockets_InvalidMessageType,
+ typeof(WebSocket).Name + "." + nameof(CloseAsync),
+ typeof(WebSocket).Name + "." + nameof(CloseOutputAsync),
+ receiveResult.MessageType));
}
}
+ }
+ else
+ {
+ _receiveOutstandingOperationHelper.CompleteOperation(ownsReceiveCancellationTokenSource);
+ ReleaseLock(_thisLock, ref lockTaken);
+ await _closeReceivedTaskCompletionSource.Task.SuppressContextFlow();
+ }
- if (OnCloseOutputCompleted())
+ // When ownsReceiveCancellationTokenSource is true and an exception is thrown, the lock will be taken.
+ // So this logic here is to avoid taking the lock twice.
+ if (!lockTaken)
+ {
+ Monitor.Enter(_thisLock, ref lockTaken);
+ }
+
+ if (!IsStateTerminal(State))
+ {
+ bool ownsSendCancellationSource = false;
+ try
{
+ // We know that the CloseFrame has been sent at this point. So no Send-operation is allowed anymore and we
+ // can hijack the _SendOutstandingOperationHelper to create a linkedCancellationToken
+ ownsSendCancellationSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
+ Debug.Assert(ownsSendCancellationSource, "'ownsSendCancellationSource' MUST be 'true' at this point.");
+
bool callCompleteOnCloseCompleted = false;
try
FinishOnCloseCompleted();
}
}
-
- if (IsStateTerminal(State))
- {
- return;
- }
-
- linkedCancellationToken = CancellationToken.None;
-
- bool ownsReceiveCancellationTokenSource = _receiveOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
- if (ownsReceiveCancellationTokenSource)
- {
- _closeAsyncStartedReceive = true;
- ArraySegment<byte> closeMessageBuffer =
- new ArraySegment<byte>(new byte[HttpWebSocket.MinReceiveBufferSize]);
- EnsureReceiveOperation();
- Task<WebSocketReceiveResult> receiveAsyncTask = _receiveOperation.Process(closeMessageBuffer,
- linkedCancellationToken);
- ReleaseLock(_thisLock, ref lockTaken);
-
- WebSocketReceiveResult receiveResult = null;
- try
- {
- receiveResult = await receiveAsyncTask.SuppressContextFlow();
- }
- catch (Exception receiveException)
- {
- Monitor.Enter(_thisLock, ref lockTaken);
-
- if (!CanHandleExceptionDuringClose(receiveException))
- {
- ThrowIfConvertibleException(nameof(CloseAsync),
- receiveException,
- cancellationToken,
- linkedCancellationToken.IsCancellationRequested);
- throw;
- }
- }
-
- // receiveResult is NEVER NULL if WebSocketBase.ReceiveOperation.Process completes successfully
- // - but in the close code path we handle some exception if another thread was able to tranistion
- // the state into Closed successfully. In this case receiveResult can be NULL and it is safe to
- // skip the statements in the if-block.
- if (receiveResult != null)
- {
- if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0)
- {
- NetEventSource.DumpBuffer(this, closeMessageBuffer.Array, closeMessageBuffer.Offset, receiveResult.Count);
- }
-
- if (receiveResult.MessageType != WebSocketMessageType.Close)
- {
- throw new WebSocketException(WebSocketError.InvalidMessageType,
- SR.Format(SR.net_WebSockets_InvalidMessageType,
- typeof(WebSocket).Name + "." + nameof(CloseAsync),
- typeof(WebSocket).Name + "." + nameof(CloseOutputAsync),
- receiveResult.MessageType));
- }
- }
- }
- else
- {
- _receiveOutstandingOperationHelper.CompleteOperation(ownsReceiveCancellationTokenSource);
- ReleaseLock(_thisLock, ref lockTaken);
- await _closeReceivedTaskCompletionSource.Task.SuppressContextFlow();
- }
-
- // When ownsReceiveCancellationTokenSource is true and an exception is thrown, the lock will be taken.
- // So this logic here is to avoid taking the lock twice.
- if (!lockTaken)
+ finally
{
- Monitor.Enter(_thisLock, ref lockTaken);
+ _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationSource);
}
-
- if (!IsStateTerminal(State))
- {
- bool ownsSendCancellationSource = false;
- try
- {
- // We know that the CloseFrame has been sent at this point. So no Send-operation is allowed anymore and we
- // can hijack the _SendOutstandingOperationHelper to create a linkedCancellationToken
- ownsSendCancellationSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
- Debug.Assert(ownsSendCancellationSource, "'ownsSendCancellationSource' MUST be 'true' at this point.");
-
- bool callCompleteOnCloseCompleted = false;
-
- try
- {
- // linkedCancellationToken can be CancellationToken.None if ownsCloseCancellationTokenSource==false
- // This is still ok because OnCloseOutputCompleted won't start any IO operation in this case
- callCompleteOnCloseCompleted = await StartOnCloseCompleted(
- lockTaken, false, linkedCancellationToken).SuppressContextFlow();
- }
- catch (Exception)
- {
- // If an exception is thrown we know that the locks have been released,
- // because we enforce IWebSocketStream.CloseNetworkConnectionAsync to yield
- ResetFlagAndTakeLock(_thisLock, ref lockTaken);
- throw;
- }
-
- if (callCompleteOnCloseCompleted)
- {
- ResetFlagAndTakeLock(_thisLock, ref lockTaken);
- FinishOnCloseCompleted();
- }
- }
- finally
- {
- _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationSource);
- }
- }
- }
- catch (Exception exception)
- {
- bool aborted = linkedCancellationToken.IsCancellationRequested;
- Abort();
- ThrowIfConvertibleException(nameof(CloseAsync), exception, cancellationToken, aborted);
- throw;
- }
- finally
- {
- _closeOutstandingOperationHelper.CompleteOperation(ownsCloseCancellationTokenSource);
- ReleaseLock(_thisLock, ref lockTaken);
}
}
+ catch (Exception exception)
+ {
+ bool aborted = linkedCancellationToken.IsCancellationRequested;
+ Abort();
+ ThrowIfConvertibleException(nameof(CloseAsync), exception, cancellationToken, aborted);
+ throw;
+ }
finally
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this, inputParameter);
- }
+ _closeOutstandingOperationHelper.CompleteOperation(ownsCloseCancellationTokenSource);
+ ReleaseLock(_thisLock, ref lockTaken);
}
}
WebSocketBase thisPtr = sender as WebSocketBase;
bool lockTaken = false;
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(thisPtr);
- }
-
CancellationToken linkedCancellationToken = CancellationToken.None;
try
{
finally
{
ReleaseLock(thisPtr.SessionHandle, ref lockTaken);
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(thisPtr);
- }
}
}
private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this, HttpWebSocket.GetTraceMsgForParameters(offset, count, cancellationToken));
- }
-
CancellationTokenRegistration cancellationTokenRegistration = default;
int bytesRead = 0;
finally
{
cancellationTokenRegistration.Dispose();
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this, bytesRead);
- }
}
return bytesRead;
// true: async completion or error
private unsafe bool ReadAsyncFast(HttpListenerAsyncEventArgs eventArgs)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- }
-
eventArgs.StartOperationCommon(this, _inputStream.InternalHttpContext.RequestQueueBoundHandle);
eventArgs.StartOperationReceive();
completedAsynchronouslyOrWithError = true;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this, completedAsynchronouslyOrWithError);
- }
- }
return completedAsynchronouslyOrWithError;
}
Debug.Assert(sendBuffers != null, "'sendBuffers' MUST NOT be NULL.");
Debug.Assert(sendBuffers.Count == 2, "'sendBuffers.Count' MUST be '2' at this point.");
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- }
-
CancellationTokenRegistration cancellationTokenRegistration = default;
try
finally
{
cancellationTokenRegistration.Dispose();
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this);
- }
}
}
private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this, HttpWebSocket.GetTraceMsgForParameters(offset, count, cancellationToken));
- }
-
CancellationTokenRegistration cancellationTokenRegistration = default;
try
finally
{
cancellationTokenRegistration.Dispose();
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this);
- }
}
}
// true: async completion or with error
private unsafe bool WriteAsyncFast(HttpListenerAsyncEventArgs eventArgs)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- }
-
Interop.HttpApi.HTTP_FLAGS flags = Interop.HttpApi.HTTP_FLAGS.NONE;
eventArgs.StartOperationCommon(this, _outputStream.InternalHttpContext.RequestQueueBoundHandle);
completedAsynchronouslyOrWithError = true;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this, completedAsynchronouslyOrWithError);
- }
- }
return completedAsynchronouslyOrWithError;
}
// need to yield here to make sure that we don't get any exception synchronously
await Task.Yield();
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- }
-
CancellationTokenRegistration cancellationTokenRegistration = default;
try
finally
{
cancellationTokenRegistration.Dispose();
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this);
- }
}
}
WebSocketHttpListenerDuplexStream thisPtr = state as WebSocketHttpListenerDuplexStream;
Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL.");
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(state);
- }
-
try
{
thisPtr._outputStream.SetClosedFlag();
thisPtr._readTaskCompletionSource?.TrySetCanceled();
thisPtr._writeTaskCompletionSource?.TrySetCanceled();
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(state);
- }
}
public void SwitchToOpaqueMode(WebSocketBase webSocket)
"'thisPtr.m_OutstandingOperations.m_Writes' MUST NOT be negative.");
#endif
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(thisPtr);
- }
-
if (eventArgs.Exception != null)
{
thisPtr._writeTaskCompletionSource.TrySetException(eventArgs.Exception);
{
thisPtr._writeTaskCompletionSource.TrySetResult();
}
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(thisPtr);
- }
}
private static void OnReadCompleted(object sender, HttpListenerAsyncEventArgs eventArgs)
"'thisPtr.m_OutstandingOperations.m_Reads' MUST NOT be negative.");
#endif
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(thisPtr);
- }
-
if (eventArgs.Exception != null)
{
thisPtr._readTaskCompletionSource.TrySetException(eventArgs.Exception);
{
thisPtr._readTaskCompletionSource.TrySetResult(eventArgs.BytesTransferred);
}
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(thisPtr);
- }
}
internal class HttpListenerAsyncEventArgs : EventArgs, IDisposable
public SmtpClient()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
- try
- {
- Initialize();
- }
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
+ Initialize();
}
public SmtpClient(string? host)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host);
- try
- {
- _host = host;
- Initialize();
- }
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
+ _host = host;
+ Initialize();
}
public SmtpClient(string? host, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host, port);
try
{
if (port < 0)
}
finally
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
public void Send(MailMessage message)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, message);
-
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
- try
+
+ if (NetEventSource.Log.IsEnabled())
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}");
- NetEventSource.Associate(this, message);
- }
+ NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}");
+ NetEventSource.Associate(this, message);
+ }
- SmtpFailedRecipientException? recipientException = null;
+ SmtpFailedRecipientException? recipientException = null;
- if (InCall)
- {
- throw new InvalidOperationException(SR.net_inasync);
- }
+ if (InCall)
+ {
+ throw new InvalidOperationException(SR.net_inasync);
+ }
- if (message == null)
- {
- throw new ArgumentNullException(nameof(message));
- }
+ if (message == null)
+ {
+ throw new ArgumentNullException(nameof(message));
+ }
- if (DeliveryMethod == SmtpDeliveryMethod.Network)
- CheckHostAndPort();
+ if (DeliveryMethod == SmtpDeliveryMethod.Network)
+ CheckHostAndPort();
- MailAddressCollection recipients = new MailAddressCollection();
+ MailAddressCollection recipients = new MailAddressCollection();
- if (message.From == null)
- {
- throw new InvalidOperationException(SR.SmtpFromRequired);
- }
+ if (message.From == null)
+ {
+ throw new InvalidOperationException(SR.SmtpFromRequired);
+ }
- if (message.To != null)
- {
- foreach (MailAddress address in message.To)
- {
- recipients.Add(address);
- }
- }
- if (message.Bcc != null)
+ if (message.To != null)
+ {
+ foreach (MailAddress address in message.To)
{
- foreach (MailAddress address in message.Bcc)
- {
- recipients.Add(address);
- }
+ recipients.Add(address);
}
- if (message.CC != null)
+ }
+ if (message.Bcc != null)
+ {
+ foreach (MailAddress address in message.Bcc)
{
- foreach (MailAddress address in message.CC)
- {
- recipients.Add(address);
- }
+ recipients.Add(address);
}
-
- if (recipients.Count == 0)
+ }
+ if (message.CC != null)
+ {
+ foreach (MailAddress address in message.CC)
{
- throw new InvalidOperationException(SR.SmtpRecipientRequired);
+ recipients.Add(address);
}
+ }
- _transport.IdentityRequired = false; // everything completes on the same thread.
+ if (recipients.Count == 0)
+ {
+ throw new InvalidOperationException(SR.SmtpRecipientRequired);
+ }
- try
- {
- InCall = true;
- _timedOut = false;
- _timer = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
- bool allowUnicode = false;
- string? pickupDirectory = PickupDirectoryLocation;
-
- MailWriter writer;
- switch (DeliveryMethod)
- {
- case SmtpDeliveryMethod.PickupDirectoryFromIis:
- throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
+ _transport.IdentityRequired = false; // everything completes on the same thread.
- case SmtpDeliveryMethod.SpecifiedPickupDirectory:
- if (EnableSsl)
- {
- throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
- }
+ try
+ {
+ InCall = true;
+ _timedOut = false;
+ _timer = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
+ bool allowUnicode = false;
+ string? pickupDirectory = PickupDirectoryLocation;
- allowUnicode = IsUnicodeSupported(); // Determend by the DeliveryFormat paramiter
- ValidateUnicodeRequirement(message, recipients, allowUnicode);
- writer = GetFileMailWriter(pickupDirectory);
- break;
+ MailWriter writer;
+ switch (DeliveryMethod)
+ {
+ case SmtpDeliveryMethod.PickupDirectoryFromIis:
+ throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
- case SmtpDeliveryMethod.Network:
- default:
- GetConnection();
- // Detected durring GetConnection(), restrictable using the DeliveryFormat paramiter
- allowUnicode = IsUnicodeSupported();
- ValidateUnicodeRequirement(message, recipients, allowUnicode);
- writer = _transport.SendMail(message.Sender ?? message.From, recipients,
- message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
- break;
- }
- _message = message;
- message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
- writer.Close();
+ case SmtpDeliveryMethod.SpecifiedPickupDirectory:
+ if (EnableSsl)
+ {
+ throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
+ }
- //throw if we couldn't send to any of the recipients
- if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null)
- {
- throw recipientException;
- }
+ allowUnicode = IsUnicodeSupported(); // Determend by the DeliveryFormat paramiter
+ ValidateUnicodeRequirement(message, recipients, allowUnicode);
+ writer = GetFileMailWriter(pickupDirectory);
+ break;
+
+ case SmtpDeliveryMethod.Network:
+ default:
+ GetConnection();
+ // Detected durring GetConnection(), restrictable using the DeliveryFormat paramiter
+ allowUnicode = IsUnicodeSupported();
+ ValidateUnicodeRequirement(message, recipients, allowUnicode);
+ writer = _transport.SendMail(message.Sender ?? message.From, recipients,
+ message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
+ break;
}
- catch (Exception e)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e);
+ _message = message;
+ message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
+ writer.Close();
- if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
- {
- throw;
- }
-
- Abort();
- if (_timedOut)
- {
- throw new SmtpException(SR.net_timeout);
- }
+ //throw if we couldn't send to any of the recipients
+ if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null)
+ {
+ throw recipientException;
+ }
+ }
+ catch (Exception e)
+ {
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e);
- if (e is SecurityException ||
- e is AuthenticationException ||
- e is SmtpException)
- {
- throw;
- }
+ if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
+ {
+ throw;
+ }
- throw new SmtpException(SR.SmtpSendMailFailure, e);
+ Abort();
+ if (_timedOut)
+ {
+ throw new SmtpException(SR.net_timeout);
}
- finally
+
+ if (e is SecurityException ||
+ e is AuthenticationException ||
+ e is SmtpException)
{
- InCall = false;
- if (_timer != null)
- {
- _timer.Dispose();
- }
+ throw;
}
+
+ throw new SmtpException(SR.SmtpSendMailFailure, e);
}
finally
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+ InCall = false;
+ if (_timer != null)
+ {
+ _timer.Dispose();
+ }
}
}
throw new ObjectDisposedException(GetType().FullName);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, message, userToken, _transport);
try
{
throw new InvalidOperationException(SR.SmtpRecipientRequired);
}
- try
+ InCall = true;
+ _cancelled = false;
+ _message = message;
+ string? pickupDirectory = PickupDirectoryLocation;
+
+ CredentialCache? cache;
+ // Skip token capturing if no credentials are used or they don't include a default one.
+ // Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
+ _transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));
+
+ _asyncOp = AsyncOperationManager.CreateOperation(userToken);
+ switch (DeliveryMethod)
{
- InCall = true;
- _cancelled = false;
- _message = message;
- string? pickupDirectory = PickupDirectoryLocation;
-
- CredentialCache? cache;
- // Skip token capturing if no credentials are used or they don't include a default one.
- // Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
- _transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));
-
- _asyncOp = AsyncOperationManager.CreateOperation(userToken);
- switch (DeliveryMethod)
- {
- case SmtpDeliveryMethod.PickupDirectoryFromIis:
- throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
+ case SmtpDeliveryMethod.PickupDirectoryFromIis:
+ throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
- case SmtpDeliveryMethod.SpecifiedPickupDirectory:
+ case SmtpDeliveryMethod.SpecifiedPickupDirectory:
+ {
+ if (EnableSsl)
{
- if (EnableSsl)
- {
- throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
- }
-
- _writer = GetFileMailWriter(pickupDirectory);
- bool allowUnicode = IsUnicodeSupported();
- ValidateUnicodeRequirement(message, _recipients, allowUnicode);
- message.Send(_writer, true, allowUnicode);
-
- if (_writer != null)
- _writer.Close();
-
- AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, _asyncOp.UserSuppliedState);
- InCall = false;
- _asyncOp.PostOperationCompleted(_onSendCompletedDelegate, eventArgs);
- break;
+ throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
}
- case SmtpDeliveryMethod.Network:
- default:
- _operationCompletedResult = new ContextAwareResult(_transport.IdentityRequired, true, null, this, s_contextSafeCompleteCallback);
- lock (_operationCompletedResult.StartPostingAsyncOp())
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
- _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host!, Port);
- _operationCompletedResult.FinishPostingAsyncOp();
- }
+ _writer = GetFileMailWriter(pickupDirectory);
+ bool allowUnicode = IsUnicodeSupported();
+ ValidateUnicodeRequirement(message, _recipients, allowUnicode);
+ message.Send(_writer, true, allowUnicode);
+
+ if (_writer != null)
+ _writer.Close();
+
+ AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, _asyncOp.UserSuppliedState);
+ InCall = false;
+ _asyncOp.PostOperationCompleted(_onSendCompletedDelegate, eventArgs);
break;
- }
- }
- catch (Exception e)
- {
- InCall = false;
+ }
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e);
+ case SmtpDeliveryMethod.Network:
+ default:
+ _operationCompletedResult = new ContextAwareResult(_transport.IdentityRequired, true, null, this, s_contextSafeCompleteCallback);
+ lock (_operationCompletedResult.StartPostingAsyncOp())
+ {
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
+ _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host!, Port);
+ _operationCompletedResult.FinishPostingAsyncOp();
+ }
+ break;
+ }
+ }
+ catch (Exception e)
+ {
+ InCall = false;
- if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
- {
- throw;
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e);
- Abort();
+ if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
+ {
+ throw;
+ }
- if (e is SecurityException ||
- e is AuthenticationException ||
- e is SmtpException)
- {
- throw;
- }
+ Abort();
- throw new SmtpException(SR.SmtpSendMailFailure, e);
+ if (e is SecurityException ||
+ e is AuthenticationException ||
+ e is SmtpException)
+ {
+ throw;
}
- }
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+
+ throw new SmtpException(SR.SmtpSendMailFailure, e);
}
}
throw new ObjectDisposedException(GetType().FullName);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
- try
- {
- if (!InCall || _cancelled)
- {
- return;
- }
-
- _cancelled = true;
- Abort();
- }
- finally
+ if (!InCall || _cancelled)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+ return;
}
+
+ _cancelled = true;
+ Abort();
}
private void Complete(Exception? exception, IAsyncResult result)
{
ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState!;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
try
{
if (_cancelled)
private void SendMessageCallback(IAsyncResult result)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
try
{
_message!.EndSend(result);
{
Complete(e, result);
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
}
private void SendMailCallback(IAsyncResult result)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
try
{
_writer = _transport.EndSendMail(result);
catch (Exception e)
{
Complete(e, result);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return;
}
{
Complete(e, result);
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
}
private void ConnectCallback(IAsyncResult result)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
try
{
_transport.EndGetConnection(result);
{
Complete(e, result);
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
}
// After we've estabilished a connection and initilized ServerSupportsEai,
internal void GetConnection()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
if (_connection._isConnected)
{
throw new InvalidOperationException(SR.SmtpAlreadyConnected);
public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
- try
+ lock (_sessions)
{
- lock (_sessions)
+ NetworkCredential? cachedCredential;
+ if (!_sessions.TryGetValue(sessionCookie, out cachedCredential))
{
- NetworkCredential? cachedCredential;
- if (!_sessions.TryGetValue(sessionCookie, out cachedCredential))
+ if (credential == null || ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
{
- if (credential == null || ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
- {
- return null;
- }
-
- _sessions[sessionCookie] = credential;
+ return null;
+ }
- string userName = credential.UserName;
- string domain = credential.Domain;
+ _sessions[sessionCookie] = credential;
- if (domain != null && domain.Length > 0)
- {
- userName = domain + "\\" + userName;
- }
+ string userName = credential.UserName;
+ string domain = credential.Domain;
- return new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userName)), false);
- }
- else
+ if (domain != null && domain.Length > 0)
{
- _sessions.Remove(sessionCookie);
-
- return new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cachedCredential.Password)), true);
+ userName = domain + "\\" + userName;
}
+
+ return new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userName)), false);
+ }
+ else
+ {
+ _sessions.Remove(sessionCookie);
+
+ return new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cachedCredential.Password)), true);
}
- }
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, "Authenticate");
try
{
lock (_sessions)
{
return null;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, "Authenticate");
- }
}
public string AuthenticationType
public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, "Authenticate");
try
{
lock (_sessions)
{
return null;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, "Authenticate");
- }
}
public string AuthenticationType
internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback? callback, object? state, string host, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
IAsyncResult? result = null;
try
{
throw new SmtpException(SR.MailHostNotFound, innerException);
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Info(this, "Sync completion");
- NetEventSource.Exit(this);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Sync completion");
+
return result;
}
internal void EndGetConnection(IAsyncResult result)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
- try
- {
- _connection!.EndGetConnection(result);
- }
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
+ _connection!.EndGetConnection(result);
}
internal IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients,
public static IPHostEntry GetHostEntry(IPAddress address)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(address, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address is null)
IPHostEntry ipHostEntry = GetHostEntryCore(address);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(address, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(address, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
return ipHostEntry;
}
public static IPHostEntry GetHostEntry(string hostNameOrAddress)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostNameOrAddress is null)
ipHostEntry = GetHostEntryCore(hostNameOrAddress);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(hostNameOrAddress, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(hostNameOrAddress, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
return ipHostEntry;
}
{
if (NetEventSource.Log.IsEnabled())
{
- NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
Task<IPHostEntry> t = GetHostEntryCoreAsync(hostNameOrAddress, justReturnParsedIp: false, throwOnIIPAny: true);
- t.ContinueWith((t, s) => NetEventSource.Exit((string)s!, $"{t.Result} with {((IPHostEntry)t.Result).AddressList.Length} entries"),
+ t.ContinueWith((t, s) => NetEventSource.Info((string)s!, $"{t.Result} with {((IPHostEntry)t.Result).AddressList.Length} entries"),
hostNameOrAddress, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
return t;
}
public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(address, address);
-
NameResolutionPal.EnsureSocketsAreInitialized();
if (address is null)
}
return RunAsync(s => {
- IPHostEntry ipHostEntry = GetHostEntryCore((IPAddress)s);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit((IPAddress)s, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
- return ipHostEntry;
- }, address);
- }
-
- public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback? requestCallback, object? stateObject)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(address, address);
-
- IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryAsync(address), requestCallback, stateObject);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(address, asyncResult);
- return asyncResult;
- }
-
- public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback? requestCallback, object? stateObject)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
-
- IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryAsync(hostNameOrAddress), requestCallback, stateObject);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(asyncResult, asyncResult);
- return asyncResult;
+ IPHostEntry ipHostEntry = GetHostEntryCore((IPAddress)s);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info((IPAddress)s, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
+ return ipHostEntry;
+ }, address);
}
- public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(asyncResult, asyncResult);
+ public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback? requestCallback, object? stateObject) =>
+ TaskToApm.Begin(GetHostEntryAsync(address), requestCallback, stateObject);
- IPHostEntry ipHostEntry = TaskToApm.End<IPHostEntry>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
+ public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback? requestCallback, object? stateObject) =>
+ TaskToApm.Begin(GetHostEntryAsync(hostNameOrAddress), requestCallback, stateObject);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(asyncResult, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries" );
- return ipHostEntry;
- }
+ public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult) =>
+ TaskToApm.End<IPHostEntry>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostNameOrAddress is null)
addresses = GetHostAddressesCore(hostNameOrAddress);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(hostNameOrAddress, addresses);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(hostNameOrAddress, addresses);
return addresses;
}
public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress) =>
(Task<IPAddress[]>)GetHostEntryOrAddressesCoreAsync(hostNameOrAddress, justReturnParsedIp: true, throwOnIIPAny: true, justAddresses: true);
- public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback? requestCallback, object? state)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
-
- IAsyncResult asyncResult = TaskToApm.Begin(GetHostAddressesAsync(hostNameOrAddress), requestCallback, state);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(hostNameOrAddress, asyncResult);
- return asyncResult;
- }
-
- public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(asyncResult, asyncResult);
-
- IPAddress[] addresses = TaskToApm.End<IPAddress[]>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
+ public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback? requestCallback, object? state) =>
+ TaskToApm.Begin(GetHostAddressesAsync(hostNameOrAddress), requestCallback, state);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(asyncResult, addresses);
- return addresses;
- }
+ public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult) =>
+ TaskToApm.End<IPAddress[]>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
[Obsolete("GetHostByName is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByName(string hostName)
}
[Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
- public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback? requestCallback, object? stateObject)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostName, hostName);
-
- IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryCoreAsync(hostName, justReturnParsedIp: true, throwOnIIPAny: true), requestCallback, stateObject);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(hostName, asyncResult);
- return asyncResult;
- }
+ public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback? requestCallback, object? stateObject) =>
+ TaskToApm.Begin(GetHostEntryCoreAsync(hostName, justReturnParsedIp: true, throwOnIIPAny: true), requestCallback, stateObject);
[Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
- public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(asyncResult, asyncResult);
-
- IPHostEntry ipHostEntry = TaskToApm.End<IPHostEntry>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(asyncResult, ipHostEntry);
- return ipHostEntry;
- }
+ public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult) =>
+ TaskToApm.End<IPHostEntry>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(string address)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(address, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address is null)
IPHostEntry ipHostEntry = GetHostEntryCore(IPAddress.Parse(address));
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(address, ipHostEntry);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(address, ipHostEntry);
return ipHostEntry;
}
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(IPAddress address)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(address, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address is null)
IPHostEntry ipHostEntry = GetHostEntryCore(address);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(address, ipHostEntry);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(address, ipHostEntry);
return ipHostEntry;
}
[Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry Resolve(string hostName)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostName, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostName is null)
ipHostEntry = GetHostEntryCore(hostName);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(hostName, ipHostEntry);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(hostName, ipHostEntry);
return ipHostEntry;
}
[Obsolete("BeginResolve is obsoleted for this type, please use BeginGetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
- public static IAsyncResult BeginResolve(string hostName, AsyncCallback? requestCallback, object? stateObject)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, hostName);
-
- IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryCoreAsync(hostName, justReturnParsedIp: false, throwOnIIPAny: false), requestCallback, stateObject);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, asyncResult);
- return asyncResult;
- }
+ public static IAsyncResult BeginResolve(string hostName, AsyncCallback? requestCallback, object? stateObject) =>
+ TaskToApm.Begin(GetHostEntryCoreAsync(hostName, justReturnParsedIp: false, throwOnIIPAny: false), requestCallback, stateObject);
[Obsolete("EndResolve is obsoleted for this type, please use EndGetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry EndResolve(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, asyncResult);
IPHostEntry ipHostEntry;
try
ipHostEntry = CreateHostEntryForAddress(address);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, ipHostEntry);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, ipHostEntry);
return ipHostEntry;
}
internal CookieCollection CookieCutter(Uri uri, string? headerName, string setCookieHeader, bool isThrow)
{
- if (NetEventSource.Log.IsEnabled())
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"uri:{uri} headerName:{headerName} setCookieHeader:{setCookieHeader} isThrow:{isThrow}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"uri:{uri} headerName:{headerName} setCookieHeader:{setCookieHeader} isThrow:{isThrow}");
CookieCollection cookies = new CookieCollection();
CookieVariant variant = CookieVariant.Unknown;
throw new ArgumentNullException(nameof(authType));
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, uriPrefix, authType);
-
if (_cache == null)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null.");
throw new ArgumentOutOfRangeException(nameof(port));
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host, port, authenticationType);
-
if (_cacheForHosts == null)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null.");
internal SocketException(SocketError errorCode, uint platformError) : base((int)platformError)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, errorCode, platformError);
_errorCode = errorCode;
}
/// <summary>Creates a new instance of the <see cref='System.Net.Sockets.SocketException'/> class with the specified error code as SocketError.</summary>
internal SocketException(SocketError socketError) : base(GetNativeErrorForSocketError(socketError))
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, socketError, Message);
_errorCode = socketError;
}
//
public override WebResponse GetResponse()
{
- if (NetEventSource.Log.IsEnabled())
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
try
{
}
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, _ftpWebResponse);
- }
return _ftpWebResponse!;
}
/// </summary>
public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
ContextAwareResult? asyncResult;
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
return asyncResult;
}
/// </summary>
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
try
{
// parameter validation
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
return _ftpWebResponse!;
}
/// </summary>
public override Stream GetRequestStream()
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
try
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
return _stream;
}
/// </summary>
public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
ContextAwareResult? asyncResult = null;
try
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
return asyncResult;
}
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
Stream? requestStream = null;
try
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
return requestStream;
}
//
private void SyncRequestCallback(object? obj)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, obj);
RequestStage stageMode = RequestStage.CheckForError;
try
finally
{
FinishRequestStage(stageMode);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
CheckError(); //will throw on error
}
}
//
private void AsyncRequestCallback(object? obj)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, obj);
RequestStage stageMode = RequestStage.CheckForError;
try
finally
{
FinishRequestStage(stageMode);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
}
if (_aborted)
return;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
try
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
throw;
}
- finally
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- }
}
public bool KeepAlive
internal FtpWebResponse(Stream? responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string? statusLine, DateTime lastModified, string? bannerMessage, string? welcomeMessage, string? exitMessage)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, contentLength, statusLine);
-
_responseStream = responseStream;
if (responseStream == null && contentLength < 0)
{
/// </summary>
public override void Close()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
_responseStream?.Close();
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
/// <summary>
/// </summary>
private static void ThreadProc()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
// Set this thread as a background thread. On AppDomain/Process shutdown, the thread will just be killed.
Thread.CurrentThread.IsBackground = true;
// Newly created WebRequest.
private static WebRequest Create(Uri requestUri, bool useUriBase)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, requestUri);
-
string LookupUri;
WebRequestPrefixElement? Current = null;
bool Found = false;
{
// We found a match, so just call the creator and return what it does.
WebRequest webRequest = Current!.Creator.Create(requestUri);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, webRequest);
return webRequest;
}
// Otherwise no match, throw an exception.
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null);
throw new NotSupportedException(SR.net_unknown_prefix);
}
return null;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(securityContext);
-
SafeSslHandle sslContext = ((SafeDeleteSslContext)securityContext).SslContext;
if (sslContext == null)
}
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Log.RemoteCertificate(result);
- NetEventSource.Exit(securityContext, result);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.RemoteCertificate(result);
return result;
}
return null;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(securityContext);
-
X509Certificate2? result = null;
SafeFreeCertContext? remoteContext = null;
try
}
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Log.RemoteCertificate(result);
- NetEventSource.Exit(securityContext, result);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.RemoteCertificate(result);
return result;
}
return null;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(securityContext);
-
X509Certificate2? result = null;
SafeFreeCertContext? remoteContext = null;
try
}
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Log.RemoteCertificate(result);
- NetEventSource.Exit(null, result, securityContext);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.RemoteCertificate(result);
return result;
}
private static unsafe uint Verify(SafeX509ChainHandle chainContext, ref Interop.Crypt32.CERT_CHAIN_POLICY_PARA cpp)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(chainContext, cpp.dwFlags);
-
Interop.Crypt32.CERT_CHAIN_POLICY_STATUS status = default;
status.cbSize = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_STATUS);
internal SecureChannel(SslAuthenticationOptions sslAuthenticationOptions, SslStream sslStream)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this, sslAuthenticationOptions.TargetHost, sslAuthenticationOptions.ClientCertificates);
- NetEventSource.Log.SecureChannelCtor(this, sslStream, sslAuthenticationOptions.TargetHost!, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.SecureChannelCtor(this, sslStream, sslAuthenticationOptions.TargetHost!, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy);
SslStreamPal.VerifyPackageInfo();
_securityContext = null;
_refreshCredentialNeeded = true;
_sslAuthenticationOptions = sslAuthenticationOptions;
-
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this);
}
//
internal ChannelBinding? GetChannelBinding(ChannelBindingKind kind)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this, kind);
-
ChannelBinding? result = null;
if (_securityContext != null)
{
result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind);
}
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, result);
return result;
}
private bool AcquireClientCredentials(ref byte[]? thumbPrint)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this);
-
// Acquire possible Client Certificate information and set it on the handle.
X509Certificate? clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart.
List<X509Certificate>? filteredCerts = null; // This is an intermediate client certs collection that try to use if no selectedCert is available yet.
}
}
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, cachedCred, _credentialsHandle);
return cachedCred;
}
//
private bool AcquireServerCredentials(ref byte[]? thumbPrint)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this);
-
X509Certificate? localCertificate = null;
X509Certificate2? selectedCert = null;
bool cachedCred = false;
thumbPrint = guessedThumbPrint;
}
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, cachedCred, _credentialsHandle);
return cachedCred;
}
//
internal ProtocolToken NextMessage(ReadOnlySpan<byte> incomingBuffer)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this);
-
byte[]? nextmsg = null;
SecurityStatusPal status = GenerateToken(incomingBuffer, ref nextmsg);
{
NetEventSource.Error(this, $"Authentication failed. Status: {status.ToString()}, Exception message: {token.GetException()!.Message}");
}
-
- NetEventSource.Exit(this, token);
}
return token;
}
--*/
private SecurityStatusPal GenerateToken(ReadOnlySpan<byte> inputBuffer, ref byte[]? output)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"_refreshCredentialNeeded = {_refreshCredentialNeeded}");
-
byte[]? result = Array.Empty<byte>();
SecurityStatusPal status = default;
bool cachedCreds = false;
}
output = result;
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(this);
- }
return status;
}
--*/
internal void ProcessHandshakeSuccess()
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this);
-
if (_negotiatedApplicationProtocol == default)
{
// try to get ALPN info unless we already have it. (renegotiation)
}
SslStreamPal.QueryContextConnectionInfo(_securityContext!, out _connectionInfo);
-
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this);
}
/*++
--*/
internal SecurityStatusPal Encrypt(ReadOnlyMemory<byte> buffer, ref byte[] output, out int resultSize)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this, buffer, buffer.Length);
- NetEventSource.DumpBuffer(this, buffer);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer);
byte[] writeBuffer = output;
if (secStatus.ErrorCode != SecurityStatusPalErrorCode.OK)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, $"ERROR {secStatus}");
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"ERROR {secStatus}");
}
else
{
output = writeBuffer;
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, $"OK data size:{resultSize}");
}
return secStatus;
internal SecurityStatusPal Decrypt(byte[]? payload, ref int offset, ref int count)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this, payload, offset, count);
-
if ((uint)offset > (uint)(payload == null ? 0 : payload.Length))
{
NetEventSource.Fail(this, "Argument 'offset' out of range.");
//This method validates a remote certificate.
internal bool VerifyRemoteCertificate(RemoteCertValidationCallback? remoteCertValidationCallback, ref ProtocolToken? alertToken)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this);
-
SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
// We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true.
if (remoteCertificateEx == null)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, $"No remote certificate received. RemoteCertRequired: {RemoteCertRequired}");
+ if (NetEventSource.Log.IsEnabled() && RemoteCertRequired) NetEventSource.Error(this, $"Remote certificate required, but no remote certificate received");
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable;
}
else
remoteCertificateEx?.Dispose();
}
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, success);
-
return success;
}
public ProtocolToken? CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this);
-
TlsAlertMessage alertMessage;
switch (sslPolicyErrors)
return null;
}
- ProtocolToken token = GenerateAlertToken();
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, token);
- return token;
+ return GenerateAlertToken();
}
public ProtocolToken? CreateShutdownToken()
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this);
-
SecurityStatusPal status;
status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext!);
return null;
}
- ProtocolToken token = GenerateAlertToken();
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, token);
- return token;
+ return GenerateAlertToken();
}
private ProtocolToken GenerateAlertToken()
SecurityStatusPal status;
status = GenerateToken(default, ref nextmsg);
- ProtocolToken token = new ProtocolToken(nextmsg, status);
-
- return token;
+ return new ProtocolToken(nextmsg, status);
}
private static TlsAlertMessage GetAlertMessageFromChain(X509Chain chain)
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Scavenged cache, New Cache Count = {s_cachedCreds.Count}");
}
}
- else if (NetEventSource.Log.IsEnabled())
+ else
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"CacheCredential() (locked retry) Found already cached Handle = {cached.Target}");
}
}
}
- else if (NetEventSource.Log.IsEnabled())
+ else
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"CacheCredential() Ignoring incoming handle = {creds} since found already cached Handle = {cached.Target}");
}
//
private void CloseInternal()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
_exception = s_disposedSentinel;
_context?.Close();
// Suppress finalizer if the read buffer was returned.
GC.SuppressFinalize(this);
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
private SecurityStatusPal EncryptData(ReadOnlyMemory<byte> buffer, ref byte[] outBuffer, out int outSize)
//
private bool CompleteHandshake(ref ProtocolToken? alertToken)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this);
-
_context!.ProcessHandshakeSuccess();
if (!_context.VerifyRemoteCertificate(_sslAuthenticationOptions!.CertValidationDelegate, ref alertToken))
{
_handshakeCompleted = false;
-
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, false);
return false;
}
_handshakeCompleted = true;
-
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, true);
return true;
}
// Returns TLS Frame size.
private int GetFrameSize(ReadOnlySpan<byte> buffer)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(this, buffer.Length);
-
int payloadSize = -1;
switch (_framing)
{
break;
}
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(this, payloadSize);
-
return payloadSize;
}
}
protected virtual void ForceReleaseUnmanagedStructures()
{
// Free the unmanaged memory if allocated.
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
_nativeOverlapped!.Dispose();
_nativeOverlapped = null;
GC.SuppressFinalize(this);
private int _currentWriteTimeout = -1;
internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, mode, timeout, silent);
-
if (timeout < 0)
{
timeout = 0; // -1 becomes 0 for the winsock stack
public Socket(SocketInformation socketInformation)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
InitializeSockets();
SocketError errorCode = SocketPal.CreateSocket(socketInformation, out _handle,
_handle = null!;
throw new SocketException((int)errorCode);
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
private unsafe void LoadSocketTypeFromHandle(
public SocketInformation DuplicateAndClose(int targetProcessId)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, targetProcessId);
-
ThrowIfDisposed();
SocketError errorCode = SocketPal.DuplicateSocket(_handle, targetProcessId, out SocketInformation info);
Close(timeout: -1);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return info;
}
// Initializes a new instance of the Sockets.Socket class.
public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, addressFamily);
-
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, addressFamily);
InitializeSockets();
SocketError errorCode = SocketPal.CreateSocket(addressFamily, socketType, protocolType, out _handle);
_socketType = socketType;
_protocolType = protocolType;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
/// <summary>Initializes a new instance of the <see cref="Socket"/> class for the specified socket handle.</summary>
// Associates a socket with an end point.
public void Bind(EndPoint localEP)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, localEP);
-
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP);
ThrowIfDisposed();
// Validate input parameters.
Internals.SocketAddress socketAddress = Serialize(ref localEP);
DoBind(localEP, socketAddress);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
private void DoBind(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress)
ValidateBlockingMode();
- if (NetEventSource.Log.IsEnabled())
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"DST:{remoteEP}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"DST:{remoteEP}");
DnsEndPoint? dnsEP = remoteEP as DnsEndPoint;
if (dnsEP != null)
public void Connect(IPAddress address, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, address);
-
ThrowIfDisposed();
if (address == null)
IPEndPoint remoteEP = new IPEndPoint(address, port);
Connect(remoteEP);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public void Connect(string host, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host);
-
ThrowIfDisposed();
if (host == null)
IPAddress[] addresses = Dns.GetHostAddresses(host);
Connect(addresses, port);
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public void Connect(IPAddress[] addresses, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, addresses);
-
ThrowIfDisposed();
if (addresses == null)
{
throw new ArgumentException(SR.net_invalidAddressList, nameof(addresses));
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public void Close()
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, $"timeout = {_closeTimeout}");
- }
-
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"timeout = {_closeTimeout}");
Dispose();
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public void Close(int timeout)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, timeout);
if (timeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"timeout = {_closeTimeout}");
Dispose();
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, timeout);
}
/// <summary>
/// <param name="backlog">The maximum length of the pending connections queue.</param>
public void Listen(int backlog)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, backlog);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, backlog);
ThrowIfDisposed();
// This may throw ObjectDisposedException.
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
_isListening = true;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Creates a new Sockets.Socket instance to handle an incoming connection.
public Socket Accept()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
// Validate input parameters.
ThrowIfDisposed();
Debug.Assert(!acceptedSocketHandle.IsInvalid);
Socket socket = CreateAcceptSocket(acceptedSocketHandle, _rightEndPoint.Create(socketAddress));
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Accepted(socket, socket.RemoteEndPoint!, socket.LocalEndPoint);
- NetEventSource.Exit(this, socket);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Accepted(socket, socket.RemoteEndPoint!, socket.LocalEndPoint);
return socket;
}
public int Send(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
if (buffers == null)
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Error(this, new SocketException((int)errorCode));
- NetEventSource.Exit(this, 0);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
return 0;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
// Validate input parameters.
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Error(this, new SocketException((int)errorCode));
- NetEventSource.Exit(this, 0);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
return 0;
}
{
NetEventSource.Info(this, $"Send returns:{bytesTransferred}");
NetEventSource.DumpBuffer(this, buffer, offset, bytesTransferred);
- NetEventSource.Exit(this, bytesTransferred);
}
return bytesTransferred;
public int Send(ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out SocketError errorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
ValidateBlockingMode();
bytesTransferred = 0;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public void SendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
if (!Connected)
SendFileInternal(fileName, preBuffer, postBuffer, flags);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Sends data to a specific end point, starting at the indicated location in the buffer.
public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
// Validate input parameters.
_rightEndPoint = remoteEP;
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.DumpBuffer(this, buffer, offset, size);
- NetEventSource.Exit(this, bytesTransferred);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer, offset, size);
return bytesTransferred;
}
public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
// Validate input parameters.
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Error(this, new SocketException((int)errorCode));
- NetEventSource.Exit(this, 0);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
return 0;
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.DumpBuffer(this, buffer, offset, bytesTransferred);
- NetEventSource.Exit(this, bytesTransferred);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer, offset, bytesTransferred);
return bytesTransferred;
}
public int Receive(Span<byte> buffer, SocketFlags socketFlags, out SocketError errorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
ValidateBlockingMode();
bytesTransferred = 0;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public int Receive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
if (buffers == null)
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Error(this, new SocketException((int)errorCode));
- NetEventSource.Exit(this, 0);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
return 0;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
-
return bytesTransferred;
}
// the end point.
public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
if (buffer == null)
{
// the end point.
public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
// Validate input parameters.
throw socketException;
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.DumpBuffer(this, buffer, offset, size);
- NetEventSource.Exit(this, bytesTransferred);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer, offset, size);
return bytesTransferred;
}
public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback? callback, object? state)
{
// Validate input parameters.
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, remoteEP);
ThrowIfDisposed();
if (remoteEP == null)
public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host);
ThrowIfDisposed();
if (host == null)
IPAddress? parsedAddress;
if (IPAddress.TryParse(host, out parsedAddress))
{
- IAsyncResult r = BeginConnect(parsedAddress, port, requestCallback, state);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, r);
- return r;
+ return BeginConnect(parsedAddress, port, requestCallback, state);
}
ValidateForMultiConnect(isMultiEndpoint: true);
// Done posting.
result.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, result);
return result;
}
public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, address);
ThrowIfDisposed();
if (address == null)
throw new NotSupportedException(SR.net_invalidversion);
}
- IAsyncResult result = BeginConnect(new IPEndPoint(address, port), requestCallback, state);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, result);
- return result;
+ return BeginConnect(new IPEndPoint(address, port), requestCallback, state);
}
public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, addresses);
ThrowIfDisposed();
if (addresses == null)
// Finished posting async op. Possibly will call callback.
result.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, result);
return result;
}
public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
// Start context-flowing op. No need to lock - we don't use the context till the callback.
private void DoBeginDisconnect(bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
SocketError errorCode = SocketError.Success;
errorCode = SocketPal.DisconnectAsync(this, _handle, reuseSocket, asyncResult);
{
throw new SocketException((int)errorCode);
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
}
public void Disconnect(bool reuseSocket)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
SocketError errorCode = SocketError.Success;
SetToDisconnected();
_remoteEndPoint = null;
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Routine Description:
// int - Return code from async Connect, 0 for success, SocketError.NotConnected otherwise
public void EndConnect(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
ThrowIfDisposed();
// Validate input parameters.
ExceptionDispatchInfo.Throw(ex);
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
- NetEventSource.Exit(this, "");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
}
public void EndDisconnect(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
ThrowIfDisposed();
if (asyncResult == null)
{
UpdateStatusAfterSocketErrorAndThrowException((SocketError)castedAsyncResult.ErrorCode);
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Routine Description:
public IAsyncResult? BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
// Validate input parameters.
asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
public IAsyncResult? BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
// Validate input parameters.
asyncResult = null;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
public int EndSend(IAsyncResult asyncResult, out SocketError errorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
ThrowIfDisposed();
// Validate input parameters.
UpdateSendSocketErrorForDisposed(ref errorCode);
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Error(this, new SocketException((int)errorCode));
- NetEventSource.Exit(this, 0);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
return 0;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public IAsyncResult BeginSendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
if (!Connected)
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"::DoBeginSendFile() SRC:{LocalEndPoint} DST:{RemoteEndPoint} fileName:{fileName}");
- IAsyncResult asyncResult = BeginSendFileInternal(fileName, preBuffer, postBuffer, flags, callback, state);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
- return asyncResult;
+ return BeginSendFileInternal(fileName, preBuffer, postBuffer, flags, callback, state);
}
public void EndSendFile(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
-
ThrowIfDisposed();
if (asyncResult == null)
}
EndSendFileInternal(asyncResult);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Routine Description:
// IAsyncResult - Async result used to retrieve result
public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
// Validate input parameters.
// Finish, possibly posting the callback. The callback won't be posted before this point is reached.
asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
// int - Number of bytes transferred
public int EndSendTo(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
-
ThrowIfDisposed();
// Validate input parameters.
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public IAsyncResult? BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
// Validate input parameters.
asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
public IAsyncResult? BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
// Validate input parameters.
asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
public int EndReceive(IAsyncResult asyncResult, out SocketError errorCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
-
ThrowIfDisposed();
// Validate input parameters.
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Error(this, new SocketException((int)errorCode));
- NetEventSource.Exit(this, 0);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
return 0;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(this);
- NetEventSource.Info(this, $"size:{size}");
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"size:{size}");
ThrowIfDisposed();
if (buffer == null)
}
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Info(this, $"size:{size} returning AsyncResult:{asyncResult}");
- NetEventSource.Exit(this, asyncResult);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"size:{size} returning AsyncResult:{asyncResult}");
return asyncResult;
}
public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
ThrowIfDisposed();
if (endPoint == null)
socketFlags = castedAsyncResult.SocketFlags;
ipPacketInformation = castedAsyncResult.IPPacketInformation;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
// IAsyncResult - Async result used to retrieve result
public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
// Validate input parameters.
}
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
// int - Number of bytes transferred
public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
-
ThrowIfDisposed();
// Validate input parameters.
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
return BeginAccept(0, callback, state);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
Debug.Assert(Disposed);
ThrowObjectDisposedException();
return null; // unreachable
// This is the truly async version that uses AcceptEx.
public IAsyncResult BeginAccept(Socket? acceptSocket, int receiveSize, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
ThrowIfDisposed();
// Validate input parameters.
// Finish the flow capture, maybe complete here.
asyncResult.FinishPostingAsyncOp(ref Caches.AcceptClosureCache);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
public Socket EndAccept(out byte[]? buffer, out int bytesTransferred, IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
ThrowIfDisposed();
// Validate input parameters.
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
- NetEventSource.Exit(this, socket);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
return socket;
}
// Disables sends and receives on a socket.
public void Shutdown(SocketShutdown how)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, how);
ThrowIfDisposed();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"how:{how}");
SetToDisconnected();
InternalSetBlocking(_willBlockInternal);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
#region Async methods
public bool AcceptAsync(SocketAsyncEventArgs e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
ThrowIfDisposed();
if (e == null)
throw;
}
- bool pending = (socketError == SocketError.IOPending);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
- return pending;
+ return socketError == SocketError.IOPending;
}
public bool ConnectAsync(SocketAsyncEventArgs e) =>
private bool ConnectAsync(SocketAsyncEventArgs e, bool userSocket)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
bool pending;
ThrowIfDisposed();
pending = (socketError == SocketError.IOPending);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
return pending;
}
public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
bool pending;
if (e == null)
pending = attemptSocket.ConnectAsync(e, userSocket: false);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, pending);
return pending;
}
public bool DisconnectAsync(SocketAsyncEventArgs e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
// Throw if socket disposed
ThrowIfDisposed();
throw;
}
- bool retval = (socketError == SocketError.IOPending);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, retval);
- return retval;
+ return socketError == SocketError.IOPending;
}
public bool ReceiveAsync(SocketAsyncEventArgs e) => ReceiveAsync(e, default(CancellationToken));
private bool ReceiveAsync(SocketAsyncEventArgs e, CancellationToken cancellationToken)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
ThrowIfDisposed();
if (e == null)
throw;
}
- bool pending = (socketError == SocketError.IOPending);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
- return pending;
+ return socketError == SocketError.IOPending;
}
public bool ReceiveFromAsync(SocketAsyncEventArgs e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
ThrowIfDisposed();
if (e == null)
}
bool pending = (socketError == SocketError.IOPending);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
return pending;
}
public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
ThrowIfDisposed();
if (e == null)
throw;
}
- bool pending = (socketError == SocketError.IOPending);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
- return pending;
+ return socketError == SocketError.IOPending;
}
public bool SendAsync(SocketAsyncEventArgs e) => SendAsync(e, default(CancellationToken));
private bool SendAsync(SocketAsyncEventArgs e, CancellationToken cancellationToken)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
ThrowIfDisposed();
if (e == null)
throw;
}
- bool pending = (socketError == SocketError.IOPending);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
- return pending;
+ return socketError == SocketError.IOPending;
}
public bool SendPacketsAsync(SocketAsyncEventArgs e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
ThrowIfDisposed();
if (e == null)
throw;
}
- bool pending = (socketError == SocketError.IOPending);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
- return pending;
+ return socketError == SocketError.IOPending;
}
public bool SendToAsync(SocketAsyncEventArgs e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
ThrowIfDisposed();
if (e == null)
_rightEndPoint = oldEndPoint;
}
- bool retval = (socketError == SocketError.IOPending);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, retval);
- return retval;
+ return socketError == SocketError.IOPending;
}
#endregion
#endregion
private void DoConnect(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, endPointSnapshot);
-
SocketError errorCode = SocketPal.Connect(_handle, socketAddress.Buffer, socketAddress.Size);
// Throw an appropriate SocketException if the native call fails.
// Update state and performance counters.
SetToConnected();
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
- NetEventSource.Exit(this);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
}
protected virtual void Dispose(bool disposing)
try
{
NetEventSource.Info(this, $"disposing:{disposing} Disposed:{Disposed}");
- NetEventSource.Enter(this);
}
catch (Exception exception) when (!ExceptionCheck.IsFatal(exception)) { }
}
// Make sure we're the first call to Dispose
if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 1)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return;
}
public void Dispose()
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Info(this, $"timeout = {_closeTimeout}");
- NetEventSource.Enter(this);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"timeout = {_closeTimeout}");
Dispose(true);
GC.SuppressFinalize(this);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
~Socket()
// This version does not throw.
internal void InternalShutdown(SocketShutdown how)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"how:{how}");
if (Disposed || _handle.IsInvalid)
{
internal unsafe void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue, bool silent)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue} silent:{silent}");
-
if (silent && (Disposed || _handle.IsInvalid))
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "skipping the call");
// error code, and will update internal state on success.
private SocketError InternalSetBlocking(bool desired, out bool current)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"desired:{desired} willBlock:{_willBlock} willBlockInternal:{_willBlockInternal}");
-
if (Disposed)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, "ObjectDisposed");
current = _willBlock;
return SocketError.Success;
}
// Since this is private, the unsafe mode is specified with a flag instead of an overload.
private IAsyncResult BeginConnectEx(EndPoint remoteEP, bool flowContext, AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
EndPoint endPointSnapshot = remoteEP;
Internals.SocketAddress socketAddress = Serialize(ref endPointSnapshot);
// This is a nop if the context isn't being flowed.
asyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Info(this, $"{endPointSnapshot} returning AsyncResult:{asyncResult}");
- NetEventSource.Exit(this, asyncResult);
- }
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"{endPointSnapshot} returning AsyncResult:{asyncResult}");
return asyncResult;
}
internal void SetToDisconnected()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
if (!_isConnected)
{
// Socket was already disconnected.
{
// If we already know the socket is disconnected
// we don't need to do anything else.
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"errorCode:{errorCode}");
if (_isConnected && (_handle.IsInvalid || (errorCode != SocketError.WouldBlock &&
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient(AddressFamily family)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, family);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, family);
// Validate parameter
if (family != AddressFamily.InterNetwork &&
_family = family;
InitializeClientSocket();
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class with the specified end point.
public TcpClient(IPEndPoint localEP)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, localEP);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP);
if (localEP == null)
{
_family = localEP.AddressFamily; // set before calling CreateSocket
InitializeClientSocket();
_clientSocket.Bind(localEP);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class and connects to the specified port on
// the specified host.
public TcpClient(string hostname, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, hostname);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, hostname);
if (hostname == null)
{
_clientSocket?.Close();
throw;
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Used by TcpListener.Accept().
internal TcpClient(Socket acceptedSocket)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, acceptedSocket);
-
_clientSocket = acceptedSocket;
_active = true;
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Used by the class to indicate that a connection has been made.
// Connects the Client to the specified port on the specified host.
public void Connect(string hostname, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, hostname);
ThrowIfDisposed();
throw new SocketException((int)SocketError.NotConnected);
}
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Connects the Client to the specified port on the specified host.
public void Connect(IPAddress address, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, address);
-
ThrowIfDisposed();
if (address == null)
IPEndPoint remoteEP = new IPEndPoint(address, port);
Connect(remoteEP);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Connect the Client to the specified end point.
public void Connect(IPEndPoint remoteEP)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, remoteEP);
-
ThrowIfDisposed();
if (remoteEP == null)
Client.Connect(remoteEP);
_family = Client.AddressFamily;
_active = true;
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public void Connect(IPAddress[] ipAddresses, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, ipAddresses);
-
Client.Connect(ipAddresses, port);
_family = Client.AddressFamily;
_active = true;
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public Task ConnectAsync(IPAddress address, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, address);
Task result = CompleteConnectAsync(Client.ConnectAsync(address, port));
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- return result;
- }
-
- public Task ConnectAsync(string host, int port)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host);
-
- Task result = CompleteConnectAsync(Client.ConnectAsync(host, port));
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return result;
}
- public Task ConnectAsync(IPAddress[] addresses, int port)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, addresses);
+ public Task ConnectAsync(string host, int port) =>
+ CompleteConnectAsync(Client.ConnectAsync(host, port));
- Task result = CompleteConnectAsync(Client.ConnectAsync(addresses, port));
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- return result;
- }
+ public Task ConnectAsync(IPAddress[] addresses, int port) =>
+ CompleteConnectAsync(Client.ConnectAsync(addresses, port));
private async Task CompleteConnectAsync(Task task)
{
_active = true;
}
- public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, address);
-
- IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- return result;
- }
-
- public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, (string)host);
-
- IAsyncResult result = Client.BeginConnect(host, port, requestCallback, state);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- return result;
- }
-
- public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, addresses);
+ public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state) =>
+ Client.BeginConnect(address, port, requestCallback, state);
- IAsyncResult result = Client.BeginConnect(addresses, port, requestCallback, state);
+ public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state) =>
+ Client.BeginConnect(host, port, requestCallback, state);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- return result;
- }
+ public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state) =>
+ Client.BeginConnect(addresses, port, requestCallback, state);
public void EndConnect(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
-
_clientSocket.EndConnect(asyncResult);
_active = true;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Returns the stream used to read and write data to the remote host.
public NetworkStream GetStream()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
ThrowIfDisposed();
if (!Connected)
_dataStream = new NetworkStream(Client, true);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, _dataStream);
return _dataStream;
}
// Disposes the Tcp connection.
protected virtual void Dispose(bool disposing)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0)
{
if (disposing)
GC.SuppressFinalize(this);
}
}
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
public void Dispose() => Dispose(true);
// Initializes a new instance of the TcpListener class with the specified local end point.
public TcpListener(IPEndPoint localEP)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, localEP);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP);
+
if (localEP == null)
{
throw new ArgumentNullException(nameof(localEP));
}
_serverSocketEP = localEP;
_serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Initializes a new instance of the TcpListener class that listens to the specified IP address
// and port.
public TcpListener(IPAddress localaddr, int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, localaddr);
+ if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localaddr);
+
if (localaddr == null)
{
throw new ArgumentNullException(nameof(localaddr));
_serverSocketEP = new IPEndPoint(localaddr, port);
_serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Initiailizes a new instance of the TcpListener class that listens on the specified port.
throw new ArgumentOutOfRangeException(nameof(backlog));
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
// Already listening.
if (_active)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
return;
}
}
_active = true;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Closes the network connection.
public void Stop()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
_serverSocket?.Dispose();
_active = false;
_serverSocket = null;
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
}
// Determine if there are pending connection requests.
// Accept the first pending connection
public Socket AcceptSocket()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
- Socket socket = _serverSocket!.Accept();
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, socket);
- return socket;
+ return _serverSocket!.Accept();
}
public TcpClient AcceptTcpClient()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
Socket acceptedSocket = _serverSocket!.Accept();
- TcpClient returnValue = new TcpClient(acceptedSocket);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, returnValue);
- return returnValue;
+ return new TcpClient(acceptedSocket);
}
public IAsyncResult BeginAcceptSocket(AsyncCallback? callback, object? state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
- IAsyncResult result = _serverSocket!.BeginAccept(callback, state);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
- return result;
+ return _serverSocket!.BeginAccept(callback, state);
}
public Socket EndAcceptSocket(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
// This will throw ObjectDisposedException if Stop() has been called.
- Socket socket = asyncSocket.EndAccept(asyncResult);
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, socket);
- return socket;
+ return asyncSocket.EndAccept(asyncResult);
}
public IAsyncResult BeginAcceptTcpClient(AsyncCallback? callback, object? state) =>
public Task<Socket> AcceptSocketAsync()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
- Task<Socket> result = _serverSocket!.AcceptAsync();
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
- return result;
+ return _serverSocket!.AcceptAsync();
}
public Task<TcpClient> AcceptTcpClientAsync()
// This creates a TcpListener that listens on both IPv4 and IPv6 on the given port.
public static TcpListener Create(int port)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, port);
-
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
listener = new TcpListener(IPAddress.Any, port);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, port);
-
return listener;
}