Add validation for topics before publishing.

This commit is contained in:
Christian Kratky
2019-03-22 20:37:14 +01:00
parent 673fc5e20c
commit 7c3d88f62d
9 changed files with 84 additions and 9 deletions
@@ -127,6 +127,8 @@ namespace MQTTnet.Extensions.ManagedClient
{
if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
MqttTopicValidator.ThrowIfInvalid(applicationMessage.ApplicationMessage.Topic);
ManagedMqttApplicationMessage removedMessage = null;
ApplicationMessageSkippedEventArgs applicationMessageSkippedEventArgs = null;
+2
View File
@@ -166,6 +166,8 @@ namespace MQTTnet.Client
{
if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
MqttTopicValidator.ThrowIfInvalid(applicationMessage.Topic);
ThrowIfNotConnected();
var publishPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePublishPacket(applicationMessage);
@@ -74,8 +74,11 @@ namespace MQTTnet.Internal
Task winner;
if (timeout == Timeout.InfiniteTimeSpan)
{
await tcs.Task.ConfigureAwait(false);
winner = tcs.Task;
using (cancellationToken.Register(() => { tcs.TrySetCanceled(); }))
{
await tcs.Task.ConfigureAwait(false);
winner = tcs.Task;
}
}
else
{
@@ -122,7 +125,7 @@ namespace MQTTnet.Internal
}
}
toRelease?.SetResult(true);
toRelease?.TrySetResult(true);
}
}
}
@@ -0,0 +1,25 @@
using MQTTnet.Exceptions;
namespace MQTTnet.Protocol
{
public static class MqttTopicValidator
{
public static void ThrowIfInvalid(string topic)
{
if (string.IsNullOrEmpty(topic))
{
throw new MqttProtocolViolationException("Topic should not be empty.");
}
if (topic.Contains("+"))
{
throw new MqttProtocolViolationException("The character '+' is not allowed in topics.");
}
if (topic.Contains("#"))
{
throw new MqttProtocolViolationException("The character '#' is not allowed in topics.");
}
}
}
}
+3
View File
@@ -7,6 +7,7 @@ using MQTTnet.Adapter;
using MQTTnet.Client.Publishing;
using MQTTnet.Client.Receiving;
using MQTTnet.Diagnostics;
using MQTTnet.Protocol;
using MQTTnet.Server.Status;
namespace MQTTnet.Server
@@ -101,6 +102,8 @@ namespace MQTTnet.Server
{
if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
MqttTopicValidator.ThrowIfInvalid(applicationMessage.Topic);
if (_cancellationTokenSource == null) throw new InvalidOperationException("The server is not started.");
_clientSessionsManager.DispatchApplicationMessage(applicationMessage, null);