From ff9e76392c4dd4a5f764c652e9501fe036379c65 Mon Sep 17 00:00:00 2001 From: maikebing Date: Fri, 13 Nov 2026 00:53:12 +0800 Subject: [PATCH 1/7] fix(protocol): bind response matching to peer and message ID --- CoAP.NET/Net/Matcher.cs | 110 +++++++++++-- CoAP.Test/MatcherProtocolTest.cs | 273 +++++++++++++++++++++++++++++++ 2 files changed, 370 insertions(+), 13 deletions(-) create mode 100644 CoAP.Test/MatcherProtocolTest.cs diff --git a/CoAP.NET/Net/Matcher.cs b/CoAP.NET/Net/Matcher.cs index cbfa078..0292d1b 100644 --- a/CoAP.NET/Net/Matcher.cs +++ b/CoAP.NET/Net/Matcher.cs @@ -90,7 +90,7 @@ public void SendRequest(Exchange exchange, Request request) // the MID is from the local namespace -- use blank address Exchange.KeyID keyID = new Exchange.KeyID(request.ID, null); - Exchange.KeyToken keyToken = new Exchange.KeyToken(request.Token); + Exchange.KeyToken keyToken = new TokenKey(request.Token, request.Multicast ? null : request.Destination); exchange.Completed += OnExchangeCompleted; @@ -301,10 +301,8 @@ public Exchange ReceiveResponse(Response response) // remote namespace keyId = new Exchange.KeyID(response.ID, response.Source); - Exchange.KeyToken keyToken = new Exchange.KeyToken(response.Token); - Exchange exchange; - if (_exchangesByToken.TryGetValue(keyToken, out exchange)) + if (TryGetResponseExchange(response, out exchange)) { // There is an exchange with the given token Exchange prev = _deduplicator.FindPrevious(keyId, exchange); @@ -323,13 +321,6 @@ public Exchange ReceiveResponse(Response response) _exchangesByID.Remove(keyId); } - if (response.Type == MessageType.ACK && exchange.CurrentRequest.ID != response.ID) - { - // The token matches but not the MID. This is a response for an older exchange - if (Log.IsEnabled(LogLevel.Warning)) - Log.LogWarning("Possible MID reuse before lifetime end: " + response.TokenString + " expected MID " + exchange.CurrentRequest.ID + " but received " + response.ID); - } - return exchange; } else @@ -339,7 +330,7 @@ public Exchange ReceiveResponse(Response response) { // only act upon separate responses Exchange prev = _deduplicator.Find(keyId); - if (prev != null) + if (prev != null && IsResponseMatch(response, prev)) { if (Log.IsEnabled(LogLevel.Information)) Log.LogInformation("Duplicate response for completed exchange: " + response); @@ -365,6 +356,12 @@ public Exchange ReceiveEmptyMessage(EmptyMessage message) Exchange exchange; if (_exchangesByID.TryGetValue(keyID, out exchange)) { + System.Net.EndPoint destination = exchange.Origin == Origin.Local + ? exchange.CurrentRequest.Destination + : exchange.CurrentResponse.Destination; + if (!Object.Equals(destination, message.Source)) + return null; + if (Log.IsEnabled(LogLevel.Debug)) Log.LogDebug("Exchange got reply: Cleaning up " + keyID); _exchangesByID.Remove(keyID); @@ -412,7 +409,9 @@ private void OnExchangeCompleted(Object sender, EventArgs e) { // this endpoint created the Exchange by issuing a request Exchange.KeyID keyID = new Exchange.KeyID(exchange.CurrentRequest.ID, null); - Exchange.KeyToken keyToken = new Exchange.KeyToken(exchange.CurrentRequest.Token); + Exchange.KeyToken keyToken = new TokenKey( + exchange.CurrentRequest.Token, + exchange.CurrentRequest.Multicast ? null : exchange.CurrentRequest.Destination); if (Log.IsEnabled(LogLevel.Debug)) Log.LogDebug("Exchange completed: Cleaning up " + keyToken); @@ -453,5 +452,90 @@ private void OnExchangeCompleted(Object sender, EventArgs e) } } } + + private Boolean TryGetResponseExchange(Response response, out Exchange exchange) + { + exchange = null; + + if (response.Token == null) + return false; + + // A unicast response must come from the endpoint addressed by the + // request. The endpoint is part of the token key so that equal + // tokens used by different peers cannot cross-match. + if (response.Source != null && + _exchangesByToken.TryGetValue(new TokenKey(response.Token, response.Source), out exchange)) + { + if (IsResponseMatch(response, exchange)) + return true; + + exchange = null; + return false; + } + + // Multicast requests intentionally accept responses from multiple + // source endpoints. They are stored under a null endpoint key and + // still require the request/response token (and ACK MID, if any). + if (_exchangesByToken.TryGetValue(new TokenKey(response.Token, null), out exchange) && + exchange.CurrentRequest != null && exchange.CurrentRequest.Multicast && + IsResponseMatch(response, exchange)) + { + return true; + } + + exchange = null; + return false; + } + + private static Boolean IsResponseMatch(Response response, Exchange exchange) + { + Request request = exchange.CurrentRequest; + if (request == null || exchange.Origin != Origin.Local || + !ByteArrayUtils.Equals(request.Token, response.Token)) + return false; + + if (!request.Multicast && !Object.Equals(request.Destination, response.Source)) + return false; + + // Piggybacked responses are matched by both the request MID and + // token. Separate CON/NON responses use the token and endpoint; + // their MID is a new server-side message identifier. + return response.Type != MessageType.ACK || response.ID == request.ID; + } + + private sealed class TokenKey : Exchange.KeyToken + { + private readonly Byte[] _token; + private readonly System.Net.EndPoint _endpoint; + private readonly Int32 _hash; + + public TokenKey(Byte[] token, System.Net.EndPoint endpoint) + : base(token) + { + if (token == null) + throw new ArgumentNullException("token"); + + _token = token; + _endpoint = endpoint; + unchecked + { + _hash = ByteArrayUtils.ComputeHash(token) * 31 + + (endpoint == null ? 0 : endpoint.GetHashCode()); + } + } + + public override Int32 GetHashCode() + { + return _hash; + } + + public override Boolean Equals(Object obj) + { + TokenKey other = obj as TokenKey; + return other != null && + Object.Equals(_endpoint, other._endpoint) && + ByteArrayUtils.Equals(_token, other._token); + } + } } } diff --git a/CoAP.Test/MatcherProtocolTest.cs b/CoAP.Test/MatcherProtocolTest.cs new file mode 100644 index 0000000..16ddfd6 --- /dev/null +++ b/CoAP.Test/MatcherProtocolTest.cs @@ -0,0 +1,273 @@ +using System; +using System.Net; +using System.Reflection; +using NUnit.Framework; + +using CoAP.Net; + +namespace CoAP +{ + [TestFixture] + public sealed class MatcherProtocolTest + { + private static readonly IPEndPoint LocalEndpoint = + new IPEndPoint(IPAddress.Loopback, 51000); + private static readonly IPEndPoint RemoteEndpoint = + new IPEndPoint(IPAddress.Loopback, 5683); + private static readonly IPEndPoint OtherRemoteEndpoint = + new IPEndPoint(IPAddress.Loopback, 5684); + + [Test] + public void SeparateResponseFromDifferentEndpointDoesNotMatchToken() + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1201, false, RemoteEndpoint); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + Response response = CreateResponse(request, MessageType.NON, 0x2201, OtherRemoteEndpoint); + + Assert.That(ReceiveResponse(matcher, response), Is.Null); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [Test] + public void PiggybackedResponseRequiresRequestMessageId() + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1202, false, RemoteEndpoint); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + Response response = CreateResponse(request, MessageType.ACK, 0x2202, RemoteEndpoint); + + Assert.That(ReceiveResponse(matcher, response), Is.Null); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [Test] + public void SeparateResponseFromRequestEndpointMatchesToken() + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1203, false, RemoteEndpoint); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + Response response = CreateResponse(request, MessageType.NON, 0x2203, RemoteEndpoint); + + Assert.That(ReceiveResponse(matcher, response), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [Test] + public void MulticastResponseMayComeFromDifferentEndpoint() + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest( + 0x1204, + true, + new IPEndPoint(IPAddress.Parse("239.255.0.1"), 5683)); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + Response response = CreateResponse(request, MessageType.NON, 0x2204, OtherRemoteEndpoint); + + Assert.That(ReceiveResponse(matcher, response), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [Test] + public void EqualTokensForDifferentPeersRemainIndependent() + { + object matcher = CreateMatcher(); + try + { + Request first = CreateRequest(0x1205, false, RemoteEndpoint); + Request second = CreateRequest(0x1206, false, OtherRemoteEndpoint); + Exchange firstExchange = new Exchange(first, Origin.Local); + Exchange secondExchange = new Exchange(second, Origin.Local); + Invoke(matcher, "SendRequest", firstExchange, first); + Invoke(matcher, "SendRequest", secondExchange, second); + + Assert.That(ReceiveResponse(matcher, + CreateResponse(first, MessageType.NON, 0x2205, RemoteEndpoint)), + Is.SameAs(firstExchange)); + firstExchange.Complete = true; + + Assert.That(ReceiveResponse(matcher, + CreateResponse(second, MessageType.NON, 0x2206, OtherRemoteEndpoint)), + Is.SameAs(secondExchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [Test] + public void EqualTokenHashesDoNotMatchDifferentTokenBytes() + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1207, false, RemoteEndpoint); + request.Token = new Byte[] { 0x5c, 0x09, 0x00, 0x00, 0x00 }; + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + Response response = CreateResponse(request, MessageType.NON, 0x2207, RemoteEndpoint); + response.Token = new Byte[] { 0x3f, 0xbc, 0x00, 0x00, 0x00 }; + + Assert.That(CoAP.Util.ByteArrayUtils.ComputeHash(request.Token), + Is.EqualTo(CoAP.Util.ByteArrayUtils.ComputeHash(response.Token))); + Assert.That(ReceiveResponse(matcher, response), Is.Null); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [TestCase(MessageType.ACK)] + [TestCase(MessageType.RST)] + public void EmptyMessageFromWrongEndpointDoesNotConsumePendingMessage(MessageType type) + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1208, false, RemoteEndpoint); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + EmptyMessage wrong = new EmptyMessage(type); + wrong.ID = request.ID; + wrong.Source = OtherRemoteEndpoint; + Assert.That(Invoke(matcher, "ReceiveEmptyMessage", wrong), Is.Null); + + EmptyMessage correct = new EmptyMessage(type); + correct.ID = request.ID; + correct.Source = RemoteEndpoint; + Assert.That(Invoke(matcher, "ReceiveEmptyMessage", correct), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [Test] + public void EmptyAcknowledgementMatchesSentResponseDestination() + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1209, false, RemoteEndpoint); + request.Source = RemoteEndpoint; + Exchange exchange = new Exchange(request, Origin.Remote); + Response response = CreateResponse(request, MessageType.CON, 0x2209, LocalEndpoint); + response.Destination = RemoteEndpoint; + exchange.CurrentResponse = response; + Invoke(matcher, "SendResponse", exchange, response); + + EmptyMessage wrong = new EmptyMessage(MessageType.ACK); + wrong.ID = response.ID; + wrong.Source = OtherRemoteEndpoint; + Assert.That(Invoke(matcher, "ReceiveEmptyMessage", wrong), Is.Null); + + EmptyMessage correct = new EmptyMessage(MessageType.ACK); + correct.ID = response.ID; + correct.Source = RemoteEndpoint; + Assert.That(Invoke(matcher, "ReceiveEmptyMessage", correct), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [Test] + public void DuplicateMessageIdWithDifferentTokenDoesNotMatchEarlierResponse() + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1210, false, RemoteEndpoint); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + Response response = CreateResponse(request, MessageType.NON, 0x2210, RemoteEndpoint); + Assert.That(ReceiveResponse(matcher, response), Is.SameAs(exchange)); + + Response unexpected = CreateResponse(request, MessageType.NON, response.ID, RemoteEndpoint); + unexpected.Token = new Byte[] { 0x07, 0x08, 0x09, 0x0a }; + + Assert.That(ReceiveResponse(matcher, unexpected), Is.Null); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + private static object CreateMatcher() + { + Type matcherType = typeof(CoapClient).Assembly.GetType("CoAP.Net.Matcher", true); + return Activator.CreateInstance(matcherType, new CoapConfig()); + } + + private static Request CreateRequest(Int32 id, Boolean multicast, System.Net.EndPoint destination) + { + Request request = Request.NewGet(); + request.ID = id; + request.Token = new Byte[] { 0x01, 0x02, 0x03, 0x04 }; + request.Source = LocalEndpoint; + request.Destination = destination; + request.Multicast = multicast; + return request; + } + + private static Response CreateResponse(Request request, MessageType type, Int32 id, System.Net.EndPoint source) + { + Response response = Response.CreateResponse(request, StatusCode.Content); + response.Type = type; + response.ID = id; + response.Source = source; + response.Destination = LocalEndpoint; + return response; + } + + private static Exchange ReceiveResponse(object matcher, Response response) + { + return (Exchange)Invoke(matcher, "ReceiveResponse", response); + } + + private static object Invoke(object target, String methodName, params object[] arguments) + { + return target.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public) + .Invoke(target, arguments); + } + } +} From d299b483401d93b14df2869320cb16e5976f18c7 Mon Sep 17 00:00:00 2001 From: maikebing Date: Fri, 13 Nov 2026 00:58:04 +0800 Subject: [PATCH 2/7] fix(blockwise): validate Block1 responses before advancing uploads --- CoAP.NET/Stack/BlockwiseLayer.cs | 62 ++- CoAP.Test/BlockwiseProtocolRegressionTest.cs | 383 +++++++++++++++++++ 2 files changed, 427 insertions(+), 18 deletions(-) create mode 100644 CoAP.Test/BlockwiseProtocolRegressionTest.cs diff --git a/CoAP.NET/Stack/BlockwiseLayer.cs b/CoAP.NET/Stack/BlockwiseLayer.cs index 0df2c5c..d507fcd 100644 --- a/CoAP.NET/Stack/BlockwiseLayer.cs +++ b/CoAP.NET/Stack/BlockwiseLayer.cs @@ -118,7 +118,7 @@ public override void ReceiveRequest(INextLayer nextLayer, Exchange exchange, Req Response error = Response.CreateResponse(request, StatusCode.RequestEntityIncomplete); error.AddOption(new BlockOption(OptionType.Block1, block1.NUM, block1.SZX, block1.M)); error.SetPayload("Changed Content-Format"); - + exchange.CurrentResponse = error; base.SendResponse(nextLayer, exchange, error); return; @@ -226,7 +226,7 @@ public override void SendResponse(INextLayer nextLayer, Exchange exchange, Respo BlockwiseStatus status = FindResponseBlockStatus(exchange, response); Response block = GetNextResponseBlock(response, status); - + if (block1 != null) // in case we still have to ack the last block1 block.SetOption(block1); if (block.Token == null) @@ -289,21 +289,58 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re BlockOption block1 = response.Block1; if (block1 != null) { - // TODO: What if request has not been sent blockwise (server error) if (Log.IsEnabled(LogLevel.Debug)) Log.LogDebug("Response acknowledges block " + block1); BlockwiseStatus status = exchange.RequestBlockStatus; - if (!status.Complete) + if (status != null && block1.SZX == 7) + { + // SZX 7 is reserved for the UDP blockwise protocol. Ignore + // this invalid acknowledgement without advancing upload. + if (Log.IsEnabled(LogLevel.Warning)) + Log.LogWarning("Ignoring Block1 response with reserved SZX 7."); + return; + } + + // Match the acknowledgement even when the final request block + // has been sent: an earlier Continue must not finish that upload. + if (status != null && Code.IsSuccess(response.Code) + && block1.NUM != status.CurrentNUM) + { + if (Log.IsEnabled(LogLevel.Warning)) + Log.LogWarning("Ignoring Block1 response for block " + block1.NUM + + "; expected " + status.CurrentNUM + "."); + return; + } + + // RFC 7959 sections 2.3 and 2.5: atomic uploads use 2.31 + // Continue; a server acting on individual blocks may instead + // return another success code with its Block1 M bit cleared. + if (status == null || status.Complete || !Code.IsSuccess(response.Code) + || (response.StatusCode != StatusCode.Continue && block1.M)) + { + exchange.RequestBlockStatus = null; + ClearBlockCleanup(exchange); + if (!response.HasOption(OptionType.Block2)) + { + exchange.Response = response; + base.ReceiveResponse(nextLayer, exchange, response); + return; + } + // A final response can combine a Block1 acknowledgement + // with a Block2 response body. Continue reassembly below. + } + else { - // TODO: the response code should be CONTINUE. Otherwise deliver // Send next block Int32 currentSize = 1 << (4 + status.CurrentSZX); - Int32 nextNum = status.CurrentNUM + currentSize / block1.Size; + Int32 nextSZX = Math.Min(status.CurrentSZX, block1.SZX); + Int32 nextSize = 1 << (4 + nextSZX); + Int32 nextNum = (status.CurrentNUM + 1) * currentSize / nextSize; if (Log.IsEnabled(LogLevel.Debug)) Log.LogDebug("Send next block num = " + nextNum); status.CurrentNUM = nextNum; - status.CurrentSZX = block1.SZX; + status.CurrentSZX = nextSZX; Request nextBlock = GetNextRequestBlock(exchange.Request, status); if (nextBlock.Token == null) nextBlock.Token = response.Token; // reuse same token @@ -311,17 +348,6 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re base.SendRequest(nextLayer, exchange, nextBlock); // do not deliver response } - else if (!response.HasOption(OptionType.Block2)) - { - // All request block have been acknowledged and we receive a piggy-backed - // response that needs no blockwise transfer. Thus, deliver it. - base.ReceiveResponse(nextLayer, exchange, response); - } - else - { - if (Log.IsEnabled(LogLevel.Debug)) - Log.LogDebug("Response has Block2 option and is therefore sent blockwise"); - } } BlockOption block2 = response.Block2; diff --git a/CoAP.Test/BlockwiseProtocolRegressionTest.cs b/CoAP.Test/BlockwiseProtocolRegressionTest.cs new file mode 100644 index 0000000..b6a62ce --- /dev/null +++ b/CoAP.Test/BlockwiseProtocolRegressionTest.cs @@ -0,0 +1,383 @@ +using System; +using NUnit.Framework; +using CoAP.Net; +using CoAP.Stack; + +namespace CoAP +{ + [TestFixture] + public sealed class BlockwiseProtocolRegressionTest + { + [Test] + public void Block1ResponseWithoutRequestStatus_IsForwarded() + { + Request request = Request.NewPost(); + Exchange exchange = new Exchange(request, Origin.Local) + { + Request = request + }; + Response response = Response.CreateResponse(request, StatusCode.Continue); + response.AddOption(new BlockOption(OptionType.Block1, 0, 0, true)); + RecordingLayer next = new RecordingLayer(); + + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig()); + + Assert.DoesNotThrow(() => layer.ReceiveResponse(next, exchange, response)); + Assert.That(next.ReceivedResponses, Is.EqualTo(1)); + Assert.That(next.SentRequests, Is.EqualTo(0)); + } + + [TestCase(StatusCode.BadRequest)] + [TestCase(StatusCode.RequestEntityIncomplete)] + [TestCase(StatusCode.RequestEntityTooLarge)] + [TestCase(StatusCode.InternalServerError)] + public void Block1ErrorResponse_DoesNotContinueUpload(StatusCode statusCode) + { + Request request = Request.NewPost(); + request.SetPayload(new byte[32], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) + { + Request = request + }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + + layer.SendRequest(next, exchange, request); + Assert.That(next.SentRequests, Is.EqualTo(1)); + + Response response = Response.CreateResponse(request, statusCode); + response.AddOption(new BlockOption(OptionType.Block1, 0, 0, true)); + + layer.ReceiveResponse(next, exchange, response); + + Assert.That(next.SentRequests, Is.EqualTo(1)); + Assert.That(next.ReceivedResponses, Is.EqualTo(1)); + Assert.That(next.LastResponse, Is.SameAs(response)); + Assert.That(exchange.RequestBlockStatus, Is.Null); + } + + [Test] + public void DuplicateOrOutOfOrderBlock1Response_DoesNotAdvanceUpload() + { + Request request = Request.NewPost(); + request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) + { + Request = request + }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + + layer.SendRequest(next, exchange, request); + BlockwiseStatus status = exchange.RequestBlockStatus; + Assert.That(status, Is.Not.Null); + Assert.That(status.CurrentNUM, Is.EqualTo(0)); + + Response duplicate = Response.CreateResponse(request, StatusCode.Continue); + duplicate.AddOption(new BlockOption(OptionType.Block1, 1, 0, true)); + layer.ReceiveResponse(next, exchange, duplicate); + + Assert.That(next.SentRequests, Is.EqualTo(1)); + Assert.That(status.CurrentNUM, Is.EqualTo(0)); + + Response outOfOrder = Response.CreateResponse(request, StatusCode.Continue); + outOfOrder.AddOption(new BlockOption(OptionType.Block1, 2, 0, true)); + layer.ReceiveResponse(next, exchange, outOfOrder); + + Assert.That(next.SentRequests, Is.EqualTo(1)); + Assert.That(status.CurrentNUM, Is.EqualTo(0)); + } + + [Test] + public void ContinueForCurrentBlock_SendsOnlyNextBlock() + { + Request request = Request.NewPost(); + request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) + { + Request = request + }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + + layer.SendRequest(next, exchange, request); + Response response = Response.CreateResponse(request, StatusCode.Continue); + response.AddOption(new BlockOption(OptionType.Block1, 0, 0, true)); + + layer.ReceiveResponse(next, exchange, response); + + Assert.That(next.SentRequests, Is.EqualTo(2)); + Assert.That(next.LastRequest, Is.Not.Null); + Assert.That(next.LastRequest.Block1.NUM, Is.EqualTo(1)); + Assert.That(exchange.RequestBlockStatus.CurrentNUM, Is.EqualTo(1)); + } + + [TestCase(StatusCode.Created)] + [TestCase(StatusCode.Changed)] + public void PerBlockSuccessWithMoreBitCleared_ContinuesUpload(StatusCode statusCode) + { + Request request = Request.NewPost(); + request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + layer.SendRequest(next, exchange, request); + Response response = Response.CreateResponse(request, statusCode); + response.AddOption(new BlockOption(OptionType.Block1, 0, 0, false)); + + layer.ReceiveResponse(next, exchange, response); + + Assert.That(next.SentRequests, Is.EqualTo(2)); + Assert.That(next.LastRequest.Block1.NUM, Is.EqualTo(1)); + Assert.That(next.ReceivedResponses, Is.EqualTo(0)); + } + + [TestCase(StatusCode.Created)] + [TestCase(StatusCode.Changed)] + public void AtomicSuccessWithoutContinue_DoesNotContinueUpload(StatusCode statusCode) + { + Request request = Request.NewPost(); + request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + layer.SendRequest(next, exchange, request); + Response response = Response.CreateResponse(request, statusCode); + response.AddOption(new BlockOption(OptionType.Block1, 0, 0, true)); + + layer.ReceiveResponse(next, exchange, response); + + Assert.That(next.SentRequests, Is.EqualTo(1)); + Assert.That(next.ReceivedResponses, Is.EqualTo(1)); + Assert.That(next.LastResponse, Is.SameAs(response)); + Assert.That(exchange.RequestBlockStatus, Is.Null); + } + + [Test] + public void ContinueWithReservedBlockSize_DoesNotAdvanceUpload() + { + Request request = Request.NewPost(); + request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + layer.SendRequest(next, exchange, request); + Response response = Response.CreateResponse(request, StatusCode.Continue); + response.AddOption(new BlockOption(OptionType.Block1, 0, 7, true)); + + layer.ReceiveResponse(next, exchange, response); + + Assert.That(next.SentRequests, Is.EqualTo(1)); + Assert.That(exchange.RequestBlockStatus.CurrentNUM, Is.EqualTo(0)); + Assert.That(next.ReceivedResponses, Is.EqualTo(0)); + } + + [Test] + public void DuplicateBlock1Response_DoesNotSkipTheOutstandingBlock() + { + Request request = Request.NewPost(); + request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + layer.SendRequest(next, exchange, request); + Response first = Response.CreateResponse(request, StatusCode.Continue); + first.AddOption(new BlockOption(OptionType.Block1, 0, 0, true)); + layer.ReceiveResponse(next, exchange, first); + + layer.ReceiveResponse(next, exchange, first); + + Assert.That(next.SentRequests, Is.EqualTo(2)); + Assert.That(exchange.RequestBlockStatus.CurrentNUM, Is.EqualTo(1)); + Assert.That(next.LastRequest.Block1.NUM, Is.EqualTo(1)); + } + + [Test] + public void DuplicateContinueWhileFinalBlockIsOutstanding_DoesNotFinishUpload() + { + Request request = Request.NewPost(); + request.SetPayload(new byte[32], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + layer.SendRequest(next, exchange, request); + Response first = Response.CreateResponse(request, StatusCode.Continue); + first.AddOption(new BlockOption(OptionType.Block1, 0, 0, true)); + layer.ReceiveResponse(next, exchange, first); + BlockwiseStatus status = exchange.RequestBlockStatus; + Assert.That(status.Complete, Is.True); + + layer.ReceiveResponse(next, exchange, first); + + Assert.That(next.SentRequests, Is.EqualTo(2)); + Assert.That(next.ReceivedResponses, Is.EqualTo(0)); + Assert.That(exchange.RequestBlockStatus, Is.SameAs(status)); + + Response final = Response.CreateResponse(request, StatusCode.Changed); + final.AddOption(new BlockOption(OptionType.Block1, 1, 0, false)); + layer.ReceiveResponse(next, exchange, final); + + Assert.That(next.ReceivedResponses, Is.EqualTo(1)); + Assert.That(next.LastResponse, Is.SameAs(final)); + Assert.That(exchange.RequestBlockStatus, Is.Null); + } + + [Test] + public void ContinueWithSmallerBlockSize_PreservesTheByteOffset() + { + Request request = Request.NewPost(); + byte[] payload = new byte[96]; + for (int i = 0; i < payload.Length; i++) + payload[i] = (byte)i; + request.SetPayload(payload, MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 32, + DefaultBlockSize = 32 + }); + layer.SendRequest(next, exchange, request); + Response first = Response.CreateResponse(request, StatusCode.Continue); + first.AddOption(new BlockOption(OptionType.Block1, 0, 1, true)); + layer.ReceiveResponse(next, exchange, first); + + Response smaller = Response.CreateResponse(request, StatusCode.Continue); + smaller.AddOption(new BlockOption(OptionType.Block1, 1, 0, true)); + layer.ReceiveResponse(next, exchange, smaller); + + Assert.That(next.SentRequests, Is.EqualTo(3)); + Assert.That(next.LastRequest.Block1.NUM, Is.EqualTo(4)); + Assert.That(next.LastRequest.Payload, Is.EqualTo(new byte[] + { + 64, 65, 66, 67, 68, 69, 70, 71, + 72, 73, 74, 75, 76, 77, 78, 79 + })); + } + + [Test] + public void FinalBlock1ResponseWithBlock2_AssemblesTheResponseBody() + { + Request request = Request.NewPost(); + Exchange exchange = new Exchange(request, Origin.Local) + { + Request = request, + RequestBlockStatus = new BlockwiseStatus(MediaType.ApplicationOctetStream, 1, 0) + { + Complete = true + } + }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig()); + Response first = Response.CreateResponse(request, StatusCode.Changed); + first.SetPayload("0123456789abcdef", MediaType.TextPlain); + first.AddOption(new BlockOption(OptionType.Block1, 1, 0, false)); + first.AddOption(new BlockOption(OptionType.Block2, 0, 0, true)); + + layer.ReceiveResponse(next, exchange, first); + + Assert.That(next.ReceivedResponses, Is.EqualTo(0)); + Assert.That(next.SentRequests, Is.EqualTo(1)); + Assert.That(next.LastRequest.Block2.NUM, Is.EqualTo(1)); + + Response last = Response.CreateResponse(request, StatusCode.Changed); + last.SetPayload("ghijkl", MediaType.TextPlain); + last.AddOption(new BlockOption(OptionType.Block2, 1, 0, false)); + layer.ReceiveResponse(next, exchange, last); + + Assert.That(next.ReceivedResponses, Is.EqualTo(1)); + Assert.That(next.LastResponse.PayloadString, Is.EqualTo("0123456789abcdefghijkl")); + } + + [Test] + public void ContinueWithLargerBlockPreference_DoesNotResendPreviousBytes() + { + Request request = Request.NewPost(); + request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + layer.SendRequest(next, exchange, request); + + Response response = Response.CreateResponse(request, StatusCode.Continue); + response.AddOption(new BlockOption(OptionType.Block1, 0, 1, true)); + layer.ReceiveResponse(next, exchange, response); + + Assert.That(next.SentRequests, Is.EqualTo(2)); + Assert.That(next.LastRequest.Block1.NUM, Is.EqualTo(1)); + Assert.That(next.LastRequest.Block1.Size, Is.EqualTo(16)); + } + + private sealed class RecordingLayer : INextLayer + { + public int SentRequests { get; private set; } + public int ReceivedResponses { get; private set; } + public Request LastRequest { get; private set; } + public Response LastResponse { get; private set; } + + public void SendRequest(Exchange exchange, Request request) + { + SentRequests++; + LastRequest = request; + } + + public void SendResponse(Exchange exchange, Response response) + { + } + + public void SendEmptyMessage(Exchange exchange, EmptyMessage message) + { + } + + public void ReceiveRequest(Exchange exchange, Request request) + { + } + + public void ReceiveResponse(Exchange exchange, Response response) + { + ReceivedResponses++; + LastResponse = response; + } + + public void ReceiveEmptyMessage(Exchange exchange, EmptyMessage message) + { + } + } + } +} From 4138aef8183eba9c118038da9b7e7b8ee8ad212f Mon Sep 17 00:00:00 2001 From: maikebing Date: Fri, 13 Nov 2026 01:02:11 +0800 Subject: [PATCH 3/7] fix(codec): reject malformed RFC 7252 datagrams --- CoAP.NET/Codec/DatagramReader.cs | 23 ++- CoAP.NET/Net/CoAPEndPoint.cs | 102 +++++++--- CoAP.NET/Spec.cs | 42 +++- CoAP.Test/MalformedDatagramTest.cs | 296 +++++++++++++++++++++++++++++ 4 files changed, 436 insertions(+), 27 deletions(-) create mode 100644 CoAP.Test/MalformedDatagramTest.cs diff --git a/CoAP.NET/Codec/DatagramReader.cs b/CoAP.NET/Codec/DatagramReader.cs index 6b33583..7c897dd 100644 --- a/CoAP.NET/Codec/DatagramReader.cs +++ b/CoAP.NET/Codec/DatagramReader.cs @@ -41,6 +41,12 @@ public DatagramReader(Byte[] buffer) /// An integer containing the bits read public Int32 Read(Int32 numBits) { + if (numBits < 0 || numBits > 32) + throw new ArgumentOutOfRangeException("numBits", "The number of bits must be between 0 and 32."); + + if ((long)numBits > RemainingBits) + throw new EndOfStreamException("The datagram ended before the requested bits were available."); + Int32 bits = 0; // initialize all bits to zero for (Int32 i = numBits - 1; i >= 0; i--) { @@ -75,6 +81,9 @@ public Byte[] ReadBytes(Int32 count) if (count < 0) count = (Int32)(_stream.Length - _stream.Position); + if (count > 0 && (long)count * 8L > RemainingBits) + throw new EndOfStreamException("The datagram ended before the requested bytes were available."); + Byte[] bytes = new Byte[count]; // are there bits left to read in buffer? @@ -125,11 +134,21 @@ private void ReadCurrentByte() if (val >= 0) _currentByte = (Byte)val; else - // EOF - _currentByte = 0; + throw new EndOfStreamException("The datagram ended while reading a byte."); // reset current bit index _currentBitIndex = 7; } + + private long RemainingBits + { + get + { + long remaining = (_stream.Length - _stream.Position) * 8L; + if (_currentBitIndex >= 0) + remaining += _currentBitIndex + 1L; + return remaining; + } + } } } diff --git a/CoAP.NET/Net/CoAPEndPoint.cs b/CoAP.NET/Net/CoAPEndPoint.cs index cf235b0..4ada59d 100644 --- a/CoAP.NET/Net/CoAPEndPoint.cs +++ b/CoAP.NET/Net/CoAPEndPoint.cs @@ -10,6 +10,7 @@ */ using System; +using System.IO; using CoAP.Channel; using CoAP.Codec; using Microsoft.Extensions.Logging; @@ -232,7 +233,28 @@ private void ReceiveData(Object sender, DataReceivedEventArgs e) private void ReceiveData(DataReceivedEventArgs e) { - IMessageDecoder decoder = Spec.NewMessageDecoder(e.Data); + IMessageDecoder decoder; + try + { + decoder = Spec.NewMessageDecoder(e.Data); + } + catch (Exception ex) when (IsMessageFormatException(ex)) + { + // A datagram without a complete fixed header does not provide + // enough information to construct a safe reply. Drop it. + if (Log.IsEnabled(LogLevel.Warning)) + Log.LogWarning("Ignoring malformed CoAP datagram from " + e.EndPoint); + return; + } + + if (!decoder.IsWellFormed) + { + if (Log.IsEnabled(LogLevel.Warning)) + Log.LogWarning("Ignoring malformed CoAP header from " + e.EndPoint); + HandleMalformedDatagram(decoder, e); + return; + } + if (decoder.IsRequest) { Request request; @@ -240,27 +262,9 @@ private void ReceiveData(DataReceivedEventArgs e) { request = decoder.DecodeRequest(); } - catch (Exception) + catch (Exception ex) when (IsMessageFormatException(ex)) { - if (decoder.IsReply) - { - if (Log.IsEnabled(LogLevel.Warning)) - Log.LogWarning("Message format error caused by " + e.EndPoint); - } - else - { - // manually build RST from raw information - EmptyMessage rst = new EmptyMessage(MessageType.RST); - rst.Destination = e.EndPoint; - rst.ID = decoder.ID; - - Fire(SendingEmptyMessage, rst); - - _channel.Send(Serialize(rst), rst.Destination); - - if (Log.IsEnabled(LogLevel.Warning)) - Log.LogWarning("Message format error caused by " + e.EndPoint + " and reseted."); - } + HandleMalformedDatagram(decoder, e); return; } @@ -280,7 +284,18 @@ private void ReceiveData(DataReceivedEventArgs e) } else if (decoder.IsResponse) { - Response response = decoder.DecodeResponse(); + Response response; + try + { + response = decoder.DecodeResponse(); + } + catch (Exception ex) when (IsMessageFormatException(ex)) + { + // Reject a malformed CON with RST, while ACK/RST and NON + // are silently discarded without reaching the matcher. + HandleMalformedDatagram(decoder, e); + return; + } response.Source = e.EndPoint; Fire(ReceivingResponse, response); @@ -304,7 +319,18 @@ private void ReceiveData(DataReceivedEventArgs e) } else if (decoder.IsEmpty) { - EmptyMessage message = decoder.DecodeEmptyMessage(); + EmptyMessage message; + try + { + message = decoder.DecodeEmptyMessage(); + } + catch (Exception ex) when (IsMessageFormatException(ex)) + { + // Empty messages must contain no token, options, or + // payload. Apply the same message-format error handling. + HandleMalformedDatagram(decoder, e); + return; + } message.Source = e.EndPoint; Fire(ReceivingEmptyMessage, message); @@ -335,6 +361,36 @@ private void ReceiveData(DataReceivedEventArgs e) } } + private void HandleMalformedDatagram(IMessageDecoder decoder, DataReceivedEventArgs e) + { + if (Log.IsEnabled(LogLevel.Warning)) + Log.LogWarning("Message format error caused by " + e.EndPoint); + + // RFC 7252 section 4.2 requires a reset for a malformed + // Confirmable message when its version, type, and message ID are + // known. Never reflect a reset to NON, ACK, RST, or an invalid + // fixed header. + if (e.Data == null || e.Data.Length < 4 || decoder.Version != 1 || + ((e.Data[0] >> 4) & 0x03) != (Int32)MessageType.CON) + return; + + EmptyMessage rst = new EmptyMessage(MessageType.RST) + { + Destination = e.EndPoint, + ID = decoder.ID + }; + + Fire(SendingEmptyMessage, rst); + if (!rst.IsCancelled) + _channel.Send(Serialize(rst), rst.Destination); + } + + private static Boolean IsMessageFormatException(Exception exception) + { + return exception is ArgumentException || exception is FormatException || + exception is InvalidOperationException || exception is EndOfStreamException; + } + private void Reject(Message message) { EmptyMessage rst = EmptyMessage.NewRST(message); diff --git a/CoAP.NET/Spec.cs b/CoAP.NET/Spec.cs index f696506..1ce498e 100644 --- a/CoAP.NET/Spec.cs +++ b/CoAP.NET/Spec.cs @@ -15,6 +15,7 @@ using System; using System.Collections.Generic; +using System.IO; using CoAP.Codec; using Microsoft.Extensions.Logging; using CoAP.Util; @@ -1654,15 +1655,35 @@ protected override void Serialize(DatagramWriter writer, Message msg, Int32 code class MessageDecoder18 : MessageDecoder { + private Boolean _headerComplete; + public MessageDecoder18(Byte[] data) : base(data) { - ReadProtocol(); + try + { + ReadProtocol(); + _headerComplete = true; + } + catch (EndOfStreamException) + { + // A truncated fixed header is not a decodable message. Keep + // the decoder object available so the endpoint can silently + // discard it without reflecting an RST to an unknown peer. + _headerComplete = false; + } } public override Boolean IsWellFormed { - get { return m_version == Version; } + // MessageDecoder.Version is an inherited property, so an + // unqualified Version here would compare m_version to itself. + get + { + Int32 codeClass = m_code >> 5; + return _headerComplete && m_version == 1 && m_tokenLength <= 8 && + (codeClass == 0 || codeClass == 2 || codeClass == 4 || codeClass == 5); + } } protected override void ReadProtocol() @@ -1677,6 +1698,23 @@ protected override void ReadProtocol() protected override void ParseMessage(Message msg) { + if (!IsWellFormed) + throw new FormatException("The CoAP message header is malformed."); + + if (m_type == MessageType.RST && m_code != Code.Empty || + m_type == MessageType.ACK && IsRequest) + throw new FormatException("The CoAP message type does not allow its code."); + + if (m_code == Code.Empty) + { + if (m_type == MessageType.NON) + throw new FormatException("A non-confirmable CoAP message must contain a request or response."); + if (m_tokenLength != 0 || m_reader.BytesAvailable) + throw new FormatException("An empty CoAP message must not contain a token, options, or payload."); + msg.Token = CoapConstants.EmptyToken; + return; + } + // read token if (m_tokenLength > 0) msg.Token = m_reader.ReadBytes(m_tokenLength); diff --git a/CoAP.Test/MalformedDatagramTest.cs b/CoAP.Test/MalformedDatagramTest.cs new file mode 100644 index 0000000..6b24e40 --- /dev/null +++ b/CoAP.Test/MalformedDatagramTest.cs @@ -0,0 +1,296 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using CoAP.Channel; +using CoAP.Codec; +using CoAP.Net; +using CoAP.Threading; +using NUnit.Framework; +using NetworkEndPoint = System.Net.EndPoint; + +namespace CoAP.Protocol +{ + [TestFixture] + public sealed class MalformedDatagramTest + { + private static readonly IPEndPoint Remote = new IPEndPoint(IPAddress.Loopback, 56830); + + [TestCase("")] + [TestCase("40")] + [TestCase("4001")] + [TestCase("400100")] + [TestCase("41010001")] + [TestCase("42010001aa")] + [TestCase("48010001aabbcc")] + [TestCase("49010001")] + [TestCase("4f010001")] + [TestCase("00010001")] + [TestCase("80010001")] + [TestCase("c0010001")] + [TestCase("40010001d0")] + [TestCase("40010001e000")] + [TestCase("40010001bd")] + [TestCase("40010001be00")] + [TestCase("4001000111")] + [TestCase("40010001f0")] + [TestCase("400100010f")] + [TestCase("40010001ff")] + [TestCase("6000000100")] + [TestCase("61000001aa")] + [TestCase("60000001ffaa")] + [TestCase("50000001")] + [TestCase("70010001")] + [TestCase("60010001")] + [TestCase("70450001")] + public void MalformedWireMessagesCannotDecode(String hex) + { + Assert.That(() => Spec.Decode(Convert.FromHexString(hex)), Throws.Exception); + } + + [Test] + public void EightByteTokenAndZeroLengthOptionDecodeWithoutPadding() + { + Request request = (Request)Spec.Decode(Convert.FromHexString("48010001000102030405060700")); + + Assert.That(request.Token, Is.EqualTo(Convert.FromHexString("0001020304050607"))); + Assert.That(request.GetFirstOption(OptionType.Reserved).RawValue, Is.Empty); + } + + [Test] + public void TruncatedFixedHeaderIsNotWellFormed() + { + IMessageDecoder decoder = Spec.NewMessageDecoder(new Byte[] { 0x40, 0x01 }); + + Assert.That(decoder.IsWellFormed, Is.False); + Assert.That(() => decoder.DecodeRequest(), Throws.Exception); + } + + [Test] + public void TokenLengthGreaterThanEightIsNotWellFormed() + { + IMessageDecoder decoder = Spec.NewMessageDecoder(new Byte[] { 0x49, 0x01, 0x00, 0x01 }); + + Assert.That(decoder.IsWellFormed, Is.False); + Assert.That(() => decoder.DecodeRequest(), Throws.Exception); + } + + [Test] + public void TruncatedOptionValueIsRejected() + { + // GET / with option delta 1 and length 1, but no value byte. + IMessageDecoder decoder = Spec.NewMessageDecoder(new Byte[] + { + 0x40, 0x01, 0x00, 0x01, 0x11 + }); + + Assert.That(decoder.IsWellFormed, Is.True); + Assert.That(() => decoder.DecodeRequest(), Throws.Exception); + } + + [Test] + public void TrailingPayloadMarkerIsRejected() + { + IMessageDecoder decoder = Spec.NewMessageDecoder(new Byte[] + { + 0x40, 0x01, 0x00, 0x01, 0xff + }); + + Assert.That(decoder.IsWellFormed, Is.True); + Assert.That(() => decoder.DecodeRequest(), Throws.Exception); + } + + [Test] + public void InvalidVersionIsNotWellFormed() + { + IMessageDecoder decoder = Spec.NewMessageDecoder(new Byte[] { 0x00, 0x01, 0x00, 0x01 }); + + Assert.That(decoder.IsWellFormed, Is.False); + } + + [Test] + public void EmptyMessageWithPayloadIsRejectedButValidEmptyMessageDecodes() + { + IMessageDecoder malformed = Spec.NewMessageDecoder(new Byte[] + { + 0x60, 0x00, 0x00, 0x01, 0xff, 0x01 + }); + Assert.That(malformed.IsWellFormed, Is.True); + Assert.That(() => malformed.DecodeEmptyMessage(), Throws.Exception); + + IMessageDecoder valid = Spec.NewMessageDecoder(new Byte[] { 0x60, 0x00, 0x00, 0x01 }); + Assert.That(valid.IsWellFormed, Is.True); + Assert.That(valid.DecodeEmptyMessage(), Is.Not.Null); + } + + [Test] + public void UnknownElectiveOptionIsRetained() + { + // Option number 204 is unknown to this version and elective (even). + IMessageDecoder decoder = Spec.NewMessageDecoder(new Byte[] + { + 0x40, 0x01, 0x00, 0x01, 0xd1, 0xbf, 0x7f + }); + + Request request = decoder.DecodeRequest(); + Option option = request.GetFirstOption((OptionType)204); + Assert.That(option, Is.Not.Null); + Assert.That(option.RawValue, Is.EqualTo(new Byte[] { 0x7f })); + } + + [Test] + public void MalformedConfirmableRequestGetsOneReset() + { + RecordingChannel channel = new RecordingChannel(); + using (CoAPEndPoint endpoint = new CoAPEndPoint(channel, CoapConfig.Default) + { + Executor = Executors.NoThreading + }) + { + endpoint.Start(); + channel.Emit(new Byte[] { 0x40, 0x01, 0x00, 0x2a, 0x11 }, Remote); + } + + Assert.That(channel.Sent, Has.Count.EqualTo(1)); + Assert.That(channel.Sent[0].Data, Is.EqualTo(new Byte[] { 0x70, 0x00, 0x00, 0x2a })); + Assert.That(channel.Sent[0].EndPoint, Is.EqualTo(Remote)); + } + + [TestCase("4145002a")] + [TestCase("4000002aff01")] + [TestCase("4901002a")] + [TestCase("4020002a")] + public void IdentifiableMalformedConfirmableMessageGetsMatchingReset(String hex) + { + RecordingChannel channel = new RecordingChannel(); + using (CoAPEndPoint endpoint = new CoAPEndPoint(channel, CoapConfig.Default) + { + Executor = Executors.NoThreading + }) + { + endpoint.Start(); + channel.Emit(Convert.FromHexString(hex), Remote); + } + + Assert.That(channel.Sent, Has.Count.EqualTo(1)); + Assert.That(channel.Sent[0].Data, Is.EqualTo(new Byte[] { 0x70, 0x00, 0x00, 0x2a })); + Assert.That(channel.Sent[0].EndPoint, Is.EqualTo(Remote)); + } + + [Test] + public void MalformedNonConfirmableRequestDoesNotGetReset() + { + RecordingChannel channel = new RecordingChannel(); + using (CoAPEndPoint endpoint = new CoAPEndPoint(channel, CoapConfig.Default) + { + Executor = Executors.NoThreading + }) + { + endpoint.Start(); + channel.Emit(new Byte[] { 0x50, 0x01, 0x00, 0x2a, 0x11 }, Remote); + } + + Assert.That(channel.Sent, Is.Empty); + } + + [Test] + public void ShortHeadersAndUnsupportedVersionsAreSilentlyDropped() + { + RecordingChannel channel = new RecordingChannel(); + using (CoAPEndPoint endpoint = new CoAPEndPoint(channel, CoapConfig.Default) + { + Executor = Executors.NoThreading + }) + { + endpoint.Start(); + endpoint.ReceivingRequest += (sender, e) => + { + Assert.Fail("Malformed fixed header reached the request pipeline."); + }; + channel.Emit(new Byte[] { 0x40, 0x01 }, Remote); + channel.Emit(new Byte[] { 0x00, 0x01, 0x00, 0x01 }, Remote); + channel.Emit(new Byte[] { 0x80, 0x01, 0x00, 0x01 }, Remote); + } + + Assert.That(channel.Sent, Is.Empty); + } + + [Test] + public void CancelledMalformedMessageResetIsNotSent() + { + RecordingChannel channel = new RecordingChannel(); + using (CoAPEndPoint endpoint = new CoAPEndPoint(channel, CoapConfig.Default) + { + Executor = Executors.NoThreading + }) + { + endpoint.Start(); + endpoint.SendingEmptyMessage += (sender, e) => e.Message.IsCancelled = true; + channel.Emit(new Byte[] { 0x40, 0x01, 0x00, 0x2a, 0x11 }, Remote); + } + + Assert.That(channel.Sent, Is.Empty); + } + + [Test] + public void MalformedResponseAndEmptyMessageAreDroppedWithoutReset() + { + RecordingChannel channel = new RecordingChannel(); + using (CoAPEndPoint endpoint = new CoAPEndPoint(channel, CoapConfig.Default) + { + Executor = Executors.NoThreading + }) + { + endpoint.Start(); + // ACK response declares a one-byte token but ends at the header. + channel.Emit(new Byte[] { 0x61, 0x45, 0x00, 0x01 }, Remote); + // Empty ACK with a payload marker is malformed and must not be a ping. + channel.Emit(new Byte[] { 0x60, 0x00, 0x00, 0x02, 0xff, 0x01 }, Remote); + channel.Emit(new Byte[] { 0x50, 0x00, 0x00, 0x04 }, Remote); + } + + Assert.That(channel.Sent, Is.Empty); + } + + private sealed class RecordingChannel : IChannel + { + public event EventHandler DataReceived; + + public List Sent { get; } = new List(); + + public NetworkEndPoint LocalEndPoint { get; } = new IPEndPoint(IPAddress.Loopback, 0); + + public void Start() + { } + + public void Stop() + { } + + public void Send(Byte[] data, NetworkEndPoint endpoint) + { + Sent.Add(new SentDatagram(data.ToArray(), endpoint)); + } + + public void Emit(Byte[] data, NetworkEndPoint endpoint) + { + DataReceived?.Invoke(this, new DataReceivedEventArgs(data, endpoint)); + } + + public void Dispose() + { } + } + + private sealed class SentDatagram + { + public SentDatagram(Byte[] data, NetworkEndPoint endPoint) + { + Data = data; + EndPoint = endPoint; + } + + public Byte[] Data { get; } + + public NetworkEndPoint EndPoint { get; } + } + } +} From 7aa0fcb37a6344199aa1420d7ab1531f1c372042 Mon Sep 17 00:00:00 2001 From: maikebing Date: Fri, 13 Nov 2026 01:12:20 +0800 Subject: [PATCH 4/7] fix(blockwise): cancel invalid atomic upload responses --- CoAP.NET/Stack/BlockwiseLayer.cs | 22 ++++++- CoAP.Test/BlockwiseProtocolRegressionTest.cs | 67 +++++++++++++++++++- 2 files changed, 84 insertions(+), 5 deletions(-) diff --git a/CoAP.NET/Stack/BlockwiseLayer.cs b/CoAP.NET/Stack/BlockwiseLayer.cs index d507fcd..76024f3 100644 --- a/CoAP.NET/Stack/BlockwiseLayer.cs +++ b/CoAP.NET/Stack/BlockwiseLayer.cs @@ -313,11 +313,29 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re return; } + // A collecting server must not include Block2, and its + // non-final successes must be Continue. Conversely, Continue + // cannot be the final outcome after the last request block. + // Never report any of these protocol errors as upload success. + if (block1.M && response.HasOption(OptionType.Block2) || + status != null && Code.IsSuccess(response.Code) && + (block1.M && response.StatusCode != StatusCode.Continue || + status.Complete && response.StatusCode == StatusCode.Continue)) + { + if (Log.IsEnabled(LogLevel.Warning)) + Log.LogWarning("Cancelling upload after an invalid Block1 response: " + + response.CodeString + " " + block1); + exchange.RequestBlockStatus = null; + ClearBlockCleanup(exchange); + exchange.Complete = true; + exchange.Request.Cancel(); + return; + } + // RFC 7959 sections 2.3 and 2.5: atomic uploads use 2.31 // Continue; a server acting on individual blocks may instead // return another success code with its Block1 M bit cleared. - if (status == null || status.Complete || !Code.IsSuccess(response.Code) - || (response.StatusCode != StatusCode.Continue && block1.M)) + if (status == null || status.Complete || !Code.IsSuccess(response.Code)) { exchange.RequestBlockStatus = null; ClearBlockCleanup(exchange); diff --git a/CoAP.Test/BlockwiseProtocolRegressionTest.cs b/CoAP.Test/BlockwiseProtocolRegressionTest.cs index b6a62ce..e245319 100644 --- a/CoAP.Test/BlockwiseProtocolRegressionTest.cs +++ b/CoAP.Test/BlockwiseProtocolRegressionTest.cs @@ -150,7 +150,7 @@ public void PerBlockSuccessWithMoreBitCleared_ContinuesUpload(StatusCode statusC [TestCase(StatusCode.Created)] [TestCase(StatusCode.Changed)] - public void AtomicSuccessWithoutContinue_DoesNotContinueUpload(StatusCode statusCode) + public void AtomicSuccessWithoutContinue_CancelsUploadWithoutReportingSuccess(StatusCode statusCode) { Request request = Request.NewPost(); request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); @@ -168,9 +168,40 @@ public void AtomicSuccessWithoutContinue_DoesNotContinueUpload(StatusCode status layer.ReceiveResponse(next, exchange, response); Assert.That(next.SentRequests, Is.EqualTo(1)); - Assert.That(next.ReceivedResponses, Is.EqualTo(1)); - Assert.That(next.LastResponse, Is.SameAs(response)); + Assert.That(next.ReceivedResponses, Is.EqualTo(0)); + Assert.That(request.IsCancelled, Is.True); + Assert.That(exchange.Complete, Is.True); + Assert.That(request.WaitForResponse(0), Is.Null); + Assert.That(exchange.RequestBlockStatus, Is.Null); + } + + [TestCase(StatusCode.Continue)] + [TestCase(StatusCode.Changed)] + public void AtomicBlock1ResponseWithBlock2_CancelsBeforeSendingAnotherRequest(StatusCode statusCode) + { + Request request = Request.NewPost(); + request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + layer.SendRequest(next, exchange, request); + Response response = Response.CreateResponse(request, statusCode); + response.SetPayload("0123456789abcdef", MediaType.TextPlain); + response.AddOption(new BlockOption(OptionType.Block1, 0, 0, true)); + response.AddOption(new BlockOption(OptionType.Block2, 0, 0, true)); + + layer.ReceiveResponse(next, exchange, response); + + Assert.That(next.SentRequests, Is.EqualTo(1)); + Assert.That(next.ReceivedResponses, Is.EqualTo(0)); + Assert.That(request.IsCancelled, Is.True); + Assert.That(exchange.Complete, Is.True); Assert.That(exchange.RequestBlockStatus, Is.Null); + Assert.That(exchange.ResponseBlockStatus, Is.Null); } [Test] @@ -254,6 +285,36 @@ public void DuplicateContinueWhileFinalBlockIsOutstanding_DoesNotFinishUpload() Assert.That(exchange.RequestBlockStatus, Is.Null); } + [TestCase(false)] + [TestCase(true)] + public void ContinueForFinalBlock_CancelsUploadWithoutReportingSuccess(bool more) + { + Request request = Request.NewPost(); + request.SetPayload(new byte[32], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + layer.SendRequest(next, exchange, request); + Response first = Response.CreateResponse(request, StatusCode.Continue); + first.AddOption(new BlockOption(OptionType.Block1, 0, 0, true)); + layer.ReceiveResponse(next, exchange, first); + Response invalidFinal = Response.CreateResponse(request, StatusCode.Continue); + invalidFinal.AddOption(new BlockOption(OptionType.Block1, 1, 0, more)); + + layer.ReceiveResponse(next, exchange, invalidFinal); + + Assert.That(next.SentRequests, Is.EqualTo(2)); + Assert.That(next.ReceivedResponses, Is.EqualTo(0)); + Assert.That(request.IsCancelled, Is.True); + Assert.That(exchange.Complete, Is.True); + Assert.That(request.WaitForResponse(0), Is.Null); + Assert.That(exchange.RequestBlockStatus, Is.Null); + } + [Test] public void ContinueWithSmallerBlockSize_PreservesTheByteOffset() { From 258f9e987dd31955bb4a21305ea599d097996a9f Mon Sep 17 00:00:00 2001 From: maikebing Date: Fri, 13 Nov 2026 01:56:41 +0800 Subject: [PATCH 5/7] fix(protocol): classify odd option numbers as critical --- CoAP.NET/Option.cs | 2 +- CoAP.Test/CriticalOptionClassificationTest.cs | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 CoAP.Test/CriticalOptionClassificationTest.cs diff --git a/CoAP.NET/Option.cs b/CoAP.NET/Option.cs index c8d20fe..23e9f2d 100644 --- a/CoAP.NET/Option.cs +++ b/CoAP.NET/Option.cs @@ -437,7 +437,7 @@ public static OptionFormat GetFormatByType(OptionType type) /// true if the option is critical public static Boolean IsCritical(OptionType type) { - return ((Int32)type & 1) > 1; + return ((Int32)type & 1) != 0; } /// diff --git a/CoAP.Test/CriticalOptionClassificationTest.cs b/CoAP.Test/CriticalOptionClassificationTest.cs new file mode 100644 index 0000000..8b95959 --- /dev/null +++ b/CoAP.Test/CriticalOptionClassificationTest.cs @@ -0,0 +1,33 @@ +using System; +using NUnit.Framework; + +namespace CoAP.Protocol +{ + [TestFixture] + public sealed class CriticalOptionClassificationTest + { + [TestCase(1)] + [TestCase(11)] + [TestCase(19)] + [TestCase(31)] + [TestCase(205)] + [TestCase(65001)] + public void OddOptionNumbersAreCriticalAndNotElective(Int32 number) + { + Assert.That(Option.IsCritical((OptionType)number), Is.True); + Assert.That(Option.IsElective((OptionType)number), Is.False); + } + + [TestCase(0)] + [TestCase(4)] + [TestCase(12)] + [TestCase(28)] + [TestCase(204)] + [TestCase(65000)] + public void EvenOptionNumbersAreElectiveAndNotCritical(Int32 number) + { + Assert.That(Option.IsCritical((OptionType)number), Is.False); + Assert.That(Option.IsElective((OptionType)number), Is.True); + } + } +} From 41ac813a1e5355eb30ba2a9d867ca7af5ce8385e Mon Sep 17 00:00:00 2001 From: maikebing Date: Fri, 13 Nov 2026 02:32:18 +0800 Subject: [PATCH 6/7] fix(protocol): normalize mapped IPv4 peers in matcher --- CoAP.NET/Net/Matcher.cs | 24 +++- CoAP.Test/MatcherProtocolTest.cs | 238 +++++++++++++++++++++++++++++++ 2 files changed, 258 insertions(+), 4 deletions(-) diff --git a/CoAP.NET/Net/Matcher.cs b/CoAP.NET/Net/Matcher.cs index 0292d1b..c448aaf 100644 --- a/CoAP.NET/Net/Matcher.cs +++ b/CoAP.NET/Net/Matcher.cs @@ -359,7 +359,7 @@ public Exchange ReceiveEmptyMessage(EmptyMessage message) System.Net.EndPoint destination = exchange.Origin == Origin.Local ? exchange.CurrentRequest.Destination : exchange.CurrentResponse.Destination; - if (!Object.Equals(destination, message.Source)) + if (!EndPointsEqual(destination, message.Source)) return null; if (Log.IsEnabled(LogLevel.Debug)) @@ -494,7 +494,7 @@ private static Boolean IsResponseMatch(Response response, Exchange exchange) !ByteArrayUtils.Equals(request.Token, response.Token)) return false; - if (!request.Multicast && !Object.Equals(request.Destination, response.Source)) + if (!request.Multicast && !EndPointsEqual(request.Destination, response.Source)) return false; // Piggybacked responses are matched by both the request MID and @@ -503,6 +503,22 @@ private static Boolean IsResponseMatch(Response response, Exchange exchange) return response.Type != MessageType.ACK || response.ID == request.ID; } + private static Boolean EndPointsEqual(System.Net.EndPoint first, System.Net.EndPoint second) + { + return Object.Equals(NormalizeEndPoint(first), NormalizeEndPoint(second)); + } + + private static System.Net.EndPoint NormalizeEndPoint(System.Net.EndPoint endpoint) + { + System.Net.IPEndPoint ipEndpoint = endpoint as System.Net.IPEndPoint; + if (ipEndpoint != null && ipEndpoint.Address.IsIPv4MappedToIPv6) + return new System.Net.IPEndPoint(ipEndpoint.Address.MapToIPv4(), ipEndpoint.Port); + + // Native IPv6 addresses keep their ScopeId, and custom endpoints + // keep their own equality semantics. + return endpoint; + } + private sealed class TokenKey : Exchange.KeyToken { private readonly Byte[] _token; @@ -516,11 +532,11 @@ public TokenKey(Byte[] token, System.Net.EndPoint endpoint) throw new ArgumentNullException("token"); _token = token; - _endpoint = endpoint; + _endpoint = NormalizeEndPoint(endpoint); unchecked { _hash = ByteArrayUtils.ComputeHash(token) * 31 + - (endpoint == null ? 0 : endpoint.GetHashCode()); + (_endpoint == null ? 0 : _endpoint.GetHashCode()); } } diff --git a/CoAP.Test/MatcherProtocolTest.cs b/CoAP.Test/MatcherProtocolTest.cs index 16ddfd6..e5b21d0 100644 --- a/CoAP.Test/MatcherProtocolTest.cs +++ b/CoAP.Test/MatcherProtocolTest.cs @@ -232,6 +232,244 @@ public void DuplicateMessageIdWithDifferentTokenDoesNotMatchEarlierResponse() } } + [TestCase(true, MessageType.ACK)] + [TestCase(true, MessageType.CON)] + [TestCase(true, MessageType.NON)] + [TestCase(false, MessageType.ACK)] + [TestCase(false, MessageType.CON)] + [TestCase(false, MessageType.NON)] + public void IPv4MappedResponseMatchesIPv4Peer(Boolean mappedDestination, MessageType type) + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1301, false, CreateIPv4Endpoint(mappedDestination, 5683)); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + Response response = CreateResponse(request, type, + type == MessageType.ACK ? request.ID : 0x2301, + CreateIPv4Endpoint(!mappedDestination, 5683)); + + Assert.That(ReceiveResponse(matcher, response), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [TestCase(true, MessageType.ACK)] + [TestCase(true, MessageType.RST)] + [TestCase(false, MessageType.ACK)] + [TestCase(false, MessageType.RST)] + public void IPv4MappedEmptyMessageMatchesPendingRequest(Boolean mappedDestination, MessageType type) + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1302, false, CreateIPv4Endpoint(mappedDestination, 5683)); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + EmptyMessage message = new EmptyMessage(type) + { + ID = request.ID, + Source = CreateIPv4Endpoint(!mappedDestination, 5683) + }; + + Assert.That(Invoke(matcher, "ReceiveEmptyMessage", message), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [TestCase(true, MessageType.ACK)] + [TestCase(true, MessageType.RST)] + [TestCase(false, MessageType.ACK)] + [TestCase(false, MessageType.RST)] + public void IPv4MappedEmptyMessageMatchesPendingResponse(Boolean mappedDestination, MessageType type) + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1303, false, LocalEndpoint); + request.Source = CreateIPv4Endpoint(mappedDestination, 5683); + Exchange exchange = new Exchange(request, Origin.Remote); + Response response = CreateResponse(request, MessageType.CON, 0x2303, LocalEndpoint); + response.Destination = request.Source; + exchange.CurrentResponse = response; + Invoke(matcher, "SendResponse", exchange, response); + + EmptyMessage message = new EmptyMessage(type) + { + ID = response.ID, + Source = CreateIPv4Endpoint(!mappedDestination, 5683) + }; + + Assert.That(Invoke(matcher, "ReceiveEmptyMessage", message), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [TestCase(true)] + [TestCase(false)] + public void IPv4MappedResponseStillRequiresMatchingPort(Boolean mappedDestination) + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1304, false, CreateIPv4Endpoint(mappedDestination, 5683)); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + Response wrong = CreateResponse(request, MessageType.ACK, request.ID, + CreateIPv4Endpoint(!mappedDestination, 5684)); + Assert.That(ReceiveResponse(matcher, wrong), Is.Null); + Response correct = CreateResponse(request, MessageType.ACK, request.ID, + CreateIPv4Endpoint(!mappedDestination, 5683)); + Assert.That(ReceiveResponse(matcher, correct), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [TestCase(MessageType.ACK)] + [TestCase(MessageType.RST)] + public void IPv4MappedEmptyMessageStillRequiresMatchingPort(MessageType type) + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1305, false, CreateIPv4Endpoint(true, 5683)); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + EmptyMessage message = new EmptyMessage(type) + { + ID = request.ID, + Source = CreateIPv4Endpoint(false, 5684) + }; + Assert.That(Invoke(matcher, "ReceiveEmptyMessage", message), Is.Null); + message.Source = CreateIPv4Endpoint(false, 5683); + Assert.That(Invoke(matcher, "ReceiveEmptyMessage", message), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [Test] + public void NativeIPv6ResponseStillRequiresMatchingScopeId() + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1306, false, CreateScopedIPv6Endpoint(7)); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + Response wrong = CreateResponse(request, MessageType.ACK, request.ID, + CreateScopedIPv6Endpoint(8)); + Assert.That(ReceiveResponse(matcher, wrong), Is.Null); + Response correct = CreateResponse(request, MessageType.ACK, request.ID, + CreateScopedIPv6Endpoint(7)); + Assert.That(ReceiveResponse(matcher, correct), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [TestCase(MessageType.ACK)] + [TestCase(MessageType.RST)] + public void NativeIPv6EmptyMessageStillRequiresMatchingScopeId(MessageType type) + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1307, false, CreateScopedIPv6Endpoint(7)); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + EmptyMessage message = new EmptyMessage(type) + { + ID = request.ID, + Source = CreateScopedIPv6Endpoint(8) + }; + Assert.That(Invoke(matcher, "ReceiveEmptyMessage", message), Is.Null); + message.Source = CreateScopedIPv6Endpoint(7); + Assert.That(Invoke(matcher, "ReceiveEmptyMessage", message), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + [Test] + public void CustomEndpointKeepsItsOwnEqualitySemantics() + { + object matcher = CreateMatcher(); + try + { + Request request = CreateRequest(0x1308, false, new NamedEndPoint("peer")); + Exchange exchange = new Exchange(request, Origin.Local); + Invoke(matcher, "SendRequest", exchange, request); + + Response wrong = CreateResponse(request, MessageType.ACK, request.ID, + new NamedEndPoint("other")); + Assert.That(ReceiveResponse(matcher, wrong), Is.Null); + Response correct = CreateResponse(request, MessageType.ACK, request.ID, + new NamedEndPoint("peer")); + Assert.That(ReceiveResponse(matcher, correct), Is.SameAs(exchange)); + } + finally + { + ((IDisposable)matcher).Dispose(); + } + } + + private static IPEndPoint CreateIPv4Endpoint(Boolean mapped, Int32 port) + { + return new IPEndPoint(mapped ? IPAddress.Loopback.MapToIPv6() : IPAddress.Loopback, port); + } + + private static IPEndPoint CreateScopedIPv6Endpoint(Int64 scopeId) + { + return new IPEndPoint(new IPAddress(IPAddress.Parse("fe80::1234").GetAddressBytes(), scopeId), 5683); + } + + private sealed class NamedEndPoint : System.Net.EndPoint + { + private readonly String _name; + + public NamedEndPoint(String name) + { + _name = name; + } + + public override Boolean Equals(Object obj) + { + NamedEndPoint other = obj as NamedEndPoint; + return other != null && String.Equals(_name, other._name, StringComparison.Ordinal); + } + + public override Int32 GetHashCode() + { + return StringComparer.Ordinal.GetHashCode(_name); + } + } + private static object CreateMatcher() { Type matcherType = typeof(CoapClient).Assembly.GetType("CoAP.Net.Matcher", true); From 6152facbd9603ef33fb9331da5aeb7168509b9a3 Mon Sep 17 00:00:00 2001 From: maikebing Date: Fri, 13 Nov 2026 02:35:43 +0800 Subject: [PATCH 7/7] fix(blockwise): terminate invalid acknowledgements and serialize transfers --- CoAP.NET/Stack/BlockwiseLayer.cs | 50 +++++++-- CoAP.Test/BlockwiseProtocolRegressionTest.cs | 104 ++++++++++++++++--- 2 files changed, 128 insertions(+), 26 deletions(-) diff --git a/CoAP.NET/Stack/BlockwiseLayer.cs b/CoAP.NET/Stack/BlockwiseLayer.cs index 76024f3..c7f7983 100644 --- a/CoAP.NET/Stack/BlockwiseLayer.cs +++ b/CoAP.NET/Stack/BlockwiseLayer.cs @@ -263,6 +263,11 @@ public override void SendResponse(INextLayer nextLayer, Exchange exchange, Respo /// public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Response response) { + // The matcher/reliability layers normally consume duplicates before + // this layer. Never let an explicitly marked duplicate end an upload. + if (response.Duplicate) + return; + // do not continue fetching blocks if canceled if (exchange.Request.IsCancelled) { @@ -295,21 +300,35 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re BlockwiseStatus status = exchange.RequestBlockStatus; if (status != null && block1.SZX == 7) { - // SZX 7 is reserved for the UDP blockwise protocol. Ignore - // this invalid acknowledgement without advancing upload. + // Reliability has already acknowledged this current response; + // abandoning it without a terminal signal would strand upload. if (Log.IsEnabled(LogLevel.Warning)) - Log.LogWarning("Ignoring Block1 response with reserved SZX 7."); + Log.LogWarning("Cancelling upload after Block1 response with reserved SZX 7."); + CancelBlockwiseUpload(exchange); return; } - // Match the acknowledgement even when the final request block - // has been sent: an earlier Continue must not finish that upload. + // Old message IDs and duplicates are filtered below this layer. + // A response matched to the outstanding message but acknowledging + // a different block is a protocol error, not a pending response. if (status != null && Code.IsSuccess(response.Code) && block1.NUM != status.CurrentNUM) { if (Log.IsEnabled(LogLevel.Warning)) - Log.LogWarning("Ignoring Block1 response for block " + block1.NUM + Log.LogWarning("Cancelling upload after Block1 response for block " + block1.NUM + "; expected " + status.CurrentNUM + "."); + CancelBlockwiseUpload(exchange); + return; + } + + // A normal request cannot complete with an unsolicited non-final + // Block1 success. Explicit Block1 requests are managed by callers; + // error responses such as 4.13 with a size hint remain deliverable. + if (status == null && !exchange.Request.HasOption(OptionType.Block1) + && Code.IsSuccess(response.Code) + && (response.StatusCode == StatusCode.Continue || block1.M)) + { + CancelBlockwiseUpload(exchange); return; } @@ -325,10 +344,7 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re if (Log.IsEnabled(LogLevel.Warning)) Log.LogWarning("Cancelling upload after an invalid Block1 response: " + response.CodeString + " " + block1); - exchange.RequestBlockStatus = null; - ClearBlockCleanup(exchange); - exchange.Complete = true; - exchange.Request.Cancel(); + CancelBlockwiseUpload(exchange); return; } @@ -364,7 +380,10 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re nextBlock.Token = response.Token; // reuse same token exchange.CurrentRequest = nextBlock; base.SendRequest(nextLayer, exchange, nextBlock); - // do not deliver response + // The high-level operation returns the final upload result. + // An optional intermediate per-block response body must not + // start Block2 retrieval alongside the next Block1 request. + return; } } @@ -461,6 +480,15 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re } } + private void CancelBlockwiseUpload(Exchange exchange) + { + exchange.RequestBlockStatus = null; + exchange.ResponseBlockStatus = null; + ClearBlockCleanup(exchange); + exchange.Complete = true; + exchange.Request.Cancel(); + } + private void EarlyBlock2Negotiation(Exchange exchange, Request request) { // Call this method when a request has completely arrived (might have diff --git a/CoAP.Test/BlockwiseProtocolRegressionTest.cs b/CoAP.Test/BlockwiseProtocolRegressionTest.cs index e245319..7c27197 100644 --- a/CoAP.Test/BlockwiseProtocolRegressionTest.cs +++ b/CoAP.Test/BlockwiseProtocolRegressionTest.cs @@ -9,9 +9,10 @@ namespace CoAP public sealed class BlockwiseProtocolRegressionTest { [Test] - public void Block1ResponseWithoutRequestStatus_IsForwarded() + public void ManuallyManagedBlock1ResponseWithoutRequestStatus_IsForwarded() { Request request = Request.NewPost(); + request.AddOption(new BlockOption(OptionType.Block1, 0, 0, true)); Exchange exchange = new Exchange(request, Origin.Local) { Request = request @@ -25,6 +26,46 @@ public void Block1ResponseWithoutRequestStatus_IsForwarded() Assert.DoesNotThrow(() => layer.ReceiveResponse(next, exchange, response)); Assert.That(next.ReceivedResponses, Is.EqualTo(1)); Assert.That(next.SentRequests, Is.EqualTo(0)); + Assert.That(request.IsCancelled, Is.False); + } + + [TestCase(StatusCode.Continue, false)] + [TestCase(StatusCode.Continue, true)] + [TestCase(StatusCode.Changed, true)] + public void UnsolicitedNonFinalBlock1SuccessForOrdinaryGet_CancelsWithoutReportingSuccess(StatusCode code, bool more) + { + Request request = Request.NewGet(); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + Response response = Response.CreateResponse(request, code); + response.AddOption(new BlockOption(OptionType.Block1, 0, 0, more)); + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig()); + + layer.ReceiveResponse(next, exchange, response); + + Assert.That(next.ReceivedResponses, Is.EqualTo(0)); + Assert.That(next.SentRequests, Is.EqualTo(0)); + Assert.That(request.IsCancelled, Is.True); + Assert.That(exchange.Complete, Is.True); + } + + [Test] + public void InitialRequestEntityTooLargeWithBlock1Hint_IsDelivered() + { + Request request = Request.NewPut(); + request.SetPayload("payload", MediaType.TextPlain); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + Response response = Response.CreateResponse(request, StatusCode.RequestEntityTooLarge); + response.AddOption(new BlockOption(OptionType.Block1, 0, 0, false)); + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig()); + + layer.ReceiveResponse(next, exchange, response); + + Assert.That(next.ReceivedResponses, Is.EqualTo(1)); + Assert.That(next.LastResponse, Is.SameAs(response)); + Assert.That(next.SentRequests, Is.EqualTo(0)); + Assert.That(request.IsCancelled, Is.False); } [TestCase(StatusCode.BadRequest)] @@ -60,8 +101,10 @@ public void Block1ErrorResponse_DoesNotContinueUpload(StatusCode statusCode) Assert.That(exchange.RequestBlockStatus, Is.Null); } - [Test] - public void DuplicateOrOutOfOrderBlock1Response_DoesNotAdvanceUpload() + [TestCase(1, 0)] + [TestCase(2, 0)] + [TestCase(0, 7)] + public void InvalidBlock1Acknowledgement_CancelsUpload(int number, int szx) { Request request = Request.NewPost(); request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); @@ -81,19 +124,16 @@ public void DuplicateOrOutOfOrderBlock1Response_DoesNotAdvanceUpload() Assert.That(status, Is.Not.Null); Assert.That(status.CurrentNUM, Is.EqualTo(0)); - Response duplicate = Response.CreateResponse(request, StatusCode.Continue); - duplicate.AddOption(new BlockOption(OptionType.Block1, 1, 0, true)); - layer.ReceiveResponse(next, exchange, duplicate); - - Assert.That(next.SentRequests, Is.EqualTo(1)); - Assert.That(status.CurrentNUM, Is.EqualTo(0)); - - Response outOfOrder = Response.CreateResponse(request, StatusCode.Continue); - outOfOrder.AddOption(new BlockOption(OptionType.Block1, 2, 0, true)); - layer.ReceiveResponse(next, exchange, outOfOrder); + Response response = Response.CreateResponse(request, StatusCode.Continue); + response.AddOption(new BlockOption(OptionType.Block1, number, szx, true)); + layer.ReceiveResponse(next, exchange, response); Assert.That(next.SentRequests, Is.EqualTo(1)); Assert.That(status.CurrentNUM, Is.EqualTo(0)); + Assert.That(next.ReceivedResponses, Is.EqualTo(0)); + Assert.That(request.IsCancelled, Is.True); + Assert.That(exchange.Complete, Is.True); + Assert.That(exchange.RequestBlockStatus, Is.Null); } [Test] @@ -148,6 +188,36 @@ public void PerBlockSuccessWithMoreBitCleared_ContinuesUpload(StatusCode statusC Assert.That(next.ReceivedResponses, Is.EqualTo(0)); } + [TestCase(false)] + [TestCase(true)] + public void IntermediateBlock2Body_DoesNotAdvanceOrCompleteTheUpload(bool more) + { + Request request = Request.NewPost(); + request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + BlockwiseLayer layer = new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16 + }); + layer.SendRequest(next, exchange, request); + Response response = Response.CreateResponse(request, StatusCode.Changed); + response.SetPayload("0123456789abcdef", MediaType.TextPlain); + response.AddOption(new BlockOption(OptionType.Block1, 0, 0, false)); + response.AddOption(new BlockOption(OptionType.Block2, 0, 0, more)); + + layer.ReceiveResponse(next, exchange, response); + + Assert.That(next.SentRequests, Is.EqualTo(2)); + Assert.That(next.LastRequest.Block1, Is.Not.Null); + Assert.That(next.LastRequest.Block1.NUM, Is.EqualTo(1)); + Assert.That(exchange.CurrentRequest, Is.SameAs(next.LastRequest)); + Assert.That(exchange.ResponseBlockStatus, Is.Null); + Assert.That(next.ReceivedResponses, Is.EqualTo(0)); + Assert.That(request.IsCancelled, Is.False); + } + [TestCase(StatusCode.Created)] [TestCase(StatusCode.Changed)] public void AtomicSuccessWithoutContinue_CancelsUploadWithoutReportingSuccess(StatusCode statusCode) @@ -205,7 +275,7 @@ public void AtomicBlock1ResponseWithBlock2_CancelsBeforeSendingAnotherRequest(St } [Test] - public void ContinueWithReservedBlockSize_DoesNotAdvanceUpload() + public void ContinueWithReservedBlockSize_CancelsUpload() { Request request = Request.NewPost(); request.SetPayload(new byte[48], MediaType.ApplicationOctetStream); @@ -223,7 +293,9 @@ public void ContinueWithReservedBlockSize_DoesNotAdvanceUpload() layer.ReceiveResponse(next, exchange, response); Assert.That(next.SentRequests, Is.EqualTo(1)); - Assert.That(exchange.RequestBlockStatus.CurrentNUM, Is.EqualTo(0)); + Assert.That(exchange.RequestBlockStatus, Is.Null); + Assert.That(request.IsCancelled, Is.True); + Assert.That(exchange.Complete, Is.True); Assert.That(next.ReceivedResponses, Is.EqualTo(0)); } @@ -244,6 +316,7 @@ public void DuplicateBlock1Response_DoesNotSkipTheOutstandingBlock() first.AddOption(new BlockOption(OptionType.Block1, 0, 0, true)); layer.ReceiveResponse(next, exchange, first); + first.Duplicate = true; layer.ReceiveResponse(next, exchange, first); Assert.That(next.SentRequests, Is.EqualTo(2)); @@ -270,6 +343,7 @@ public void DuplicateContinueWhileFinalBlockIsOutstanding_DoesNotFinishUpload() BlockwiseStatus status = exchange.RequestBlockStatus; Assert.That(status.Complete, Is.True); + first.Duplicate = true; layer.ReceiveResponse(next, exchange, first); Assert.That(next.SentRequests, Is.EqualTo(2));