Skip to content

Commit

Permalink
Use C# 8 using declarations.
Browse files Browse the repository at this point in the history
  • Loading branch information
bgrainger committed Sep 23, 2019
1 parent 5285bae commit 3852548
Show file tree
Hide file tree
Showing 45 changed files with 3,694 additions and 4,573 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,99 +58,97 @@ public byte[] CreateResponse(string password, ReadOnlySpan<byte> authenticationD
az[31] |= 64;
*/

using (var sha512 = SHA512.Create())
{
byte[] az = sha512.ComputeHash(passwordBytes);
ScalarOperations.sc_clamp(az, 0);

/*** Java
int mlen = seed.length;
final byte[] sm = new byte[64 + mlen];
System.arraycopy(seed, 0, sm, 64, mlen);
System.arraycopy(az, 32, sm, 32, 32);
byte[] buff = Arrays.copyOfRange(sm, 32, 96);
hash.reset();
byte[] nonce = hash.digest(buff);
*/
/*** C
unsigned char nonce[64];
unsigned char hram[64];
memmove(sm + 64,m,mlen);
memmove(sm + 32,az + 32,32);
crypto_hash_sha512(nonce,sm + 32,mlen + 32);
*/

byte[] sm = new byte[64 + authenticationData.Length];
authenticationData.CopyTo(sm.AsSpan().Slice(64));
Buffer.BlockCopy(az, 32, sm, 32, 32);
byte[] nonce = sha512.ComputeHash(sm, 32, authenticationData.Length + 32);

/*** Java
ScalarOps scalar = new ScalarOps();
EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName("Ed25519");
GroupElement elementAvalue = spec.getB().scalarMultiply(az);
byte[] elementAarray = elementAvalue.toByteArray();
System.arraycopy(elementAarray, 0, sm, 32, elementAarray.length);
*/
/*** C
ge_p3 A;
ge_scalarmult_base(&A,az);
ge_p3_tobytes(sm + 32,&A);
*/

GroupOperations.ge_scalarmult_base(out var A, az, 0);
GroupOperations.ge_p3_tobytes(sm, 32, ref A);

/*** Java
nonce = scalar.reduce(nonce);
GroupElement elementRvalue = spec.getB().scalarMultiply(nonce);
byte[] elementRarray = elementRvalue.toByteArray();
System.arraycopy(elementRarray, 0, sm, 0, elementRarray.length);
*/
/*** C
ge_p3 R;
sc_reduce(nonce);
ge_scalarmult_base(&R,nonce);
ge_p3_tobytes(sm,&R);
*/
ScalarOperations.sc_reduce(nonce);
GroupOperations.ge_scalarmult_base(out var R, nonce, 0);
GroupOperations.ge_p3_tobytes(sm, 0, ref R);

/*** Java
hash.reset();
byte[] hram = hash.digest(sm);
hram = scalar.reduce(hram);
byte[] tt = scalar.multiplyAndAdd(hram, az, nonce);
System.arraycopy(tt, 0, sm, 32, tt.length);
return Arrays.copyOfRange(sm, 0, 64);
*/
/*** C
unsigned char hram[64];
crypto_hash_sha512(hram,sm,mlen + 64);
sc_reduce(hram);
sc_muladd(sm + 32,hram,az,nonce);
return 0;
*/
var hram = sha512.ComputeHash(sm);
ScalarOperations.sc_reduce(hram);
var temp = new byte[32];
ScalarOperations.sc_muladd(temp, hram, az, nonce);
Buffer.BlockCopy(temp, 0, sm, 32, temp.Length);

var result = new byte[64];
Buffer.BlockCopy(sm, 0, result, 0, result.Length);
return result;
}
using var sha512 = SHA512.Create();
byte[] az = sha512.ComputeHash(passwordBytes);
ScalarOperations.sc_clamp(az, 0);

/*** Java
int mlen = seed.length;
final byte[] sm = new byte[64 + mlen];
System.arraycopy(seed, 0, sm, 64, mlen);
System.arraycopy(az, 32, sm, 32, 32);
byte[] buff = Arrays.copyOfRange(sm, 32, 96);
hash.reset();
byte[] nonce = hash.digest(buff);
*/
/*** C
unsigned char nonce[64];
unsigned char hram[64];
memmove(sm + 64,m,mlen);
memmove(sm + 32,az + 32,32);
crypto_hash_sha512(nonce,sm + 32,mlen + 32);
*/

byte[] sm = new byte[64 + authenticationData.Length];
authenticationData.CopyTo(sm.AsSpan().Slice(64));
Buffer.BlockCopy(az, 32, sm, 32, 32);
byte[] nonce = sha512.ComputeHash(sm, 32, authenticationData.Length + 32);

/*** Java
ScalarOps scalar = new ScalarOps();
EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName("Ed25519");
GroupElement elementAvalue = spec.getB().scalarMultiply(az);
byte[] elementAarray = elementAvalue.toByteArray();
System.arraycopy(elementAarray, 0, sm, 32, elementAarray.length);
*/
/*** C
ge_p3 A;
ge_scalarmult_base(&A,az);
ge_p3_tobytes(sm + 32,&A);
*/

GroupOperations.ge_scalarmult_base(out var A, az, 0);
GroupOperations.ge_p3_tobytes(sm, 32, ref A);

/*** Java
nonce = scalar.reduce(nonce);
GroupElement elementRvalue = spec.getB().scalarMultiply(nonce);
byte[] elementRarray = elementRvalue.toByteArray();
System.arraycopy(elementRarray, 0, sm, 0, elementRarray.length);
*/
/*** C
ge_p3 R;
sc_reduce(nonce);
ge_scalarmult_base(&R,nonce);
ge_p3_tobytes(sm,&R);
*/
ScalarOperations.sc_reduce(nonce);
GroupOperations.ge_scalarmult_base(out var R, nonce, 0);
GroupOperations.ge_p3_tobytes(sm, 0, ref R);

/*** Java
hash.reset();
byte[] hram = hash.digest(sm);
hram = scalar.reduce(hram);
byte[] tt = scalar.multiplyAndAdd(hram, az, nonce);
System.arraycopy(tt, 0, sm, 32, tt.length);
return Arrays.copyOfRange(sm, 0, 64);
*/
/*** C
unsigned char hram[64];
crypto_hash_sha512(hram,sm,mlen + 64);
sc_reduce(hram);
sc_muladd(sm + 32,hram,az,nonce);
return 0;
*/
var hram = sha512.ComputeHash(sm);
ScalarOperations.sc_reduce(hram);
var temp = new byte[32];
ScalarOperations.sc_muladd(temp, hram, az, nonce);
Buffer.BlockCopy(temp, 0, sm, 32, temp.Length);

var result = new byte[64];
Buffer.BlockCopy(sm, 0, result, 0, result.Length);
return result;
}

private Ed25519AuthenticationPlugin()
Expand Down
83 changes: 39 additions & 44 deletions src/MySqlConnector/Core/CachedProcedure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,35 +23,32 @@ internal sealed class CachedProcedure
{
try
{
using (var cmd = connection.CreateCommand())
using var cmd = connection.CreateCommand();
cmd.Transaction = connection.CurrentTransaction;
cmd.CommandText = @"SELECT param_list, returns FROM mysql.proc WHERE db = @schema AND name = @component";
cmd.Parameters.AddWithValue("@schema", schema);
cmd.Parameters.AddWithValue("@component", component);

using var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false);
var exists = await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
if (!exists)
return null;

var parametersSqlBytes = (byte[]) reader.GetValue(0);
var returnsSqlBytes = (byte[]) reader.GetValue(1);

// ASSUME this is UTF-8 encoded; it's possible that the `character_set_client` column would need to be used?
var parametersSql = Encoding.UTF8.GetString(parametersSqlBytes);
var returnsSql = Encoding.UTF8.GetString(returnsSqlBytes);

var parsedParameters = ParseParameters(parametersSql);
if (returnsSql.Length != 0)
{
cmd.Transaction = connection.CurrentTransaction;
cmd.CommandText = @"SELECT param_list, returns FROM mysql.proc WHERE db = @schema AND name = @component";
cmd.Parameters.AddWithValue("@schema", schema);
cmd.Parameters.AddWithValue("@component", component);
using (var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false))
{
var exists = await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
if (!exists)
return null;

var parametersSqlBytes = (byte[]) reader.GetValue(0);
var returnsSqlBytes = (byte[]) reader.GetValue(1);

// ASSUME this is UTF-8 encoded; it's possible that the `character_set_client` column would need to be used?
var parametersSql = Encoding.UTF8.GetString(parametersSqlBytes);
var returnsSql = Encoding.UTF8.GetString(returnsSqlBytes);

var parsedParameters = ParseParameters(parametersSql);
if (returnsSql.Length != 0)
{
var returnDataType = ParseDataType(returnsSql, out var unsigned, out var length);
parsedParameters.Insert(0, CreateCachedParameter(0, null, null, returnDataType, unsigned, length, returnsSql));
}

return new CachedProcedure(schema, component, parsedParameters);
}
var returnDataType = ParseDataType(returnsSql, out var unsigned, out var length);
parsedParameters.Insert(0, CreateCachedParameter(0, null, null, returnDataType, unsigned, length, returnsSql));
}

return new CachedProcedure(schema, component, parsedParameters);
}
catch (MySqlException ex)
{
Expand Down Expand Up @@ -82,24 +79,22 @@ FROM information_schema.parameters
cmd.Parameters.AddWithValue("@schema", schema);
cmd.Parameters.AddWithValue("@component", component);

using (var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false))
{
await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
routineCount = reader.GetInt32(0);
await reader.NextResultAsync(cancellationToken).ConfigureAwait(false);
using var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false);
await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
routineCount = reader.GetInt32(0);
await reader.NextResultAsync(cancellationToken).ConfigureAwait(false);

while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
var dataType = ParseDataType(reader.GetString(3), out var unsigned, out var length);
parameters.Add(new CachedParameter(
reader.GetInt32(0),
!reader.IsDBNull(1) ? reader.GetString(1) : null,
!reader.IsDBNull(2) ? reader.GetString(2) : null,
dataType,
unsigned,
length
));
}
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
var dataType = ParseDataType(reader.GetString(3), out var unsigned, out var length);
parameters.Add(new CachedParameter(
reader.GetInt32(0),
!reader.IsDBNull(1) ? reader.GetString(1) : null,
!reader.IsDBNull(2) ? reader.GetString(2) : null,
dataType,
unsigned,
length
));
}
}

Expand Down
40 changes: 19 additions & 21 deletions src/MySqlConnector/Core/CommandExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,28 +53,26 @@ public static async Task<DbDataReader> ExecuteReaderAsync(IReadOnlyList<IMySqlCo

cancellationToken.ThrowIfCancellationRequested();

using (var payload = writer.ToPayloadData())
using (command.CancellableCommand.RegisterCancel(cancellationToken))
using var payload = writer.ToPayloadData();
using var registration = command.CancellableCommand.RegisterCancel(cancellationToken);
connection.Session.StartQuerying(command.CancellableCommand);
command.SetLastInsertedId(-1);
try
{
connection.Session.StartQuerying(command.CancellableCommand);
command.SetLastInsertedId(-1);
try
{
await connection.Session.SendAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false);
return await MySqlDataReader.CreateAsync(commandListPosition, payloadCreator, cachedProcedures, command, behavior, ioBehavior, cancellationToken).ConfigureAwait(false);
}
catch (MySqlException ex) when (ex.Number == (int) MySqlErrorCode.QueryInterrupted && cancellationToken.IsCancellationRequested)
{
Log.Warn("Session{0} query was interrupted", connection.Session.Id);
throw new OperationCanceledException(cancellationToken);
}
catch (Exception ex) when (payload.Span.Length > 4_194_304 && (ex is SocketException || ex is IOException || ex is MySqlProtocolException))
{
// the default MySQL Server value for max_allowed_packet (in MySQL 5.7) is 4MiB: https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_max_allowed_packet
// use "decimal megabytes" (to round up) when creating the exception message
int megabytes = payload.Span.Length / 1_000_000;
throw new MySqlException("Error submitting {0}MB packet; ensure 'max_allowed_packet' is greater than {0}MB.".FormatInvariant(megabytes), ex);
}
await connection.Session.SendAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false);
return await MySqlDataReader.CreateAsync(commandListPosition, payloadCreator, cachedProcedures, command, behavior, ioBehavior, cancellationToken).ConfigureAwait(false);
}
catch (MySqlException ex) when (ex.Number == (int) MySqlErrorCode.QueryInterrupted && cancellationToken.IsCancellationRequested)
{
Log.Warn("Session{0} query was interrupted", connection.Session.Id);
throw new OperationCanceledException(cancellationToken);
}
catch (Exception ex) when (payload.Span.Length > 4_194_304 && (ex is SocketException || ex is IOException || ex is MySqlProtocolException))
{
// the default MySQL Server value for max_allowed_packet (in MySQL 5.7) is 4MiB: https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_max_allowed_packet
// use "decimal megabytes" (to round up) when creating the exception message
int megabytes = payload.Span.Length / 1_000_000;
throw new MySqlException("Error submitting {0}MB packet; ensure 'max_allowed_packet' is greater than {0}MB.".FormatInvariant(megabytes), ex);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/MySqlConnector/Core/ConnectionPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -475,8 +475,8 @@ private void StartReaperTask()
var task = Task.Delay(reaperInterval);
try
{
using (var source = new CancellationTokenSource(reaperInterval))
await ReapAsync(IOBehavior.Asynchronous, source.Token).ConfigureAwait(false);
using var source = new CancellationTokenSource(reaperInterval);
await ReapAsync(IOBehavior.Asynchronous, source.Token).ConfigureAwait(false);
}
catch
{
Expand Down
28 changes: 12 additions & 16 deletions src/MySqlConnector/Core/ResultSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,17 +76,15 @@ public async Task ReadResultSetHeaderAsync(IOBehavior ioBehavior)
&& !localInfile.FileName.StartsWith(MySqlBulkLoader.StreamPrefix, StringComparison.Ordinal))
throw new NotSupportedException("Use SourceStream or SslMode >= VerifyCA for LOAD DATA LOCAL INFILE. See https://fl.vu/mysql-load-data");

using (var stream = localInfile.FileName.StartsWith(MySqlBulkLoader.StreamPrefix, StringComparison.Ordinal) ?
using var stream = localInfile.FileName.StartsWith(MySqlBulkLoader.StreamPrefix, StringComparison.Ordinal) ?
MySqlBulkLoader.GetAndRemoveStream(localInfile.FileName) :
File.OpenRead(localInfile.FileName))
File.OpenRead(localInfile.FileName);
var readBuffer = new byte[65536];
int byteCount;
while ((byteCount = await stream.ReadAsync(readBuffer, 0, readBuffer.Length).ConfigureAwait(false)) > 0)
{
byte[] readBuffer = new byte[65536];
int byteCount;
while ((byteCount = await stream.ReadAsync(readBuffer, 0, readBuffer.Length).ConfigureAwait(false)) > 0)
{
payload = new PayloadData(new ArraySegment<byte>(readBuffer, 0, byteCount));
await Session.SendReplyAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false);
}
payload = new PayloadData(new ArraySegment<byte>(readBuffer, 0, byteCount));
await Session.SendReplyAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false);
}
}
catch (Exception ex)
Expand Down Expand Up @@ -213,13 +211,11 @@ public async Task<bool> ReadAsync(IOBehavior ioBehavior, CancellationToken cance
if (BufferState == ResultSetState.HasMoreData || BufferState == ResultSetState.NoMoreData || BufferState == ResultSetState.None)
return new ValueTask<Row?>(default(Row?));

using (Command.CancellableCommand.RegisterCancel(cancellationToken))
{
var payloadValueTask = Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None);
return payloadValueTask.IsCompletedSuccessfully
? new ValueTask<Row?>(ScanRowAsyncRemainder(this, payloadValueTask.Result, row))
: new ValueTask<Row?>(ScanRowAsyncAwaited(this, payloadValueTask.AsTask(), row, cancellationToken));
}
using var registration = Command.CancellableCommand.RegisterCancel(cancellationToken);
var payloadValueTask = Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None);
return payloadValueTask.IsCompletedSuccessfully
? new ValueTask<Row?>(ScanRowAsyncRemainder(this, payloadValueTask.Result, row))
: new ValueTask<Row?>(ScanRowAsyncAwaited(this, payloadValueTask.AsTask(), row, cancellationToken));

static async Task<Row?> ScanRowAsyncAwaited(ResultSet this_, Task<PayloadData> payloadTask, Row? row_, CancellationToken token)
{
Expand Down
Loading

0 comments on commit 3852548

Please sign in to comment.