Skip to content

Commit 27f1f32

Browse files
authored
[master378] Stop encoding a message when it is past its size limit (#5248)
Backport of the send-path part of master commit acac1e0 (#5066), adapted for master378. ## Problem A UA-TCP channel encoded a whole message into pooled send buffers and checked the size limits afterwards. A 4 MB response against a 64 KB limit rented about 515 buffers of 8 KB before it was rejected. When the encoder rejected the message, those buffers were not returned. ## Fix - The stream a message is encoded into takes at most one chunk more than a message within the limits can fill, so encoding stops there. The same response now rents at most 12 buffers. - The buffers of a message that could not be encoded are returned. ## Checklist _Put an `x` in the boxes that apply. You can complete these step by step after opening the PR._ - [ ] I have signed the [CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf) and read the [CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md) doc. - [x] I have added tests that prove my fix is effective or that my feature works and increased code coverage. - [ ] I have added all necessary documentation. - [ ] I have verified that my changes do not introduce (new) build or analyzer warnings. - [ ] If this PR changes C# source files, I ran **all** tests locally using the **UA.slnx** solution against at least .NET **Framework** and .NET **10**, and all passed. PRs changing only non-C# files do not require these .NET test runs. - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. - [ ] I have addressed **all** PR feedback received.
1 parent c5b82ab commit 27f1f32

3 files changed

Lines changed: 512 additions & 21 deletions

File tree

‎Stack/Opc.Ua.Core/Stack/Bindings/ArraySegmentStream.cs‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,18 @@ public ArraySegmentStream(BufferManager bufferManager)
9494
{
9595
}
9696

97+
/// <summary>
98+
/// The most buffers a writable stream takes from its buffer manager. Zero means
99+
/// no limit. A write that needs one more buffer fails with BadEncodingLimitsExceeded
100+
/// and sets <see cref="BufferLimitExceeded"/>.
101+
/// </summary>
102+
internal int MaxBufferCount { get; set; }
103+
104+
/// <summary>
105+
/// Whether a write failed because the stream holds <see cref="MaxBufferCount"/> buffers.
106+
/// </summary>
107+
internal bool BufferLimitExceeded { get; private set; }
108+
97109
/// <inheritdoc/>
98110
protected override void Dispose(bool disposing)
99111
{
@@ -635,6 +647,11 @@ private void CheckEndOfStream()
635647
throw new IOException("Attempt to write past end of stream.");
636648
}
637649

650+
if (MaxBufferCount != 0 && m_buffers.Count >= MaxBufferCount)
651+
{
652+
ThrowBufferLimitExceeded();
653+
}
654+
638655
byte[] newBuffer = m_bufferManager.TakeBuffer(
639656
m_bufferSize,
640657
"ArraySegmentStream.Write");
@@ -645,6 +662,26 @@ private void CheckEndOfStream()
645662
}
646663
}
647664

665+
/// <summary>
666+
/// Fails a write that needs more than <see cref="MaxBufferCount"/> buffers.
667+
/// </summary>
668+
[MethodImpl(MethodImplOptions.NoInlining)]
669+
private void ThrowBufferLimitExceeded()
670+
{
671+
// the write moved past the last buffer, so all of it is written.
672+
if (m_buffers.Count > 0)
673+
{
674+
m_endOfLastBuffer = m_buffers[^1].Count;
675+
}
676+
677+
BufferLimitExceeded = true;
678+
679+
throw ServiceResultException.Create(
680+
StatusCodes.BadEncodingLimitsExceeded,
681+
"The message does not fit in {0} buffers.",
682+
MaxBufferCount);
683+
}
684+
648685
/// <summary>
649686
/// Clears the buffers and resets the state variables.
650687
/// </summary>

‎Stack/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.Symmetric.cs‎

Lines changed: 89 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -526,38 +526,84 @@ protected BufferCollection WriteSymmetricMessage(
526526
}
527527

528528
// write the body to stream.
529+
bool truncated = false;
529530
var ostrm = new ArraySegmentStream(
530531
BufferManager,
531532
SendBufferSize,
532533
headerSize,
533534
maxPayloadSize);
534535

535-
// check for encodeable body.
536-
if (messageBody is IEncodeable encodeable)
536+
try
537537
{
538-
// debug code used to verify that message aborts are handled correctly.
539-
// int maxMessageSize = Quotas.MessageContext.MaxMessageSize;
540-
// Quotas.MessageContext.MaxMessageSize = Int32.MaxValue;
538+
// the stream does not take more chunks than a message within the
539+
// limits can fill, so a larger message is not encoded in full.
540+
int maxMessageSize = Quotas.MessageContext.MaxMessageSize;
541+
bool encoderLimit = maxMessageSize > 0 && messageBody is IEncodeable;
542+
int maxChannelSize = isRequest ? MaxRequestMessageSize : MaxResponseMessageSize;
543+
544+
// the size check of the channel below lets a body pass that is
545+
// up to the size of the chunk headers larger than its limit.
546+
ostrm.MaxBufferCount = encoderLimit
547+
? GetMaxBodyChunkCount(maxMessageSize, 0, maxPayloadSize)
548+
: GetMaxBodyChunkCount(
549+
maxChannelSize > 0 ? (long)maxChannelSize + headerSize : 0,
550+
isRequest ? MaxRequestChunkCount : MaxResponseChunkCount,
551+
maxPayloadSize);
552+
553+
try
554+
{
555+
// check for encodeable body.
556+
if (messageBody is IEncodeable encodeable)
557+
{
558+
// debug code used to verify that message aborts are handled correctly.
559+
// int maxMessageSize = Quotas.MessageContext.MaxMessageSize;
560+
// Quotas.MessageContext.MaxMessageSize = Int32.MaxValue;
541561

542-
BinaryEncoder.EncodeMessage(encodeable, ostrm, Quotas.MessageContext, true);
562+
BinaryEncoder.EncodeMessage(encodeable, ostrm, Quotas.MessageContext, true);
543563

544-
// Quotas.MessageContext.MaxMessageSize = maxMessageSize;
545-
}
564+
// Quotas.MessageContext.MaxMessageSize = maxMessageSize;
565+
}
566+
567+
// check for raw bytes.
568+
var rawBytes = messageBody as ArraySegment<byte>?;
569+
570+
if (rawBytes != null)
571+
{
572+
using var encoder = new BinaryEncoder(ostrm, Quotas.MessageContext, true);
573+
encoder.WriteRawBytes(
574+
rawBytes.Value.Array,
575+
rawBytes.Value.Offset,
576+
rawBytes.Value.Count);
577+
}
578+
}
579+
catch (Exception) when (ostrm.BufferLimitExceeded)
580+
{
581+
// the encoder reports a message that is larger than its limit
582+
// after it has written all of it. This is the same error.
583+
if (encoderLimit)
584+
{
585+
throw ServiceResultException.Create(
586+
StatusCodes.BadEncodingLimitsExceeded,
587+
"MaxMessageSize {0} exceeded.",
588+
maxMessageSize);
589+
}
546590

547-
// check for raw bytes.
548-
var rawBytes = messageBody as ArraySegment<byte>?;
591+
// the chunks written so far exceed the limits of the channel
592+
// and the message is aborted below.
593+
truncated = true;
594+
}
549595

550-
if (rawBytes != null)
596+
chunksToProcess = ostrm.GetBuffers("WriteSymmetricMessage");
597+
}
598+
finally
551599
{
552-
using var encoder = new BinaryEncoder(ostrm, Quotas.MessageContext, true);
553-
encoder.WriteRawBytes(
554-
rawBytes.Value.Array,
555-
rawBytes.Value.Offset,
556-
rawBytes.Value.Count);
600+
// returns the buffers of a body that could not be encoded.
601+
if (chunksToProcess == null)
602+
{
603+
ostrm.Dispose();
604+
}
557605
}
558606

559-
chunksToProcess = ostrm.GetBuffers("WriteSymmetricMessage");
560-
561607
// ensure there is at least one chunk.
562608
if (chunksToProcess.Count == 0)
563609
{
@@ -589,9 +635,10 @@ protected BufferCollection WriteSymmetricMessage(
589635
using var encoder = new BinaryEncoder(strm, Quotas.MessageContext, false);
590636
// check if the message needs to be aborted.
591637
if (MessageLimitsExceeded(
592-
isRequest,
593-
messageSize + chunkToProcess.Count - headerSize,
594-
ii + 1))
638+
isRequest,
639+
messageSize + chunkToProcess.Count - headerSize,
640+
ii + 1) ||
641+
(truncated && ii == chunksToProcess.Count - 1))
595642
{
596643
encoder.WriteUInt32(null, messageType | TcpMessageType.Abort);
597644

@@ -742,6 +789,27 @@ protected BufferCollection WriteSymmetricMessage(
742789
}
743790
}
744791

792+
/// <summary>
793+
/// The chunks a message body can fill before it is larger than a message size or
794+
/// a chunk count. Zero if there is no limit.
795+
/// </summary>
796+
/// <param name="maxBodySize">The largest body; zero if not limited.</param>
797+
/// <param name="maxChunkCount">The most chunks; zero if not limited.</param>
798+
/// <param name="maxPayloadSize">The body bytes a chunk holds.</param>
799+
private static int GetMaxBodyChunkCount(long maxBodySize, int maxChunkCount, int maxPayloadSize)
800+
{
801+
// one chunk more than the limit holds: a body that needs another chunk
802+
// is larger than the limit.
803+
long limit = maxChunkCount > 0 ? maxChunkCount + 1L : long.MaxValue;
804+
805+
if (maxBodySize > 0 && maxPayloadSize > 0)
806+
{
807+
limit = Math.Min(limit, (maxBodySize / maxPayloadSize) + 1L);
808+
}
809+
810+
return limit > int.MaxValue ? 0 : (int)limit;
811+
}
812+
745813
/// <summary>
746814
/// Decrypts and verifies a message chunk.
747815
/// </summary>

0 commit comments

Comments
 (0)