Skip to content

Commit 66026a2

Browse files
committed
Added content-length and guard clauses to HttpContentStream
1 parent 90ebeae commit 66026a2

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

TechnitiumLibrary.Net/Http/HttpContentStream.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ You should have received a copy of the GNU General Public License
1919

2020
using System;
2121
using System.IO;
22+
using System.Net.Http;
2223
using System.Threading;
2324
using System.Threading.Tasks;
2425

@@ -43,6 +44,23 @@ class HttpContentStream : Stream
4344

4445
public HttpContentStream(Stream baseStream, byte[] buffer, int offset, int length, int contentLength = -1)
4546
{
47+
ArgumentOutOfRangeException.ThrowIfNegative(length);
48+
ArgumentNullException.ThrowIfNull(baseStream);
49+
ArgumentNullException.ThrowIfNull(buffer);
50+
if (offset < 0 || offset + length > buffer.Length)
51+
throw new ArgumentOutOfRangeException(nameof(offset));
52+
53+
// Validate Content-Length semantics
54+
if (contentLength < -1)
55+
throw new InvalidDataException("Invalid Content-Length value.");
56+
57+
int bufferedBodyBytes = length - offset;
58+
59+
// RFC 9112 §6.3 — recipient MUST NOT read beyond Content-Length
60+
if (contentLength != -1 && bufferedBodyBytes > contentLength)
61+
throw new HttpRequestException(
62+
$"HTTP protocol violation: buffered {bufferedBodyBytes} body bytes, " +
63+
$"but Content-Length is {contentLength}.");
4664
_baseStream = baseStream;
4765

4866
_buffer = buffer;

0 commit comments

Comments
 (0)