Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@

## [Unreleased]

### Fixed — UDP interoperability audit (2026-11-13)

- 按 RFC 7252 严格拒绝截断头、Token、option、无 payload 的 marker 和非法 Empty/type/code 组合;修复版本自比较,格式失败后的 decoder 保持失败状态。可辨识的畸形 CON 使用匹配 MID 的 RST,ACK/RST、未知版本和短头不反射回复。
- 单播响应同时匹配完整 Token 和远端地址/端口,piggybacked ACK 另外校验 MID;空 ACK/RST 也绑定远端。保留组播的显式例外,不宣称完整组播实现。
- 端点键与比较统一规范化 IPv4-mapped IPv6,保留端口、原生 IPv6 ScopeId 与自定义 EndPoint 语义;避免有效响应/空 ACK/RST 因地址表示不同被丢弃。
- 修复 Option.IsCritical() 永远返回 false 的位掩码比较,奇数 option 为 critical、偶数为 elective;已知 option 长度和未知 critical 的 endpoint 策略仍由 #28 单独验收。
- 修复 Block1 无状态空引用、错误后继续上传、重复/乱序确认及中途降低块大小的偏移计算。保留 RFC 7959 的合法逐块 2.xx/M=0 模式;矛盾的原子响应、非法 Block2 组合和最后块 Continue 取消传输,不报告部分上传成功。
- 中间逐块响应附带 Block2 时只推进上传,不并发启动另一次取回或报告最终成功;已匹配的非法 NUM/SZX 明确取消并通知调用方,真正旧 MID/duplicate 保留忽略。无状态的非最终 Block1 成功被拒绝,手工 Block1 与合法 4.13 大小提示保持可用。
- CoapClient.SendAsync 将取消通知给失败回调与 Error 事件,追加 FailReason.Cancelled=2,保留 Rejected=0、TimedOut=1;同一请求的重复取消只通知一次。
- 吸纳上游 PR64 的停止日志修正和 PR80 的测试计数隔离思路,保留现有 ILogger 与测试框架。

### Documentation

- 新增[CoAP 标准与上游调查](docs/coap-standards-roadmap.md),记录 65 个上游 issue、17 个 PR、可见 fork 分支清单、跨语言实现比较、正式 RFC/IANA 边界和 #20~#31 逐项实现队列。单元测试、真实 peer、AOT、包与现场验收分别记录。

### Changed

- 准备 `3.0.1` 补丁候选,统一核心、ASP.NET Core adapter 和 source generator 的包版本,并将包仓库地址对齐当前正式仓库。
Expand Down
12 changes: 11 additions & 1 deletion CoAP.NET/CoapClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -391,9 +391,15 @@ public Response Send(Request request)

public void SendAsync(Request request, Action<Response> done = null, Action<FailReason> fail = null)
{
Int32 cancellationReported = 0;
request.Respond += (o, e) => Deliver(done, e);
request.Rejected += (o, e) => Fail(fail, FailReason.Rejected);
request.TimedOut += (o, e) => Fail(fail, FailReason.TimedOut);
request.Cancelled += (o, e) =>
{
if (System.Threading.Interlocked.Exchange(ref cancellationReported, 1) == 0)
Fail(fail, FailReason.Cancelled);
};

Prepare(request).Send();
}
Expand Down Expand Up @@ -534,7 +540,11 @@ public enum FailReason
/// <summary>
/// The request has been timed out.
/// </summary>
TimedOut
TimedOut,
/// <summary>
/// 请求已取消,包括协议层拒绝不合法的传输响应。
/// </summary>
Cancelled
}

/// <summary>
Expand Down
23 changes: 21 additions & 2 deletions CoAP.NET/Codec/DatagramReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ public DatagramReader(Byte[] buffer)
/// <returns>An integer containing the bits read</returns>
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--)
{
Expand Down Expand Up @@ -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?
Expand Down Expand Up @@ -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;
}
}
}
}
36 changes: 33 additions & 3 deletions CoAP.NET/Codec/MessageDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*/

using System;
using System.IO;

namespace CoAP.Codec
{
Expand All @@ -18,6 +19,8 @@ namespace CoAP.Codec
/// </summary>
public abstract class MessageDecoder : IMessageDecoder
{
private Boolean _decodeFailed;

/// <summary>
/// the bytes reader
/// </summary>
Expand Down Expand Up @@ -107,39 +110,43 @@ public Int32 ID
/// <inheritdoc/>
public Request DecodeRequest()
{
ThrowIfDecodeFailed();
System.Diagnostics.Debug.Assert(IsRequest);
Request request = new Request((Method)m_code);
request.Type = m_type;
request.ID = m_id;
ParseMessage(request);
ParseMessageGuarded(request);
return request;
}

/// <inheritdoc/>
public Response DecodeResponse()
{
ThrowIfDecodeFailed();
System.Diagnostics.Debug.Assert(IsResponse);
Response response = new Response((StatusCode)m_code);
response.Type = m_type;
response.ID = m_id;
ParseMessage(response);
ParseMessageGuarded(response);
return response;
}

/// <inheritdoc/>
public EmptyMessage DecodeEmptyMessage()
{
ThrowIfDecodeFailed();
System.Diagnostics.Debug.Assert(!IsRequest && !IsResponse);
EmptyMessage message = new EmptyMessage(m_type);
message.Type = m_type;
message.ID = m_id;
ParseMessage(message);
ParseMessageGuarded(message);
return message;
}

/// <inheritdoc/>
public Message Decode()
{
ThrowIfDecodeFailed();
if (IsRequest)
return DecodeRequest();
else if (IsResponse)
Expand All @@ -150,6 +157,29 @@ public Message Decode()
return null;
}

private void ParseMessageGuarded(Message message)
{
try
{
ParseMessage(message);
}
catch (Exception exception) when (exception is ArgumentException ||
exception is FormatException || exception is InvalidOperationException ||
exception is EndOfStreamException)
{
// A failed parse may already have consumed bytes. It cannot be
// retried from that partial position as a different message.
_decodeFailed = true;
throw;
}
}

private void ThrowIfDecodeFailed()
{
if (_decodeFailed)
throw new FormatException("The CoAP decoder cannot be reused after a message format error.");
}

/// <summary>
/// Parses the rest data other than protocol headers into the given message.
/// </summary>
Expand Down
102 changes: 79 additions & 23 deletions CoAP.NET/Net/CoAPEndPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*/

using System;
using System.IO;
using CoAP.Channel;
using CoAP.Codec;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -232,35 +233,38 @@ 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;
try
{
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;
}

Expand All @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading