Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1500,7 +1500,10 @@ internal void TdsLogin(
#nullable enable
internal void ProcessSSPI(int receivedLength)
{
Debug.Assert(_authenticationProvider is not null);
if (_authenticationProvider is null)
{
ThrowCorruptedTdsStream();
}

SniContext outerContext = _physicalStateObj.SniContext;
_physicalStateObj.SniContext = SniContext.Snix_ProcessSspi;
Expand Down Expand Up @@ -2453,7 +2456,8 @@ internal bool Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader
}

/// <summary>
/// Checks if the given token is a valid TDS token
/// Checks whether the token type is recognized. Its handler must also validate the
/// parser state required to process it.
/// </summary>
/// <param name="token">Token to check</param>
/// <returns>True if the token is a valid TDS token, otherwise false</returns>
Expand Down Expand Up @@ -2491,6 +2495,19 @@ internal static bool IsValidTdsToken(byte token)
token == TdsEnums.SQLFEDAUTHINFO);
}

/// <summary>
/// Rejects invalid token prerequisites using the existing parsing error, after ensuring
/// the connection cannot be reused. This does not convert other failures to SqlException.
/// </summary>
internal void ThrowCorruptedTdsStream()
{
SqlClientEventSource.Log.TryTraceEvent(
"<sc.TdsParser|ERR> Invalid state for received TDS token. Object ID {0}", ObjectID);
_state = TdsParserState.Broken;
_connHandler.BreakConnection();
throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream);
}

// Main parse loop for the top-level tds tokens, calls back into the I*Handler interfaces
internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, out bool dataReady)
{
Expand Down Expand Up @@ -2971,7 +2988,10 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle
case TdsEnums.SQLROW:
case TdsEnums.SQLNBCROW:
{
Debug.Assert(stateObj._cleanupMetaData != null, "Reading a row, but the metadata is null");
if (stateObj._cleanupMetaData == null)
{
ThrowCorruptedTdsStream();
}

if (token == TdsEnums.SQLNBCROW)
{
Expand Down Expand Up @@ -3128,6 +3148,11 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle
}
case TdsEnums.SQLALTROW:
{
if (stateObj._cleanupAltMetaDataSetArray == null)
{
ThrowCorruptedTdsStream();
}

result = stateObj.TryStartNewRow(isNullCompressed: false);
if (result != TdsOperationStatus.Done)
{
Expand All @@ -3146,7 +3171,14 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle
return result;
}

result = TrySkipRow(stateObj._cleanupAltMetaDataSetArray.GetAltMetadata(altRowId), stateObj);
TdsColumnMetadataToken metadata =
stateObj._cleanupAltMetaDataSetArray.GetAltMetadata(altRowId);
if (metadata == null)
{
ThrowCorruptedTdsStream();
}

result = TrySkipRow(metadata, stateObj);
if (result != TdsOperationStatus.Done)
{
// skip altRow
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Diagnostics;

namespace Microsoft.Data.SqlClient.Parser.Tokens
{
Expand Down Expand Up @@ -57,8 +56,6 @@ internal TdsColumnMetadataToken GetAltMetadata(int id)
}
}

// @TODO: Debug fail usage here isn't ideal.
Debug.Fail("Can't match up altMetaDataSet with given id");
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3328,6 +3328,11 @@ private TdsOperationStatus TryHasMoreResults(out bool moreResults)

// deprecated
case TdsEnums.SQLALTROW:
if (_altMetaDataSetCollection == null)
{
_parser.ThrowCorruptedTdsStream();
}

if (_altRowStatus == ALTROWSTATUS.Null)
{
// cache the regular metadata
Expand Down Expand Up @@ -3585,6 +3590,11 @@ private TdsOperationStatus TryNextResult(out bool more)
switch (_altRowStatus)
{
case ALTROWSTATUS.AltRow:
if (_altMetaDataSetCollection == null)
{
_parser.ThrowCorruptedTdsStream();
}

int altRowId;
result = _parser.TryGetAltRowId(_stateObj, out altRowId);
if (result != TdsOperationStatus.Done)
Expand All @@ -3593,11 +3603,11 @@ private TdsOperationStatus TryNextResult(out bool more)
return result;
}
TdsColumnMetadataToken altMetaDataSet = _altMetaDataSetCollection.GetAltMetadata(altRowId);
if (altMetaDataSet != null)
if (altMetaDataSet == null)
{
_metaData = altMetaDataSet;
_parser.ThrowCorruptedTdsStream();
}
Debug.Assert((_metaData != null), "Can't match up altrowmetadata");
_metaData = altMetaDataSet;
break;
case ALTROWSTATUS.Done:
// restore the row-metaData
Expand Down
Comment thread
cheenamalhotra marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;

namespace Microsoft.Data.SqlClient.Tests.Common;

/// <summary>
/// Selects the connection pool implementation (<c>WaitHandleDbConnectionPool</c> or
/// <c>ChannelDbConnectionPool</c>) for the duration of a test.
///
/// A pool is bound to an implementation when it is created, so simply flipping the
/// <c>UseConnectionPoolV2</c> switch is not enough: pools created before the switch was flipped
/// keep their original implementation, and pools created inside the scope would otherwise outlive
/// it and leak the chosen implementation into unrelated tests. This scope therefore clears all
/// pools both on entry and on exit.
///
/// This follows the RAII pattern; construct it at the start of a test and dispose it at the end.
/// Like <see cref="LocalAppContextSwitchesHelper"/>, it manipulates global state and enforces a
/// single-instance policy, so it must not be held for longer than necessary.
/// </summary>
public sealed class ConnectionPoolVersionScope : IDisposable
{
private readonly LocalAppContextSwitchesHelper _switches;

/// <summary>
/// Clears all existing pools and selects the requested pool implementation.
/// </summary>
/// <param name="usePoolV2">
/// True to use <c>ChannelDbConnectionPool</c>; false to use <c>WaitHandleDbConnectionPool</c>.
/// </param>
public ConnectionPoolVersionScope(bool usePoolV2)
{
_switches = new LocalAppContextSwitchesHelper();

try
{
SqlConnection.ClearAllPools();
_switches.UseConnectionPoolV2 = usePoolV2;
}
catch
{
_switches.Dispose();
throw;
}
}

/// <summary>
/// Clears all pools created under the selected implementation and restores the original
/// switch values.
/// </summary>
public void Dispose()
{
try
{
SqlConnection.ClearAllPools();
}
finally
{
_switches.Dispose();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
<Compile Include="SQL\ConnectivityTests\AADConnectionTest.cs" />
<Compile Include="SQL\ConnectivityTests\ConnectionBehaviorTest.cs" />
<Compile Include="SQL\ConnectivityTests\ConnectivityTest.cs" />
<Compile Include="SQL\ConnectivityTests\ParserResultProcessingTest.cs" />
<Compile Include="SQL\ConnectivityTests\TcpDefaultForAzureTest.cs" />
<Compile Include="SQL\DataBaseSchemaTest\ConnectionSchemaTest.cs" />
<Compile Include="SQL\DataClassificationTest\DataClassificationTest.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Data;
using System.Threading.Tasks;
using Xunit;

namespace Microsoft.Data.SqlClient.ManualTesting.Tests;

/// <summary>
/// Verifies that parser prerequisite validation preserves valid login, nullable rows,
/// result skipping, and subsequent commands against SQL Server.
/// </summary>
[Trait("Set", "2")]
public class ParserResultProcessingTest
{
/// <summary>
/// Consumes null and non-null values, skips unread rows, and reuses the connection with
/// synchronous/asynchronous APIs and both buffered and sequential access.
/// </summary>
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public async Task ValidResults_PreserveConnection(bool useAsync, bool sequential)
{
using SqlConnection connection = new(DataTestUtility.TCPConnectionString);
if (useAsync)
{
await connection.OpenAsync();
}
else
{
connection.Open();
}

// Sorting puts NULL first and leaves a deterministic unread row before the second result.
using SqlCommand command = new(
"SELECT CAST(NULL AS int) AS value UNION ALL SELECT 1 UNION ALL SELECT 2 " +
"ORDER BY value; " +
"SELECT 42 AS value;", connection);
CommandBehavior behavior = sequential
? CommandBehavior.SequentialAccess
: CommandBehavior.Default;
using (SqlDataReader reader = useAsync
? await command.ExecuteReaderAsync(behavior)
: command.ExecuteReader(behavior))
{
Assert.True(useAsync ? await reader.ReadAsync() : reader.Read());
Assert.True(reader.IsDBNull(0));
Assert.True(useAsync ? await reader.ReadAsync() : reader.Read());
Assert.Equal(1, reader.GetInt32(0));
// Skip the unread value 2 and verify that the next result uses its own metadata.
Assert.True(useAsync ? await reader.NextResultAsync() : reader.NextResult());
Assert.True(useAsync ? await reader.ReadAsync() : reader.Read());
Assert.Equal(42, reader.GetInt32(0));
Assert.False(useAsync ? await reader.ReadAsync() : reader.Read());
Assert.False(useAsync ? await reader.NextResultAsync() : reader.NextResult());
}

// A subsequent command proves valid result processing did not invalidate the connection.
command.CommandText = "SELECT 7";
object result = useAsync
? await command.ExecuteScalarAsync()
: command.ExecuteScalar();
Assert.Equal(7, result);
Assert.Equal(ConnectionState.Open, connection.State);
}
}
Comment thread
cheenamalhotra marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;

namespace Microsoft.Data.SqlClient.UnitTests.SimulatedServerTests;

/// <summary>
/// Gives a scenario its own pool and clears it before its ephemeral servers are disposed.
/// Declare before the scenario's connections so they are returned before the pool is cleared.
/// </summary>
internal sealed class SimulatedServerPoolScope : IDisposable
{
private readonly SqlConnection _poolKey;

/// <summary>
/// Isolates the builder's pool from other test cases and previous uses of the same TCP port.
/// </summary>
public SimulatedServerPoolScope(SqlConnectionStringBuilder builder)
{
builder.ApplicationName = Guid.NewGuid().ToString();
_poolKey = new SqlConnection(builder.ConnectionString);
}

/// <summary>
/// Removes only this scenario's pool, without affecting other simulator clients.
/// </summary>
public void Dispose()
{
SqlConnection.ClearPool(_poolKey);
_poolKey.Dispose();
}
}
Loading
Loading