// and responses for unit test purposes. The validation checks the
// structure of the messages, their integrity and use of specified
// features (eg. MIC).
- internal class FakeNtlmServer
+ internal class FakeNtlmServer : IDisposable
{
public FakeNtlmServer(NetworkCredential expectedCredential)
{
UntrustedSPN = 4,
}
+ public void Dispose()
+ {
+ _clientSeal?.Dispose();
+ _clientSeal = null;
+ _serverSeal?.Dispose();
+ _serverSeal = null;
+ }
+
private static ReadOnlySpan<byte> GetField(ReadOnlySpan<byte> payload, int fieldOffset)
{
uint offset = BinaryPrimitives.ReadUInt32LittleEndian(payload.Slice(fieldOffset + 4));
public void ResetKeys()
{
+ _clientSeal?.Dispose();
+ _serverSeal?.Dispose();
+
_clientSeal = new RC4(_clientSealingKey);
_serverSeal = new RC4(_serverSealingKey);
}
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
+using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
if (!handle.IsInvalid)
{
- const int InitialBufferSize = 4096;
- char[]? buffer = ArrayPool<char>.Shared.Rent(InitialBufferSize);
- uint result = GetFinalPathNameByHandle(handle, buffer);
+ char[] buffer = new char[4096];
+ uint result;
+ fixed (char* bufPtr = buffer)
+ {
+ result = Interop.Kernel32.GetFinalPathNameByHandle(handle, bufPtr, (uint)buffer.Length, Interop.Kernel32.FILE_NAME_NORMALIZED);
+ }
+
+ if (result == 0)
+ {
+ throw new Win32Exception();
+ }
+
+ Debug.Assert(result <= buffer.Length);
// Remove extended prefix
int skip = PathInternal.IsExtended(buffer) ? 4 : 0;
- return new string(
- buffer,
- skip,
- (int)result - skip);
+ return new string(buffer, skip, (int)result - skip);
}
}
catch { }
return TestDirectory;
}
- private unsafe uint GetFinalPathNameByHandle(SafeFileHandle handle, char[] buffer)
- {
- fixed (char* bufPtr = buffer)
- {
- return Interop.Kernel32.GetFinalPathNameByHandle(handle, bufPtr, (uint)buffer.Length, Interop.Kernel32.FILE_NAME_NORMALIZED);
- }
- }
-
protected string CreateTestDirectory(params string[] paths)
{
string dir = Path.Combine(paths);
[Fact]
public void BasicTest()
{
- MultiArrayBuffer buffer = new MultiArrayBuffer(0);
+ using MultiArrayBuffer buffer = new MultiArrayBuffer(0);
Assert.True(buffer.IsEmpty);
Assert.True(buffer.ActiveMemory.IsEmpty);
{
const int Size = 64 * 1024 + 1;
- MultiArrayBuffer buffer = new MultiArrayBuffer(0);
+ using MultiArrayBuffer buffer = new MultiArrayBuffer(0);
for (int i = 0; i < Size; i++)
{
const int ByteCount = 7;
const int RepeatCount = 8 * 1024; // enough to ensure we cross several block boundaries
- MultiArrayBuffer buffer = new MultiArrayBuffer(0);
+ using MultiArrayBuffer buffer = new MultiArrayBuffer(0);
for (int i = 0; i < RepeatCount; i++)
{
const int ByteCount = 7;
const int RepeatCount = 8 * 1024; // enough to ensure we cross several block boundaries
- MultiArrayBuffer buffer = new MultiArrayBuffer(0);
+ using MultiArrayBuffer buffer = new MultiArrayBuffer(0);
for (int i = 0; i < RepeatCount; i++)
{
const int ByteCount = 7;
const int RepeatCount = 8 * 1024; // enough to ensure we cross several block boundaries
- MultiArrayBuffer buffer = new MultiArrayBuffer(0);
+ using MultiArrayBuffer buffer = new MultiArrayBuffer(0);
for (int i = 0; i < RepeatCount; i++)
{
const int RepeatCount = 8 * 1024; // enough to ensure we cross several block boundaries
- MultiArrayBuffer buffer = new MultiArrayBuffer(0);
+ using MultiArrayBuffer buffer = new MultiArrayBuffer(0);
for (int i = 0; i < RepeatCount; i++)
{
const int RepeatCount = 13;
- MultiArrayBuffer buffer = new MultiArrayBuffer(0);
+ using MultiArrayBuffer buffer = new MultiArrayBuffer(0);
for (int i = 0; i < RepeatCount; i++)
{
[Fact]
public void EnsureAvailableSpaceTest()
{
- MultiArrayBuffer buffer = new MultiArrayBuffer(0);
+ using MultiArrayBuffer buffer = new MultiArrayBuffer(0);
Assert.Equal(0, buffer.ActiveMemory.Length);
Assert.Equal(0, buffer.AvailableMemory.Length);
[Fact]
public void EnsureAvailableSpaceUpToLimitTest()
{
- MultiArrayBuffer buffer = new MultiArrayBuffer(0);
+ using MultiArrayBuffer buffer = new MultiArrayBuffer(0);
Assert.Equal(0, buffer.ActiveMemory.Length);
Assert.Equal(0, buffer.AvailableMemory.Length);
namespace System.Net.Http.Unit.Tests.QPack
{
- public class QPackDecoderTests
+ public class QPackDecoderTests : IDisposable
{
private const int MaxHeaderFieldSize = 8192;
_decoder = new QPackDecoder(MaxHeaderFieldSize);
}
+ public void Dispose()
+ {
+ _decoder.Dispose();
+ }
+
[Fact]
public void DecodesIndexedHeaderField_StaticTableWithValue()
{
private static void TestDecode(byte[] encoded, KeyValuePair<string, string>[] expectedValues, bool expectDynamicTableEntry, int? bytesAtATime)
{
- QPackDecoder decoder = new QPackDecoder(MaxHeaderFieldSize);
+ using QPackDecoder decoder = new QPackDecoder(MaxHeaderFieldSize);
TestHttpHeadersHandler handler = new TestHttpHeadersHandler();
// Read past header
Assert.NotEqual(0, sb.Length);
Assert.Equal(sb.Length, vsb.Length);
+ Assert.Equal(sb.ToString(), vsb.ToString());
}
[Fact]
Assert.Equal('b', vsb[3]);
vsb[3] = 'c';
Assert.Equal('c', vsb[3]);
+ vsb.Dispose();
}
[Fact]
builder.EnsureCapacity(33);
Assert.Equal(64, builder.Capacity);
+ builder.Dispose();
}
[Fact]
builder.EnsureCapacity(16);
Assert.Equal(64, builder.Capacity);
+ builder.Dispose();
}
}
}
AssertFileModeEquals(filePath, TestPermission1);
}
- [Fact]
+ [ConditionalFact(typeof(MountHelper), nameof(MountHelper.CanCreateSymbolicLinks))]
public void LinkBeforeTarget()
{
using TempDirectory source = new TempDirectory();
AssertFileModeEquals(filePath, TestPermission1);
}
- [Fact]
+ [ConditionalFact(typeof(MountHelper), nameof(MountHelper.CanCreateSymbolicLinks))]
public async Task LinkBeforeTargetAsync()
{
using TempDirectory source = new TempDirectory();
public static void MemoryPoolPinBadOffset(int elementIndex)
{
MemoryPool<int> pool = MemoryPool<int>.Shared;
- IMemoryOwner<int> block = pool.Rent(10);
+ using IMemoryOwner<int> block = pool.Rent(10);
Memory<int> memory = block.Memory;
Span<int> sp = memory.Span;
Assert.Equal(memory.Length, sp.Length);
public static void MemoryPoolPinOffsetAtEnd()
{
MemoryPool<int> pool = MemoryPool<int>.Shared;
- IMemoryOwner<int> block = pool.Rent(10);
+ using IMemoryOwner<int> block = pool.Rent(10);
Memory<int> memory = block.Memory;
Span<int> sp = memory.Span;
Assert.Equal(memory.Length, sp.Length);
public static void MemoryPoolPinBadOffsetTooLarge()
{
MemoryPool<int> pool = MemoryPool<int>.Shared;
- IMemoryOwner<int> block = pool.Rent(10);
+ using IMemoryOwner<int> block = pool.Rent(10);
Memory<int> memory = block.Memory;
Span<int> sp = memory.Span;
Assert.Equal(memory.Length, sp.Length);
var model = new TestModel { Message = message };
var stream = new MemoryStream();
- var transcodingStream = new TranscodingWriteStream(stream, targetEncoding);
+ using var transcodingStream = new TranscodingWriteStream(stream, targetEncoding);
await JsonSerializer.SerializeAsync(transcodingStream, model, model.GetType());
// The transcoding streams use Encoders and Decoders that have internal buffers. We need to flush these
// when there is no more data to be written. Stream.FlushAsync isn't suitable since it's
}
while (!isAuthenticated);
+ fakeNtlmServer?.Dispose();
+
await connection.SendResponseAsync(HttpStatusCode.OK);
}
else if (parts[1].Equals("GSSAPI", StringComparison.OrdinalIgnoreCase))
{
Debug.Assert(ExpectedGssapiCredential != null);
- FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(ExpectedGssapiCredential) { ForceNegotiateVersion = true };
+ using FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(ExpectedGssapiCredential) { ForceNegotiateVersion = true };
FakeNegotiateServer fakeNegotiateServer = new FakeNegotiateServer(fakeNtlmServer);
try
private void ResetKeys()
{
+ // Release buffers to pool
+ _clientSeal?.Dispose();
+ _serverSeal?.Dispose();
+
_clientSeal = new RC4(_clientSealingKey);
_serverSeal = new RC4(_serverSealingKey);
}
[ConditionalFact(nameof(IsNtlmAvailable))]
public void RemoteIdentity_ThrowsOnDisposed()
{
- FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight);
+ using FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight);
NegotiateAuthentication negotiateAuthentication = new NegotiateAuthentication(
new NegotiateAuthenticationClientOptions
{
{
// Mirrors the NTLMv2 example in the NTLM specification:
NetworkCredential credential = new NetworkCredential("User", "Password", "Domain");
- FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(credential);
+ using FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(credential);
fakeNtlmServer.SendTimestamp = false;
fakeNtlmServer.TargetIsServer = true;
fakeNtlmServer.PreferUnicode = false;
[ConditionalFact(nameof(IsNtlmAvailable))]
public void NtlmCorrectExchangeTest()
{
- FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight);
+ using FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight);
NegotiateAuthentication ntAuth = new NegotiateAuthentication(
new NegotiateAuthenticationClientOptions
{
[ConditionalFact(nameof(IsNtlmAvailable))]
public void NtlmIncorrectExchangeTest()
{
- FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight);
+ using FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight);
NegotiateAuthentication ntAuth = new NegotiateAuthentication(
new NegotiateAuthenticationClientOptions
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/65678", TestPlatforms.OSX | TestPlatforms.iOS | TestPlatforms.MacCatalyst)]
public void NtlmSignatureTest()
{
- FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight);
+ using FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight);
NegotiateAuthentication ntAuth = new NegotiateAuthentication(
new NegotiateAuthenticationClientOptions
{
public void NegotiateCorrectExchangeTest(bool requestMIC, bool requestConfidentiality)
{
// Older versions of gss-ntlmssp on Linux generate MIC at incorrect offset unless ForceNegotiateVersion is specified
- FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight) { ForceNegotiateVersion = true };
+ using FakeNtlmServer fakeNtlmServer = new FakeNtlmServer(s_testCredentialRight) { ForceNegotiateVersion = true };
FakeNegotiateServer fakeNegotiateServer = new FakeNegotiateServer(fakeNtlmServer) { RequestMIC = requestMIC };
NegotiateAuthentication ntAuth = new NegotiateAuthentication(
new NegotiateAuthenticationClientOptions
}
}
- return modified ? sb.ToString() : expression;
+ if (!modified)
+ {
+ sb.Dispose();
+ return expression;
+ }
+
+ return sb.ToString();
}
/// <summary>Verifies whether the given Win32 expression matches the given name. Supports the following wildcards: '*', '?', '<', '>', '"'. The backslash character '\' escapes.</summary>
[InlineData(-16, 1)]
public void LengthAndHoleArguments_Valid(int literalLength, int formattedCount)
{
- new DefaultInterpolatedStringHandler(literalLength, formattedCount);
+ new DefaultInterpolatedStringHandler(literalLength, formattedCount).ToStringAndClear();
Span<char> scratch1 = stackalloc char[1];
foreach (IFormatProvider provider in new IFormatProvider[] { null, new ConcatFormatter(), CultureInfo.InvariantCulture, CultureInfo.CurrentCulture, new CultureInfo("en-US"), new CultureInfo("fr-FR") })
{
- new DefaultInterpolatedStringHandler(literalLength, formattedCount, provider);
+ new DefaultInterpolatedStringHandler(literalLength, formattedCount, provider).ToStringAndClear();
- new DefaultInterpolatedStringHandler(literalLength, formattedCount, provider, default);
- new DefaultInterpolatedStringHandler(literalLength, formattedCount, provider, scratch1);
- new DefaultInterpolatedStringHandler(literalLength, formattedCount, provider, Array.Empty<char>());
- new DefaultInterpolatedStringHandler(literalLength, formattedCount, provider, new char[256]);
+ new DefaultInterpolatedStringHandler(literalLength, formattedCount, provider, default).ToStringAndClear();
+ new DefaultInterpolatedStringHandler(literalLength, formattedCount, provider, scratch1).ToStringAndClear();
+ new DefaultInterpolatedStringHandler(literalLength, formattedCount, provider, Array.Empty<char>()).ToStringAndClear();
+ new DefaultInterpolatedStringHandler(literalLength, formattedCount, provider, new char[256]).ToStringAndClear();
}
}
handler.AppendFormatted(tss, 1, "X2");
Assert.Same(provider, tss.ToStringState.LastProvider);
}
+
+ handler.ToStringAndClear();
}
[Fact]
handler.AppendFormatted(t, 1, "X2");
Assert.Same(provider, ((IHasToStringState)t).ToStringState.LastProvider);
+
+ handler.ToStringAndClear();
}
Test(new FormattableInt32Wrapper(42));
{
Assert.Equal(0, testSpan[i]);
}
+
+ ArrayPool<byte>.Shared.Return(rented, clearArray: false);
}
[Fact]
[InlineData("{ \"key\" : \"value\" }")]
public void RoundtripJsonDocument(string json)
{
- JsonDocument jsonDocument = JsonDocument.Parse(json);
+ using JsonDocument jsonDocument = JsonDocument.Parse(json);
string actualJson = JsonSerializer.Serialize(jsonDocument, DefaultContext.JsonDocument);
JsonTestHelper.AssertJsonEqual(json, actualJson);
- JsonDocument actualJsonDocument = JsonSerializer.Deserialize(actualJson, DefaultContext.JsonDocument);
+ using JsonDocument actualJsonDocument = JsonSerializer.Deserialize(actualJson, DefaultContext.JsonDocument);
JsonTestHelper.AssertJsonEqual(jsonDocument.RootElement, actualJsonDocument.RootElement);
}
[InlineData("{ \"key\" : \"value\" }")]
public void RoundtripJsonElement(string json)
{
- JsonElement jsonElement = JsonDocument.Parse(json).RootElement;
+ using JsonDocument jsonDocument = JsonDocument.Parse(json);
+ JsonElement jsonElement = jsonDocument.RootElement;
string actualJson = JsonSerializer.Serialize(jsonElement, DefaultContext.JsonElement);
JsonTestHelper.AssertJsonEqual(json, actualJson);