Skip to content
60 changes: 56 additions & 4 deletions src/Http/WebUtilities/src/BufferedReadStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using System.Text;

namespace Microsoft.AspNetCore.WebUtilities;
Expand Down Expand Up @@ -346,17 +347,32 @@ public async Task<bool> EnsureBufferedAsync(int minCount, CancellationToken canc
public string ReadLine(int lengthLimit)
{
CheckDisposed();
using (var builder = new MemoryStream(200))
MemoryStream? builder = null;
try
{
bool foundCR = false, foundCRLF = false;
var lineLength = 0;

while (!foundCRLF && EnsureBuffered())
{
if (builder is null)
{
if (TryReadLineFromBuffer(lengthLimit, out var line))
{
return line;
}

builder = new MemoryStream(200);
}

ProcessLineChar(builder, ref lineLength, lengthLimit, ref foundCR, ref foundCRLF);
}

return DecodeLine(builder, foundCRLF);
return builder is null ? string.Empty : DecodeLine(builder, foundCRLF);
}
finally
{
builder?.Dispose();
}
}

Expand All @@ -371,18 +387,54 @@ public string ReadLine(int lengthLimit)
public async Task<string> ReadLineAsync(int lengthLimit, CancellationToken cancellationToken)
{
CheckDisposed();
using (var builder = new MemoryStream(200))
MemoryStream? builder = null;
try
{
bool foundCR = false, foundCRLF = false;
var lineLength = 0;

while (!foundCRLF && await EnsureBufferedAsync(cancellationToken))
{
if (builder is null)
{
if (TryReadLineFromBuffer(lengthLimit, out var line))
{
return line;
}

builder = new MemoryStream(200);
}

ProcessLineChar(builder, ref lineLength, lengthLimit, ref foundCR, ref foundCRLF);
}

return DecodeLine(builder, foundCRLF);
return builder is null ? string.Empty : DecodeLine(builder, foundCRLF);
}
finally
{
builder?.Dispose();
}
}

// Fast path for the common case where the whole line, including the terminating CRLF, is already buffered.
// This avoids accumulating the line in a temporary MemoryStream one byte at a time.
private bool TryReadLineFromBuffer(int lengthLimit, [NotNullWhen(true)] out string? line)
{
var buffered = _buffer.AsSpan(_bufferOffset, _bufferCount);
var index = buffered.IndexOf("\r\n"u8);

// ProcessLineChar enforces the limit on every byte up to and including the CR,
// so defer to it when the limit would be exceeded so the same exception is produced.
if (index < 0 || index >= lengthLimit)
{
line = null;
return false;
}

line = Encoding.UTF8.GetString(buffered.Slice(0, index));
_bufferOffset += index + 2;
_bufferCount -= index + 2;
return true;
}

private void ProcessLineChar(MemoryStream builder, ref int lineLength, int lengthLimit, ref bool foundCR, ref bool foundCRLF)
Expand Down
2 changes: 1 addition & 1 deletion src/Http/WebUtilities/src/MultipartReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ private async Task<Dictionary<string, StringValues>> ReadHeadersAsync(Cancellati
}

var name = line.Substring(0, splitIndex);
var value = line.Substring(splitIndex + 1, line.Length - splitIndex - 1).Trim();
var value = line.AsSpan(splitIndex + 1).Trim().ToString();
accumulator.Append(name, value);
if (accumulator.KeyCount > HeadersCountLimit)
{
Expand Down
87 changes: 87 additions & 0 deletions src/Http/WebUtilities/test/BufferedReadStreamTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Text;

namespace Microsoft.AspNetCore.WebUtilities;
Expand Down Expand Up @@ -72,8 +73,94 @@ public void ReadLine_LineSpanningMultipleBuffersWithinLimit_Succeeds()
Assert.Equal(content, line);
}

[Fact]
public async Task ReadLineAsync_MultipleLinesWithinSingleBuffer_ReadsEachLineAndLeavesRemainder()
{
var stream = MakeStream("first\r\n\r\nthird\rwith\nlone\r\nremainder", bufferSize: 4096);

Assert.Equal("first", await stream.ReadLineAsync(lengthLimit: 100, CancellationToken.None));
Assert.Equal("", await stream.ReadLineAsync(lengthLimit: 100, CancellationToken.None));
Assert.Equal("third\rwith\nlone", await stream.ReadLineAsync(lengthLimit: 100, CancellationToken.None));

var remainder = new byte[100];
var read = await stream.ReadAsync(remainder, 0, remainder.Length);
Assert.Equal("remainder", Encoding.UTF8.GetString(remainder, 0, read));
}

[Fact]
public void ReadLine_MultipleLinesWithinSingleBuffer_ReadsEachLineAndLeavesRemainder()
{
var stream = MakeStream("first\r\n\r\nthird\rwith\nlone\r\nremainder", bufferSize: 4096);

Assert.Equal("first", stream.ReadLine(lengthLimit: 100));
Assert.Equal("", stream.ReadLine(lengthLimit: 100));
Assert.Equal("third\rwith\nlone", stream.ReadLine(lengthLimit: 100));
Assert.Equal("remainder", stream.ReadLine(lengthLimit: 100));
Assert.Equal("", stream.ReadLine(lengthLimit: 100));
}

[Theory]
[InlineData("abc\r\n", 4, "abc")]
[InlineData("\r\n", 1, "")]
[InlineData("h\u00e9llo\r\n", 7, "h\u00e9llo")]
public async Task ReadLineAsync_LineWithinSingleBufferAtLimit_Succeeds(string text, int lengthLimit, string expected)
{
var stream = MakeStream(text, bufferSize: 4096);

Assert.Equal(expected, await stream.ReadLineAsync(lengthLimit, CancellationToken.None));
Assert.Equal(expected, MakeStream(text, bufferSize: 4096).ReadLine(lengthLimit));
}

[Theory]
[InlineData("abc\r\n", 3)]
[InlineData("\r\n", 0)]
[InlineData("h\u00e9llo\r\n", 6)]
public async Task ReadLineAsync_LineWithinSingleBufferExceedingLimit_Throws(string text, int lengthLimit)
{
var stream = MakeStream(text, bufferSize: 4096);

var exception = await Assert.ThrowsAsync<InvalidDataException>(
() => stream.ReadLineAsync(lengthLimit, CancellationToken.None));
Assert.Equal($"Line length limit {lengthLimit} exceeded.", exception.Message);

exception = Assert.Throws<InvalidDataException>(() => MakeStream(text, bufferSize: 4096).ReadLine(lengthLimit));
Assert.Equal($"Line length limit {lengthLimit} exceeded.", exception.Message);
}

[Fact]
public async Task ReadLineAsync_CrLfSplitAcrossBuffers_Succeeds()
{
// "abc\r" fills the first buffer and "\n" arrives in the next one.
var stream = MakeStream("abc\r\nnext\r\n", bufferSize: 4, new ExactSizeArrayPool());

Assert.Equal("abc", await stream.ReadLineAsync(lengthLimit: 100, CancellationToken.None));
Assert.Equal("next", await stream.ReadLineAsync(lengthLimit: 100, CancellationToken.None));
Assert.Equal("", await stream.ReadLineAsync(lengthLimit: 100, CancellationToken.None));

stream = MakeStream("abc\r\nnext\r\n", bufferSize: 4, new ExactSizeArrayPool());

Assert.Equal("abc", stream.ReadLine(lengthLimit: 100));
Assert.Equal("next", stream.ReadLine(lengthLimit: 100));
Assert.Equal("", stream.ReadLine(lengthLimit: 100));
}

private static BufferedReadStream MakeStream(string text, int bufferSize)
{
return new BufferedReadStream(new MemoryStream(Encoding.UTF8.GetBytes(text)), bufferSize);
}

private static BufferedReadStream MakeStream(string text, int bufferSize, ArrayPool<byte> bytePool)
{
return new BufferedReadStream(new MemoryStream(Encoding.UTF8.GetBytes(text)), bufferSize, bytePool);
}

// ArrayPool<byte>.Shared can return larger arrays than requested, which would buffer the whole input at once.
private sealed class ExactSizeArrayPool : ArrayPool<byte>
{
public override byte[] Rent(int minimumLength) => new byte[minimumLength];

public override void Return(byte[] array, bool clearArray = false)
{
}
}
}
Loading