diff --git a/CHANGELOG.md b/CHANGELOG.md index f96d026..8a1162c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +### Token、unsigned option 与 Observe deadline — 2026-11-13 + +- #33 的自动请求 Token 改为平台 CSPRNG 生成八字节,保留显式 Token、重传、Blockwise 与 Observe 身份。当前 channel/exchange 没有真实 DTLS session/traffic-key/re-key identity,RFC 9175 secure-context non-reuse 仍 UNKNOWN,issue 保持开放。 +- #34 新增 `Option.UIntValue`、`Message.Size1Unsigned` / `Size2Unsigned`,覆盖完整 UInt32 范围;旧 signed API 和签名保留,typed raw getter 对过长值抛 `OverflowException`。Resource/MVC 反射与生成绑定支持 `uint` / `uint?`;组装保留只在首块出现的 Size 提示,不以提示预分配或替代 M 位。 +- #35 的 Observe 重注册采用 monotonic deadline、单一 `ITimer` 和最长 `Int32.MaxValue` 毫秒分片,支持 `UInt32.MaxValue` Max-Age。通知更新 deadline,取消、终态、Clear、Stop、Dispose 释放 timer。 +- [本批审计](docs/audits/coap-20261113/next-batch-validation.json)记录原始 FAIL 与本地回归;真实 peer、NativeAOT 实物、公开包与现场验收保持独立,#26 双实现矩阵为 NOT_RUN。 + ### Modern option semantics and lifecycle — 2026-11-13 - 按用户批准的兼容选择,默认 AddOption/codec 不再把 wire number 19 转成消息头 Token;旧 Token 名称保留并弃用,迁移到 Message.Token。QBlock1/2 仅登记现行名称/格式,默认未启用其处理器。 diff --git a/CoAP.NET/Message.cs b/CoAP.NET/Message.cs index 5d229e8..2e3dc2b 100644 --- a/CoAP.NET/Message.cs +++ b/CoAP.NET/Message.cs @@ -915,7 +915,7 @@ public Int64 MaxAge get { Option opt = GetFirstOption(OptionType.MaxAge); - return (null == opt) ? CoapConstants.DefaultMaxAge : opt.LongValue; + return (null == opt) ? CoapConstants.DefaultMaxAge : (Int64)opt.UIntValue; } set { @@ -1006,6 +1006,11 @@ public Int32? Observe /// /// Gets or sets the Size1 option. Be null if not set. /// + /// + /// Retains the legacy signed four-byte mapping, so 0x80000000..0xffffffff + /// read as negative values. Use for the full range. + /// + /// The raw value is longer than four bytes. public Int32? Size1 { get @@ -1025,6 +1030,11 @@ public Int32? Size1 /// /// Gets or sets the Size2 option. Be null if not set. /// + /// + /// Retains the legacy signed four-byte mapping, so 0x80000000..0xffffffff + /// read as negative values. Use for the full range. + /// + /// The raw value is longer than four bytes. public Int32? Size2 { get @@ -1041,6 +1051,46 @@ public Int32? Size2 } } + /// + /// Gets or sets Size1 in the full RFC 7959 unsigned range. Null means absent. + /// + /// The raw value is longer than four bytes. + public UInt32? Size1Unsigned + { + get + { + Option opt = GetFirstOption(OptionType.Size1); + return opt == null ? default(UInt32?) : opt.UIntValue; + } + set + { + if (value.HasValue) + SetOption(Option.Create(OptionType.Size1, value.Value)); + else + RemoveOptions(OptionType.Size1); + } + } + + /// + /// Gets or sets Size2 in the full RFC 7959 unsigned range. Null means absent. + /// + /// The raw value is longer than four bytes. + public UInt32? Size2Unsigned + { + get + { + Option opt = GetFirstOption(OptionType.Size2); + return opt == null ? default(UInt32?) : opt.UIntValue; + } + set + { + if (value.HasValue) + SetOption(Option.Create(OptionType.Size2, value.Value)); + else + RemoveOptions(OptionType.Size2); + } + } + public BlockOption Block1 { get { return GetFirstOption(OptionType.Block1) as BlockOption; } diff --git a/CoAP.NET/Option.cs b/CoAP.NET/Option.cs index 9e6ee66..40db752 100644 --- a/CoAP.NET/Option.cs +++ b/CoAP.NET/Option.cs @@ -93,10 +93,16 @@ public String StringValue /// /// Gets or sets int value of the option. /// + /// + /// Four-byte values retain the legacy signed bit pattern. Use + /// for unsigned CoAP integers up to UInt32.MaxValue. + /// + /// The raw value exceeds the integer or option width. public Int32 IntValue { get { + ValidateIntegerLength(sizeof(Int32), Length); return (Int32)int32Convertor.Decode(this._valueBytes); } set @@ -108,10 +114,16 @@ public Int32 IntValue /// /// Gets or sets long value of the option. /// + /// + /// Known integer options enforce their wire length. Other options retain + /// the legacy signed eight-byte bit pattern. + /// + /// The raw value exceeds the integer or option width. public Int64 LongValue { get { + ValidateIntegerLength(sizeof(Int64), Length); return (Int64)int64Convertor.Decode(_valueBytes); } set @@ -120,6 +132,53 @@ public Int64 LongValue } } + /// + /// Gets or sets an unsigned integer in the range 0..UInt32.MaxValue. + /// Zero is encoded as an empty value; legal leading zero bytes are accepted. + /// + /// The value exceeds the integer or option width. + public UInt32 UIntValue + { + get + { + ValidateIntegerLength(sizeof(UInt32), Length); + return unchecked((UInt32)int32Convertor.Decode(_valueBytes)); + } + set + { + Byte[] bytes = int64Convertor.Encode(value); + ValidateIntegerLength(sizeof(UInt32), bytes.Length); + _valueBytes = bytes; + } + } + + private void ValidateIntegerLength(Int32 width, Int32 length) + { + switch (_type) + { + case OptionType.ContentFormat: + case OptionType.Accept: + case OptionType.UriPort: + width = Math.Min(width, 2); + break; + case OptionType.Observe: + case OptionType.Block1: + case OptionType.Block2: + case OptionType.QBlock1: + case OptionType.QBlock2: + width = Math.Min(width, 3); + break; + case OptionType.MaxAge: + case OptionType.Size1: + case OptionType.Size2: + width = Math.Min(width, 4); + break; + } + + if (length > width) + throw new OverflowException(Name + " integer value exceeds " + width + " bytes."); + } + /// /// Gets the value of the option according to its type. /// @@ -128,6 +187,8 @@ public Object Value get { IConvertor convertor = GetConvertor(this._type); + if (GetFormatByType(_type) == OptionFormat.Integer) + ValidateIntegerLength(sizeof(Int32), Length); return null == convertor ? null : convertor.Decode(this._valueBytes); } } @@ -143,7 +204,7 @@ public Boolean IsDefault switch (this._type) { case OptionType.MaxAge: - return IntValue == CoapConstants.DefaultMaxAge; + return UIntValue == CoapConstants.DefaultMaxAge; default: return false; } @@ -157,7 +218,7 @@ public String ToValueString() case OptionFormat.Integer: return (_type == OptionType.Accept || _type == OptionType.ContentFormat) ? ("\"" + MediaType.ToString(IntValue) + "\"") : - IntValue.ToString(); + UIntValue.ToString(); case OptionFormat.String: return "\"" + StringValue + "\""; default: @@ -274,6 +335,19 @@ public static Option Create(OptionType type, Int64 val) return opt; } + /// + /// Creates an option from an unsigned integer without narrowing its value. + /// + /// The type of the option + /// The unsigned value of the option + /// The new option + public static Option Create(OptionType type, UInt32 val) + { + Option opt = Create(type); + opt.UIntValue = val; + return opt; + } + /// /// Splits a string into a set of options, e.g. a uri path. /// diff --git a/CoAP.NET/Server/Routing/CoapActionParameterBinder.cs b/CoAP.NET/Server/Routing/CoapActionParameterBinder.cs index 97cc90b..93e2cb4 100644 --- a/CoAP.NET/Server/Routing/CoapActionParameterBinder.cs +++ b/CoAP.NET/Server/Routing/CoapActionParameterBinder.cs @@ -422,6 +422,11 @@ private static object ConvertOptionValue(Option option, Type targetType, string return option.LongValue; } + if (targetType == typeof(uint)) + { + return option.UIntValue; + } + if (targetType == typeof(bool)) { return true; diff --git a/CoAP.NET/Server/Routing/CoapGeneratedEndpointHelpers.cs b/CoAP.NET/Server/Routing/CoapGeneratedEndpointHelpers.cs index c32e1c2..8376729 100644 --- a/CoAP.NET/Server/Routing/CoapGeneratedEndpointHelpers.cs +++ b/CoAP.NET/Server/Routing/CoapGeneratedEndpointHelpers.cs @@ -542,6 +542,11 @@ private static T ConvertOptionValue(Option option, string parameterName) return (T)(object)option.LongValue; } + if (targetType == typeof(uint)) + { + return (T)(object)option.UIntValue; + } + if (targetType == typeof(bool)) { return (T)(object)true; diff --git a/CoAP.NET/Stack/BlockwiseLayer.cs b/CoAP.NET/Stack/BlockwiseLayer.cs index 87fa7e8..62276e6 100644 --- a/CoAP.NET/Stack/BlockwiseLayer.cs +++ b/CoAP.NET/Stack/BlockwiseLayer.cs @@ -158,6 +158,8 @@ public override void ReceiveRequest(INextLayer nextLayer, Exchange exchange, Req if (IsTerminated(exchange) || !Object.ReferenceEquals(status, exchange.RequestBlockStatus)) return; status.AddBlock(request.Payload); + if (request.HasOption(OptionType.Size1)) + status.Size1 = request.Size1Unsigned; } } else @@ -466,6 +468,8 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re if (IsTerminated(exchange) || !Object.ReferenceEquals(status, exchange.ResponseBlockStatus)) return; status.AddBlock(response.Payload); + if (response.HasOption(OptionType.Size2)) + status.Size2 = response.Size2Unsigned; Int32? obs = response.Observe; if (obs.HasValue) status.Observe = obs.Value; @@ -845,6 +849,14 @@ private void AssembleMessage(BlockwiseStatus status, Message message, Message la message.Type = last.Type; message.SetOptions(last.GetOptions()); + // An unchanged size indication may be omitted after the first block + // (RFC 7959 section 4). It remains metadata, not an allocation limit + // or an alternative to the Block option's M bit. + if (message is Request && !message.HasOption(OptionType.Size1)) + message.Size1Unsigned = status.Size1; + if (message is Response && !message.HasOption(OptionType.Size2)) + message.Size2Unsigned = status.Size2; + Int32 length = 0; foreach (Byte[] block in status.Blocks) length += block.Length; diff --git a/CoAP.NET/Stack/BlockwiseStatus.cs b/CoAP.NET/Stack/BlockwiseStatus.cs index d6e4f8a..be2015b 100644 --- a/CoAP.NET/Stack/BlockwiseStatus.cs +++ b/CoAP.NET/Stack/BlockwiseStatus.cs @@ -29,6 +29,11 @@ public class BlockwiseStatus private Int32 _observe = NoObserve; private List _blocks = new List(); + // RFC 7959 section 4 permits a size estimate on the first block only. + // Keep just the latest scalar indication, never allocate from it. + internal UInt32? Size1 { get; set; } + internal UInt32? Size2 { get; set; } + /// /// Instantiates a new blockwise status. /// diff --git a/CoAP.NET/Stack/ObserveLayer.cs b/CoAP.NET/Stack/ObserveLayer.cs index 586a795..6fbd152 100644 --- a/CoAP.NET/Stack/ObserveLayer.cs +++ b/CoAP.NET/Stack/ObserveLayer.cs @@ -10,6 +10,7 @@ */ using System; +using System.Threading; using System.Timers; using Microsoft.Extensions.Logging; using CoAP.Net; @@ -25,14 +26,23 @@ public class ObserveLayer : AbstractLayer /// /// Additional time to wait until re-registration /// - private Int32 _backoff; + private readonly Int32 _backoff; + private readonly TimeProvider _timeProvider; /// /// Constructs a new observe layer. /// - public ObserveLayer(ICoapConfig config) + public ObserveLayer(ICoapConfig config) : this(config, TimeProvider.System) + { + } + + /// + /// Constructs an observe layer using the supplied monotonic clock and timer provider. + /// + public ObserveLayer(ICoapConfig config, TimeProvider timeProvider) { _backoff = config.NotificationReregistrationBackoff; + _timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider)); } /// @@ -146,6 +156,7 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re else { // No observe option in response => always deliver + ReleaseExchange(exchange); base.ReceiveResponse(nextLayer, exchange, response); } } @@ -243,14 +254,14 @@ private void PrepareReregistration(Exchange exchange, Response response, Action< if (CoAPEndPoint.IsExchangeRetired(exchange) || exchange.Complete || exchange.Request.IsCancelled || exchange.Request.IsTimedOut || exchange.Request.IsRejected) return; - Int64 timeout = response.MaxAge * 1000 + _backoff; - ReregistrationContext ctx = exchange.GetOrAdd( - ReregistrationContextKey, _ => new ReregistrationContext(exchange, timeout, reregister)); + Int64 timeout = Math.Max(0, response.MaxAge * 1000 + _backoff); + ReregistrationContext ctx = exchange.GetOrAdd( + ReregistrationContextKey, _ => new ReregistrationContext(exchange, _timeProvider, reregister)); if (Log.IsEnabled(LogLevel.Debug)) Log.LogDebug("Scheduling re-registration in " + timeout + "ms for " + exchange.Request); - ctx.Restart(); + ctx.Restart(timeout); } } @@ -264,78 +275,159 @@ internal static void ReleaseExchange(Exchange exchange) class ReregistrationContext : IDisposable { - private Exchange _exchange; - private Action _reregister; - private System.Timers.Timer _timer; - private Int32 _disposed; + private readonly Exchange _exchange; + private readonly Request _request; + private readonly Action _reregister; + private readonly TimeProvider _timeProvider; + private ITimer _timer; + private Int64 _started; + private TimeSpan _timeout; + private Int64 _generation; + private Boolean _armed; + private Boolean _disposed; - public ReregistrationContext(Exchange exchange, Int64 timeout, Action reregister) + public ReregistrationContext(Exchange exchange, TimeProvider timeProvider, Action reregister) { _exchange = exchange; + _request = exchange.Request; _reregister = reregister; - _timer = new System.Timers.Timer(timeout); - _timer.AutoReset = false; - _timer.Elapsed += timer_Elapsed; + _timeProvider = timeProvider; + _timer = timeProvider.CreateTimer(OnTimer, null, + Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + _request.Cancelled += Terminated; + _request.TimedOut += Terminated; + _request.Rejected += Terminated; + exchange.Completed += Terminated; } - public void Start() + public void Restart(Int64 timeout) { - Restart(); + lock (_exchange) + { + if (_disposed) + return; + _started = _timeProvider.GetTimestamp(); + _timeout = TimeSpan.FromMilliseconds(timeout); + _generation++; + _armed = true; + Schedule(_timeout); + } } - public void Restart() + private void Schedule(TimeSpan remaining) { - System.Timers.Timer timer = _timer; - if (timer == null || System.Threading.Volatile.Read(ref _disposed) != 0) - return; - try { timer.Stop(); timer.Start(); } - catch (ObjectDisposedException) { } + // A legal UInt32 Max-Age can exceed the platform timer range by + // centuries. Keep one timer and recheck the monotonic deadline + // after each bounded slice, without shortening the total wait. + TimeSpan slice = TimeSpan.FromMilliseconds(Int32.MaxValue); + _timer.Change(remaining < slice ? remaining : slice, Timeout.InfiniteTimeSpan); } - public void Cancel() + private void Terminated(Object sender, EventArgs args) => Dispose(); + + private void OnTimer(Object state) { - Dispose(); + try + { + timer_Elapsed(null, null); + } + catch (Exception error) + { + // Thread-pool timer callbacks have no synchronous caller. + // Report user/lower-layer failures without terminating it. + Dispose(); + Log.LogError(error, "Observe re-registration failed"); + } } public void Dispose() { - System.Threading.Interlocked.Exchange(ref _disposed, 1); - System.Timers.Timer timer = System.Threading.Interlocked.Exchange(ref _timer, null); - if (timer != null) + ITimer timer; + lock (_exchange) { - timer.Stop(); - timer.Dispose(); + if (_disposed) + return; + _disposed = true; + _armed = false; + _generation++; + timer = _timer; + _timer = null; + _request.Cancelled -= Terminated; + _request.TimedOut -= Terminated; + _request.Rejected -= Terminated; + _exchange.Completed -= Terminated; + if (ReferenceEquals(_exchange.Get(ReregistrationContextKey), this)) + _exchange.Remove(ReregistrationContextKey); } + timer?.Dispose(); } void timer_Elapsed(Object sender, ElapsedEventArgs e) { - Request request = _exchange.Request; - if (System.Threading.Volatile.Read(ref _disposed) == 0 && - !CoAPEndPoint.IsExchangeRetired(_exchange) && !_exchange.Complete && - !request.IsCancelled && !request.IsTimedOut && !request.IsRejected) + Request request; + Int64 generation; + lock (_exchange) + { + if (_disposed || !_armed) + return; + request = _exchange.Request; + if (IsTerminated(request)) + { + Dispose(); + return; + } + TimeSpan remaining = _timeout - _timeProvider.GetElapsedTime(_started); + if (remaining > TimeSpan.Zero) + { + Schedule(remaining); + return; + } + _armed = false; + generation = _generation; + } + + Request refresh = Request.NewGet(); + refresh.SetOptions(request.GetOptions()); + refresh.MarkObserve(); + refresh.Token = request.Token; + refresh.Destination = request.Destination; + refresh.CopyEventHandler(request); + // The context owns the original subscription. Do not duplicate + // its cleanup handlers onto each refresh request. + refresh.Cancelled -= Terminated; + refresh.TimedOut -= Terminated; + refresh.Rejected -= Terminated; + if (Log.IsEnabled(LogLevel.Debug)) + Log.LogDebug("Re-registering for " + request); + try { - Request refresh = Request.NewGet(); - refresh.SetOptions(request.GetOptions()); - // make sure Observe is set and zero - refresh.MarkObserve(); - // use same Token - refresh.Token = request.Token; - refresh.Destination = request.Destination; - refresh.CopyEventHandler(request); - if (Log.IsEnabled(LogLevel.Debug)) - Log.LogDebug("Re-registering for " + request); request.FireReregister(refresh); - if (System.Threading.Volatile.Read(ref _disposed) == 0 && - !CoAPEndPoint.IsExchangeRetired(_exchange) && !_exchange.Complete && - !request.IsCancelled && !request.IsTimedOut && !request.IsRejected) - _reregister(refresh); } - else + catch { - if (Log.IsEnabled(LogLevel.Debug)) - Log.LogDebug("Dropping re-registration for canceled " + request); + Dispose(); + throw; } + lock (_exchange) + { + if (_disposed || generation != _generation || IsTerminated(request)) + return; + } + try + { + _reregister(refresh); + } + catch + { + Dispose(); + throw; + } + } + + private Boolean IsTerminated(Request request) + { + return CoAPEndPoint.IsExchangeRetired(_exchange) || _exchange.Complete || + request.IsCancelled || request.IsTimedOut || request.IsRejected; } } } diff --git a/CoAP.NET/Stack/TokenLayer.cs b/CoAP.NET/Stack/TokenLayer.cs index 303eba6..68f2992 100644 --- a/CoAP.NET/Stack/TokenLayer.cs +++ b/CoAP.NET/Stack/TokenLayer.cs @@ -10,25 +10,25 @@ */ using System; +using System.Security.Cryptography; using CoAP.Net; namespace CoAP.Stack { /// - /// Doesn't do much yet except for setting a simple token. Notice that empty - /// tokens must be represented as byte array of length 0 (not null). + /// Assigns cryptographically random eight-byte tokens when the caller has + /// not supplied one. Empty tokens are byte arrays of length zero, not null. + /// Transport security context binding is not provided by this layer. /// public class TokenLayer : AbstractLayer { - private Int32 _counter; - /// /// Constructs a new token layer. /// public TokenLayer(ICoapConfig config) { - if (config.UseRandomTokenStart) - _counter = new Random().Next(); + // Keep the constructor and configuration surface compatible. The old + // UseRandomTokenStart setting must not disable fresh randomness. } /// @@ -67,12 +67,11 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re private Byte[] NewToken() { - UInt32 token = (UInt32)System.Threading.Interlocked.Increment(ref _counter); - return new Byte[] - { - (Byte)(token >> 24), (Byte)(token >> 16), - (Byte)(token >> 8), (Byte)token - }; + // RFC 7252 section 5.3.1 recommends nontrivial randomized tokens + // without transport security. There is no wrapping counter or token + // history here. IChannel currently exposes no DTLS session/key + // identity: randomness alone does not establish RFC 9175 binding. + return RandomNumberGenerator.GetBytes(8); } } } diff --git a/CoAP.Test/Codec/MessageTest.cs b/CoAP.Test/Codec/MessageTest.cs index 740cb57..47c81f9 100644 --- a/CoAP.Test/Codec/MessageTest.cs +++ b/CoAP.Test/Codec/MessageTest.cs @@ -98,7 +98,7 @@ public void TestMessageWithOptions() msg.ID = 12345; msg.Payload = System.Text.Encoding.UTF8.GetBytes("payload"); - msg.AddOption(Option.Create(OptionType.ContentType, "text/plain")); + msg.AddOption(Option.Create(OptionType.ContentType, MediaType.TextPlain)); msg.AddOption(Option.Create(OptionType.MaxAge, 30)); Byte[] data = Spec.Encode(msg); diff --git a/CoAP.Test/EndpointOwnedExchangeTest.cs b/CoAP.Test/EndpointOwnedExchangeTest.cs index 99cea91..03f9207 100644 --- a/CoAP.Test/EndpointOwnedExchangeTest.cs +++ b/CoAP.Test/EndpointOwnedExchangeTest.cs @@ -102,7 +102,7 @@ public void CleanupCallbackCanStartReplacementRequest() public void ObserveRefreshReleasesBothProtocolContextsOnClear() { RecordingChannel channel = new RecordingChannel(); - using (CoAPEndPoint endpoint = Endpoint(channel)) + using (CoAPEndPoint endpoint = Endpoint(channel, notificationBackoff: 1)) { endpoint.Start(); Request request = Request.NewGet().MarkObserve(); @@ -113,10 +113,12 @@ public void ObserveRefreshReleasesBothProtocolContextsOnClear() response.Type = MessageType.ACK; response.ID = sent.ID; response.Observe = 1; - response.MaxAge = 60; + response.MaxAge = 0; + channel.SentSignal.Reset(); channel.Emit(Spec.Encode(response)); Object reregistration = exchange.Get("ReregistrationContext"); - InvokeTimer(reregistration); + Assert.That(channel.SentSignal.Wait(TimeSpan.FromSeconds(2)), Is.True, + "The zero-Max-Age re-registration should send within the bounded test window."); Object transmission = exchange.Get("TransmissionContext"); Assert.That(reregistration, Is.Not.Null); Assert.That(transmission, Is.Not.Null); @@ -220,9 +222,9 @@ private sealed class RequestDeliverer : IMessageDeliverer public void DeliverResponse(Exchange exchange, Response response) { } } - private static CoAPEndPoint Endpoint(RecordingChannel channel) + private static CoAPEndPoint Endpoint(RecordingChannel channel, int notificationBackoff = 10000) { - return new CoAPEndPoint(channel, new CoapConfig { AckTimeout = 10000, NotificationReregistrationBackoff = 10000 }) + return new CoAPEndPoint(channel, new CoapConfig { AckTimeout = 10000, NotificationReregistrationBackoff = notificationBackoff }) { Executor = Executors.NoThreading }; } @@ -243,11 +245,16 @@ private sealed class RecordingChannel : IChannel { public event EventHandler DataReceived; public List Sent { get; } = new List(); + public ManualResetEventSlim SentSignal { get; } = new ManualResetEventSlim(false); public System.Net.EndPoint LocalEndPoint { get; } = new IPEndPoint(IPAddress.Loopback, 10000); public void Start() { } public void Stop() { } - public void Dispose() { } - public void Send(Byte[] data, System.Net.EndPoint endpoint) { Sent.Add(data.ToArray()); } + public void Dispose() { SentSignal.Dispose(); } + public void Send(Byte[] data, System.Net.EndPoint endpoint) + { + Sent.Add(data.ToArray()); + SentSignal.Set(); + } public void Emit(Byte[] data) { DataReceived?.Invoke(this, new DataReceivedEventArgs(data, Peer)); } } } diff --git a/CoAP.Test/ObserveLongDeadlineTest.cs b/CoAP.Test/ObserveLongDeadlineTest.cs new file mode 100644 index 0000000..394ce1c --- /dev/null +++ b/CoAP.Test/ObserveLongDeadlineTest.cs @@ -0,0 +1,361 @@ +using System; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using CoAP.Net; +using CoAP.Stack; +using NUnit.Framework; + +namespace CoAP +{ + [TestFixture] + public sealed class ObserveLongDeadlineTest + { + [TestCase(2147483L)] + [TestCase(2147484L)] + [TestCase(4294967295L)] + public void LegalMaxAgeDoesNotOverflowTimer(long maxAge) + { + Request request = Request.NewGet().MarkObserve(); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + ObserveLayer layer = new ObserveLayer(new CoapConfig { NotificationReregistrationBackoff = 0 }); + try + { + Response notification = new Response(StatusCode.Content) { Observe = 0, MaxAge = maxAge }; + Assert.DoesNotThrow(() => layer.ReceiveResponse(new RecordingLayer(), exchange, notification)); + } + finally + { + (exchange.Remove("ReregistrationContext") as IDisposable)?.Dispose(); + } + } + + [Test] + public void ZeroMaxAgeAndBackoffDoesNotThrow() + { + Request request = Request.NewGet().MarkObserve(); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + ObserveLayer layer = new ObserveLayer(new CoapConfig { NotificationReregistrationBackoff = 0 }); + try + { + Response notification = new Response(StatusCode.Content) { Observe = 0, MaxAge = 0 }; + Assert.DoesNotThrow(() => layer.ReceiveResponse(new RecordingLayer(), exchange, notification)); + } + finally + { + (exchange.Remove("ReregistrationContext") as IDisposable)?.Dispose(); + } + } + + [Test] + public void LaterNotificationReplacesTheMonotonicDeadline() + { + FakeTimeProvider clock = new FakeTimeProvider(); + Request request = Request.NewGet().MarkObserve(); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + ObserveLayer layer = new ObserveLayer(new CoapConfig { NotificationReregistrationBackoff = 0 }, clock); + try + { + Response first = new Response(StatusCode.Content) { Observe = 1, MaxAge = 30 }; + layer.ReceiveResponse(new RecordingLayer(), exchange, first); + Assert.That(clock.Timer.Changes, Is.EqualTo(2)); + Assert.That(clock.Timer.LastDueTime, Is.EqualTo(TimeSpan.FromSeconds(30))); + + clock.Advance(TimeSpan.FromSeconds(5)); + Response second = new Response(StatusCode.Content) { Observe = 2, MaxAge = 60 }; + layer.ReceiveResponse(new RecordingLayer(), exchange, second); + Assert.That(clock.Timer.Changes, Is.EqualTo(3)); + Assert.That(clock.Timer.LastDueTime, Is.EqualTo(TimeSpan.FromSeconds(60))); + } + finally + { + (exchange.Remove("ReregistrationContext") as IDisposable)?.Dispose(); + } + } + + [Test] + public void QueuedTimerCallbackIsIgnoredAfterCancellation() + { + FakeTimeProvider clock = new FakeTimeProvider(); + Request request = Request.NewGet().MarkObserve(); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + int refreshes = 0; + ObserveLayer layer = new ObserveLayer(new CoapConfig { NotificationReregistrationBackoff = 0 }, clock); + try + { + layer.ReceiveResponse(new RecordingLayer(), exchange, + new Response(StatusCode.Content) { Observe = 1, MaxAge = 1 }); + request.Reregistering += (sender, args) => refreshes++; + request.Cancel(); + clock.Timer.Fire(); + Assert.That(refreshes, Is.Zero); + Assert.That(clock.Timer.Disposed, Is.True); + } + finally + { + (exchange.Remove("ReregistrationContext") as IDisposable)?.Dispose(); + } + } + + [TestCase(0L)] + [TestCase(30L)] + [TestCase(2147483L)] + [TestCase(2147484L)] + [TestCase(4294967295L)] + public void EachTimerSliceStaysWithinPlatformRange(long maxAge) + { + using (Observation observation = new Observation(250)) + { + observation.Notify(maxAge); + Assert.That(observation.Clock.CreatedTimers, Is.EqualTo(1)); + Assert.That(observation.Clock.Timer.LastDueTime, + Is.EqualTo(TimeSpan.FromMilliseconds(Math.Min(maxAge * 1000 + 250, int.MaxValue)))); + Assert.That(observation.Next.SentRequests, Is.Zero); + } + } + + [TestCase(1L)] + [TestCase(2147484L)] + [TestCase(4294967295L)] + public void RefreshWaitsUntilTheEntireDeadlineAndRunsOnce(long maxAge) + { + using (Observation observation = new Observation(11)) + { + observation.Notify(maxAge); + TimeSpan total = TimeSpan.FromMilliseconds(maxAge * 1000 + 11); + TimeSpan firstSlice = observation.Clock.Timer.LastDueTime; + observation.Clock.Advance(firstSlice - TimeSpan.FromMilliseconds(1)); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.Zero); + observation.Clock.Advance(total - firstSlice); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.Zero); + Assert.That(observation.Clock.Timer.LastDueTime, Is.EqualTo(TimeSpan.FromMilliseconds(1))); + + observation.Clock.Advance(TimeSpan.FromMilliseconds(1)); + observation.Clock.Timer.Fire(); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.EqualTo(1)); + Assert.That(observation.Next.Request.Observe, Is.Zero); + Assert.That(observation.Next.Request.Token, Is.EqualTo(observation.Request.Token)); + Assert.That(observation.Next.Request.UriPath, Is.EqualTo("/sensors/value")); + Assert.That(observation.Next.Request.Destination, Is.EqualTo(observation.Request.Destination)); + } + } + + [Test] + public void OldQueuedCallbackRechecksTheUpdatedNotificationDeadline() + { + using (Observation observation = new Observation()) + { + observation.Notify(30); + observation.Clock.Advance(TimeSpan.FromSeconds(5)); + observation.Notify(60); + observation.Clock.Advance(TimeSpan.FromSeconds(25)); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.Zero); + Assert.That(observation.Clock.Timer.LastDueTime, Is.EqualTo(TimeSpan.FromSeconds(35))); + observation.Clock.Advance(TimeSpan.FromSeconds(35)); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.EqualTo(1)); + } + } + + [Test] + public void NewNotificationCanShortenTheDeadline() + { + using (Observation observation = new Observation()) + { + observation.Notify(uint.MaxValue); + observation.Notify(1); + observation.Clock.Advance(TimeSpan.FromSeconds(1)); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.EqualTo(1)); + } + } + + [Test] + public void WallClockChangesDoNotExpireTheMonotonicDeadline() + { + using (Observation observation = new Observation()) + { + observation.Notify(60); + observation.Clock.WallClock = observation.Clock.WallClock.AddYears(200); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.Zero); + observation.Clock.WallClock = observation.Clock.WallClock.AddYears(-400); + observation.Clock.Advance(TimeSpan.FromSeconds(60)); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.EqualTo(1)); + } + } + + [TestCase("Cancel")] + [TestCase("Timeout")] + [TestCase("Reject")] + [TestCase("Complete")] + public void TerminalStateReleasesTimerAndRejectsQueuedCallbacks(string terminal) + { + using (Observation observation = new Observation()) + { + observation.Notify(uint.MaxValue); + if (terminal == "Cancel") observation.Request.Cancel(); + else if (terminal == "Timeout") observation.Request.IsTimedOut = true; + else if (terminal == "Reject") observation.Request.IsRejected = true; + else observation.Exchange.Complete = true; + + Assert.That(observation.Exchange.Get("ReregistrationContext"), Is.Null); + Assert.That(observation.Clock.Timer.Disposed, Is.True); + observation.Clock.Advance(TimeSpan.FromMilliseconds(uint.MaxValue * 1000L)); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.Zero); + } + } + + [Test] + public void ZeroDeadlineSchedulesImmediateSingleRefresh() + { + using (Observation observation = new Observation()) + { + observation.Notify(0); + Assert.That(observation.Clock.Timer.LastDueTime, Is.EqualTo(TimeSpan.Zero)); + observation.Clock.Timer.Fire(); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.EqualTo(1)); + } + } + + [Test] + public void ResponseWithoutObserveReleasesThePreviousTimer() + { + using (Observation observation = new Observation()) + { + observation.Notify(uint.MaxValue); + Response final = new Response(StatusCode.Content); + observation.Layer.ReceiveResponse(observation.Next, observation.Exchange, final); + Assert.That(observation.Next.Response, Is.SameAs(final)); + Assert.That(observation.Exchange.Get("ReregistrationContext"), Is.Null); + Assert.That(observation.Clock.Timer.Disposed, Is.True); + } + } + + [Test] + public void CancellationDuringPublicRefreshCallbackRunsOutsideExchangeLock() + { + using (Observation observation = new Observation()) + { + observation.Request.Reregistering += (sender, args) => + { + Assert.That(Monitor.IsEntered(observation.Exchange), Is.False); + Assert.That(Task.Run(() => observation.Request.Cancel()).Wait(TimeSpan.FromSeconds(1)), Is.True); + }; + observation.Notify(0); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.Zero); + Assert.That(observation.Clock.Timer.Disposed, Is.True); + } + } + + [Test] + public void NotificationDuringPublicRefreshCallbackInvalidatesThePendingRefresh() + { + using (Observation observation = new Observation()) + { + observation.Request.Reregistering += (sender, args) => observation.Notify(60); + observation.Notify(0); + observation.Clock.Timer.Fire(); + Assert.That(observation.Next.SentRequests, Is.Zero); + Assert.That(observation.Clock.Timer.LastDueTime, Is.EqualTo(TimeSpan.FromSeconds(60))); + } + } + + [Test] + public void ThrowingRefreshCallbackStillReleasesTheTimer() + { + using (Observation observation = new Observation()) + { + observation.Request.Reregistering += (sender, args) => throw new InvalidOperationException("refresh callback"); + observation.Notify(0); + Assert.DoesNotThrow(() => observation.Clock.Timer.Fire()); + Assert.That(observation.Clock.Timer.Disposed, Is.True); + Assert.That(observation.Exchange.Get("ReregistrationContext"), Is.Null); + } + } + + private sealed class Observation : IDisposable + { + public Observation(int backoff = 0) + { + Request = Request.NewGet().MarkObserve(); + Request.Token = new byte[] { 3, 4 }; + Request.UriPath = "sensors/value"; + Request.Destination = new IPEndPoint(IPAddress.Loopback, 5683); + Exchange = new Exchange(Request, Origin.Local) { Request = Request }; + Layer = new ObserveLayer(new CoapConfig { NotificationReregistrationBackoff = backoff }, Clock); + } + public FakeTimeProvider Clock { get; } = new FakeTimeProvider(); + public Request Request { get; } + public Exchange Exchange { get; } + public ObserveLayer Layer { get; } + public RecordingLayer Next { get; } = new RecordingLayer(); + public void Notify(long maxAge) => Layer.ReceiveResponse(Next, Exchange, + new Response(StatusCode.Content) { Observe = 1, MaxAge = maxAge }); + public void Dispose() => (Exchange.Remove("ReregistrationContext") as IDisposable)?.Dispose(); + } + + private sealed class RecordingLayer : INextLayer + { + public int SentRequests { get; private set; } + public Request Request { get; private set; } + public Response Response { get; private set; } + public void SendRequest(Exchange exchange, Request request) { SentRequests++; Request = 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) => Response = response; + public void ReceiveEmptyMessage(Exchange exchange, EmptyMessage message) { } + } + + private sealed class FakeTimeProvider : TimeProvider + { + private long _timestamp; + public FakeTimer Timer { get; } = new FakeTimer(); + public int CreatedTimers { get; private set; } + public DateTimeOffset WallClock { get; set; } = new DateTimeOffset(2026, 11, 13, 0, 0, 0, TimeSpan.Zero); + public override DateTimeOffset GetUtcNow() => WallClock; + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + public override long GetTimestamp() => _timestamp; + public override ITimer CreateTimer(TimerCallback callback, object state, + TimeSpan dueTime, TimeSpan period) + { + CreatedTimers++; + Timer.Callback = callback; + Timer.State = state; + Timer.Change(dueTime, period); + return Timer; + } + public void Advance(TimeSpan elapsed) => _timestamp += elapsed.Ticks; + } + + private sealed class FakeTimer : ITimer + { + public TimerCallback Callback { get; set; } + public object State { get; set; } + public TimeSpan LastDueTime { get; private set; } + public int Changes { get; private set; } + public bool Disposed { get; private set; } + public bool Change(TimeSpan dueTime, TimeSpan period) + { + Assert.That(dueTime == Timeout.InfiniteTimeSpan || + dueTime >= TimeSpan.Zero && dueTime <= TimeSpan.FromMilliseconds(int.MaxValue), Is.True); + Assert.That(period, Is.EqualTo(Timeout.InfiniteTimeSpan)); + LastDueTime = dueTime; + Changes++; + return !Disposed; + } + public void Fire() => Callback?.Invoke(State); + public void Dispose() => Disposed = true; + public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; } + } + } +} diff --git a/CoAP.Test/TokenGenerationTest.cs b/CoAP.Test/TokenGenerationTest.cs new file mode 100644 index 0000000..f3f12dd --- /dev/null +++ b/CoAP.Test/TokenGenerationTest.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Concurrent; +using System.Net; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using CoAP.Net; +using CoAP.Stack; +using NUnit.Framework; + +namespace CoAP +{ + [TestFixture] + public sealed class TokenGenerationTest + { + [TestCase(false)] + [TestCase(true)] + public void AutomaticToken_UsesEightBytesRegardlessOfOldCounterConfiguration(bool randomStart) + { + TokenLayer layer = new TokenLayer(new CoapConfig { UseRandomTokenStart = randomStart }); + Request request = Request.NewGet(); + + Send(layer, request); + + Assert.That(request.Token, Has.Length.EqualTo(8)); + } + + [Test] + public void NewLayers_DoNotRestartAtTheSameDeterministicToken() + { + CoapConfig config = new CoapConfig { UseRandomTokenStart = false }; + Request first = Request.NewGet(); + Request second = Request.NewGet(); + + Send(new TokenLayer(config), first); + Send(new TokenLayer(config), second); + + Assert.That(second.Token, Is.Not.EqualTo(first.Token)); + // Detects the old deterministic restart, not the entropy of an RNG. + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(4)] + [TestCase(8)] + public void ExplicitToken_IsPreservedIncludingEmpty(int length) + { + TokenLayer layer = new TokenLayer(new CoapConfig()); + byte[] token = new byte[length]; + Request request = Request.NewGet(); + request.Token = token; + + Send(layer, request); + + Assert.That(request.Token, Is.SameAs(token)); + } + + [Test] + public void ResendingRequest_PreservesTheTokenAndEncodedDatagram() + { + TokenLayer layer = new TokenLayer(new CoapConfig()); + Request request = Request.NewGet(); + request.ID = 1234; + Exchange exchange = Send(layer, request); + byte[] token = request.Token; + byte[] datagram = Spec.Encode(request); + + layer.SendRequest(new Sink(), exchange, request); + + Assert.That(request.Token, Is.SameAs(token)); + Assert.That(Spec.Encode(request), Is.EqualTo(datagram)); + } + + [Test] + public void ConcurrentRequests_AreIndependentAndMatchTheirResponses() + { + TokenLayer layer = new TokenLayer(new CoapConfig { UseRandomTokenStart = false }); + ConcurrentDictionary observed = new ConcurrentDictionary(); + using (CancellationTokenSource cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5))) + { + Parallel.For(0, 256, new ParallelOptions + { + MaxDegreeOfParallelism = 4, + CancellationToken = cancellation.Token + }, number => + { + Request request = Request.NewGet(); + Exchange exchange = Send(layer, request); + Assert.That(request.Token, Has.Length.EqualTo(8)); + Assert.That(observed.TryAdd(Convert.ToHexString(request.Token), 0), Is.True); + Response response = new Response(StatusCode.Content); + layer.SendResponse(new Sink(), exchange, response); + Assert.That(response.Token, Is.EqualTo(request.Token)); + }); + } + Assert.That(observed.Count, Is.EqualTo(256)); + // This is a concurrency/identity smoke check, not a statistical or security proof. + } + + [Test] + public void BlockwiseContinuationAndObserveCancellation_PreserveAssignedToken() + { + TokenLayer layer = new TokenLayer(new CoapConfig()); + Request registration = Request.NewGet(); + registration.MarkObserve(); + Exchange exchange = Send(layer, registration); + byte[] token = registration.Token; + + Request continuation = Request.NewGet(); + continuation.SetBlock2(0, false, 1); + continuation.Token = token; + exchange.CurrentRequest = continuation; + layer.SendRequest(new Sink(), exchange, continuation); + Assert.That(continuation.Token, Is.SameAs(token)); + + Request refresh = Request.NewGet(); + refresh.MarkObserve(); + refresh.Token = token; + layer.SendRequest(new Sink(), exchange, refresh); + Assert.That(refresh.Token, Is.SameAs(token)); + + Request cancellation = Request.NewGet(); + cancellation.MarkObserveCancel(); + cancellation.Token = token; + layer.SendRequest(new Sink(), exchange, cancellation); + Assert.That(cancellation.Token, Is.SameAs(token)); + } + + [Test] + public void CompletedRequests_AreNotRetainedByTheTokenLayer() + { + TokenLayer layer = new TokenLayer(new CoapConfig()); + WeakReference request = GenerateCompletedRequest(layer); + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + Assert.That(request.IsAlive, Is.False); + GC.KeepAlive(layer); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference GenerateCompletedRequest(TokenLayer layer) + { + Request request = Request.NewGet(); + Exchange exchange = Send(layer, request); + exchange.Complete = true; + return new WeakReference(request); + } + + private static Exchange Send(TokenLayer layer, Request request) + { + request.Destination = new IPEndPoint(IPAddress.Loopback, 5683); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + layer.SendRequest(new Sink(), exchange, request); + return exchange; + } + + private sealed class Sink : INextLayer + { + public void SendRequest(Exchange exchange, Request 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) { } + public void ReceiveEmptyMessage(Exchange exchange, EmptyMessage message) { } + } + } +} diff --git a/CoAP.Test/UnsignedBlockwiseSizeTest.cs b/CoAP.Test/UnsignedBlockwiseSizeTest.cs new file mode 100644 index 0000000..8488149 --- /dev/null +++ b/CoAP.Test/UnsignedBlockwiseSizeTest.cs @@ -0,0 +1,108 @@ +using System; +using CoAP.Net; +using CoAP.Stack; +using NUnit.Framework; + +namespace CoAP +{ + [TestFixture] + public sealed class UnsignedBlockwiseSizeTest + { + [TestCase(0U)] + [TestCase(2147483647U)] + [TestCase(2147483648U)] + [TestCase(UInt32.MaxValue)] + public void IncomingBlock1PreservesFirstSizeHintWithoutAllocatingIt(uint size) + { + Request first = Request.NewPost(); + first.Token = new byte[] { 1 }; + first.SetPayload(new byte[16], MediaType.ApplicationOctetStream); + first.SetBlock1(0, true, 0); + first.Size1Unsigned = size; + Exchange exchange = new Exchange(first, Origin.Remote) { Request = first }; + RecordingLayer next = new RecordingLayer(); + using BlockwiseLayer layer = Layer(); + layer.ReceiveRequest(next, exchange, first); + + Request last = Request.NewPost(); + last.Token = first.Token; + last.SetPayload(new byte[1], MediaType.ApplicationOctetStream); + last.SetBlock1(0, false, 1); + layer.ReceiveRequest(next, exchange, last); + + Assert.That(next.ReceivedRequest.Size1Unsigned, Is.EqualTo(size)); + Assert.That(next.ReceivedRequest.PayloadSize, Is.EqualTo(17)); + } + + [TestCase(0U)] + [TestCase(2147483647U)] + [TestCase(2147483648U)] + [TestCase(UInt32.MaxValue)] + public void IncomingBlock2PreservesFirstSizeHintWithoutAllocatingIt(uint size) + { + Request request = Request.NewGet(); + request.Token = new byte[] { 1 }; + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + using BlockwiseLayer layer = Layer(); + layer.SendRequest(next, exchange, request); + + Response first = new Response(StatusCode.Content) { Token = request.Token }; + first.SetPayload(new byte[16], MediaType.ApplicationOctetStream); + first.SetBlock2(0, true, 0); + first.Size2Unsigned = size; + layer.ReceiveResponse(next, exchange, first); + + Response last = new Response(StatusCode.Content) { Token = request.Token }; + last.SetPayload(new byte[1], MediaType.ApplicationOctetStream); + last.SetBlock2(0, false, 1); + layer.ReceiveResponse(next, exchange, last); + + Assert.That(next.ReceivedResponse.Size2Unsigned, Is.EqualTo(size)); + Assert.That(next.ReceivedResponse.PayloadSize, Is.EqualTo(17)); + Assert.That(exchange.ResponseBlockStatus, Is.Null); + } + + [Test] + public void OutgoingBlocksCarryUnsignedHints() + { + RecordingLayer next = new RecordingLayer(); + using BlockwiseLayer layer = Layer(); + Request request = Request.NewPost(); + request.SetPayload(new byte[32], MediaType.ApplicationOctetStream); + request.Size1Unsigned = UInt32.MaxValue; + Exchange upload = new Exchange(request, Origin.Local) { Request = request }; + layer.SendRequest(next, upload, request); + Assert.That(next.SentRequest.Size1Unsigned, Is.EqualTo(UInt32.MaxValue)); + + Request get = Request.NewGet(); + Exchange download = new Exchange(get, Origin.Remote) { Request = get }; + Response response = new Response(StatusCode.Content); + response.SetPayload(new byte[32], MediaType.ApplicationOctetStream); + response.Size2Unsigned = UInt32.MaxValue; + layer.SendResponse(next, download, response); + Assert.That(next.SentResponse.Size2Unsigned, Is.EqualTo(UInt32.MaxValue)); + } + + private static BlockwiseLayer Layer() => new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16, + BlockwiseStatusLifetime = 10000 + }); + + private sealed class RecordingLayer : INextLayer + { + public Request ReceivedRequest { get; private set; } + public Response ReceivedResponse { get; private set; } + public Request SentRequest { get; private set; } + public Response SentResponse { get; private set; } + public void SendRequest(Exchange exchange, Request request) => SentRequest = request; + public void SendResponse(Exchange exchange, Response response) => SentResponse = response; + public void SendEmptyMessage(Exchange exchange, EmptyMessage message) { } + public void ReceiveRequest(Exchange exchange, Request request) => ReceivedRequest = request; + public void ReceiveResponse(Exchange exchange, Response response) => ReceivedResponse = response; + public void ReceiveEmptyMessage(Exchange exchange, EmptyMessage message) { } + } + } +} diff --git a/CoAP.Test/UnsignedOptionHostingTest.cs b/CoAP.Test/UnsignedOptionHostingTest.cs new file mode 100644 index 0000000..ab32df5 --- /dev/null +++ b/CoAP.Test/UnsignedOptionHostingTest.cs @@ -0,0 +1,81 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Threading.Tasks; +using CoAP.Server.Routing; +using Microsoft.Extensions.DependencyInjection; +using NUnit.Framework; + +namespace CoAP +{ + [TestFixture] + public sealed class UnsignedOptionHostingTest + { + [TestCase(false, 0U)] + [TestCase(false, 2147483647U)] + [TestCase(false, 2147483648U)] + [TestCase(false, UInt32.MaxValue)] + [TestCase(true, 0U)] + [TestCase(true, 2147483647U)] + [TestCase(true, 2147483648U)] + [TestCase(true, UInt32.MaxValue)] + public async Task ResourceActionReceivesFullUnsignedSize1Range(bool generated, uint value) + { + Request request = Request.NewPost(); + request.ID = 1; + request.Token = Array.Empty(); + request.SetBlock1(0, false, 0); + request.AddOption(Option.Create(OptionType.Size1, value)); + // A Size2 request asks for an estimate and MUST have value zero. + request.AddOption(Option.Create(OptionType.Size2, 0U)); + Request decoded = (Request)Spec.Decode(Spec.Encode(request)); + + string result = await Invoke(generated, decoded.GetOptions().ToArray()); + + string expected = value.ToString(CultureInfo.InvariantCulture); + Assert.That(result, Is.EqualTo(expected + "/0")); + } + + [TestCase(false)] + [TestCase(true)] + public async Task MissingSizesRemainNullable(bool generated) + { + Assert.That(await Invoke(generated, Array.Empty