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 @@ -1405,7 +1405,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 @@ -2357,7 +2360,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 @@ -2395,6 +2399,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 @@ -2874,7 +2891,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 @@ -3031,6 +3051,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 @@ -3049,7 +3074,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 @@ -3186,6 +3186,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 @@ -3443,6 +3448,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 @@ -3451,11 +3461,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
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);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// 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>
/// <param name="builder">The connection settings whose pool will be isolated.</param>
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