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
33 changes: 30 additions & 3 deletions src/Bydlo.Engines/TgWsProxy/FakeTls.cs
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@ public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationTo
internal sealed class FakeTlsStream(Stream inner) : Stream
{
private readonly byte[] _header = new byte[5];
private byte[]? _record;
private int _recordLeft;

public override bool CanRead => true;
Expand Down Expand Up @@ -380,7 +381,12 @@ public override async ValueTask<int> ReadAsync(Memory<byte> buffer, Cancellation
{
if (length > 0)
{
await inner.ReadExactlyAsync(new byte[length], cancellationToken).ConfigureAwait(false);
_record ??= new byte[5 + FakeTls.MaxRecordPayload];
await inner.ReadExactlyAsync(_record.AsMemory(0, Math.Min(length, _record.Length)), cancellationToken).ConfigureAwait(false);
if (length > _record.Length)
{
await inner.ReadExactlyAsync(new byte[length - _record.Length], cancellationToken).ConfigureAwait(false);
}
}

continue;
Expand All @@ -404,8 +410,29 @@ public override async ValueTask<int> ReadAsync(Memory<byte> buffer, Cancellation
return n;
}

public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) =>
await inner.WriteAsync(Wrap(buffer.Span), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Writes records through one reusable buffer instead of allocating the wrapped payload (issue #359).
/// The bytes on the wire are identical to <see cref="Wrap"/>.
/// </summary>
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
_record ??= new byte[5 + FakeTls.MaxRecordPayload];
for (var offset = 0; offset < buffer.Length; offset += FakeTls.MaxRecordPayload)
{
var length = WriteRecord(buffer.Span.Slice(offset, Math.Min(FakeTls.MaxRecordPayload, buffer.Length - offset)), _record);
await inner.WriteAsync(_record.AsMemory(0, length), cancellationToken).ConfigureAwait(false);
}
}

private static int WriteRecord(ReadOnlySpan<byte> chunk, Span<byte> output)
{
output[0] = FakeTls.RecordApplicationData;
output[1] = 0x03;
output[2] = 0x03;
BinaryPrimitives.WriteUInt16BigEndian(output[3..], (ushort)chunk.Length);
chunk.CopyTo(output[5..]);
return 5 + chunk.Length;
}

public static byte[] Wrap(ReadOnlySpan<byte> data)
{
Expand Down
46 changes: 37 additions & 9 deletions src/Bydlo.Engines/TgWsProxy/MtProto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,21 +155,31 @@ internal sealed class MsgSplitter(uint protoTag)
private int _length;
private bool _disabled;

public List<byte[]> Split(ReadOnlySpan<byte> cipher, ReadOnlySpan<byte> plain)
private int _pending;

/// <summary>
/// Appends a chunk and reports the whole packets now available, without allocating (issue #359):
/// the packets are contiguous in the returned memory and <paramref name="lengths"/> receives
/// their sizes. The memory stays valid only until the next call to this splitter.
/// </summary>
public ReadOnlyMemory<byte> SplitInto(ReadOnlySpan<byte> cipher, ReadOnlySpan<byte> plain, List<int> lengths)
{
var parts = new List<byte[]>();
lengths.Clear();
Consume(_pending);
_pending = 0;
if (cipher.IsEmpty)
{
return parts;
return ReadOnlyMemory<byte>.Empty;
}

Append(cipher, plain);
if (_disabled)
{
parts.Add(cipher.ToArray());
return parts;
lengths.Add(_length);
_pending = _length;
return _cipher.AsMemory(0, _length);
}

Append(cipher, plain);
var offset = 0;
while (offset < _length)
{
Expand All @@ -182,22 +192,40 @@ public List<byte[]> Split(ReadOnlySpan<byte> cipher, ReadOnlySpan<byte> plain)
if (packet <= 0)
{
// Unknown framing: stop splitting and pass everything through as is.
parts.Add(_cipher.AsSpan(offset, _length - offset).ToArray());
lengths.Add(_length - offset);
offset = _length;
_disabled = true;
break;
}

parts.Add(_cipher.AsSpan(offset, packet.Value).ToArray());
lengths.Add(packet.Value);
offset += packet.Value;
}

Consume(offset);
_pending = offset;
return _cipher.AsMemory(0, offset);
}

/// <summary>Allocating form of <see cref="SplitInto"/>, kept for tests and rare paths.</summary>
public List<byte[]> Split(ReadOnlySpan<byte> cipher, ReadOnlySpan<byte> plain)
{
var lengths = new List<int>();
var packets = SplitInto(cipher, plain, lengths).Span;
var parts = new List<byte[]>(lengths.Count);
var at = 0;
foreach (var length in lengths)
{
parts.Add(packets.Slice(at, length).ToArray());
at += length;
}

return parts;
}

public byte[]? Flush()
{
Consume(_pending);
_pending = 0;
if (_length == 0)
{
return null;
Expand Down
Loading
Loading