From ab07ec1a2fbb210a42b5422e5e3a2661eb248f98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Walln=C3=B6fer?= Date: Mon, 3 Mar 2025 11:34:33 +0100 Subject: [PATCH] MqttMsgBase - implement mqtt message length requirements (2.2.3 Remaining Length) --- M2Mqtt/Exceptions/MqttClientException.cs | 8 +++++++- M2Mqtt/Messages/MqttMsgBase.cs | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/M2Mqtt/Exceptions/MqttClientException.cs b/M2Mqtt/Exceptions/MqttClientException.cs index cd8303fc..de2c0156 100644 --- a/M2Mqtt/Exceptions/MqttClientException.cs +++ b/M2Mqtt/Exceptions/MqttClientException.cs @@ -127,6 +127,12 @@ public enum MqttClientErrorCode /// /// Invalid protocol name /// - InvalidProtocolName + InvalidProtocolName, + + // [v3.1.1] + /// + /// Invalid message length + /// + InvalidLength } } diff --git a/M2Mqtt/Messages/MqttMsgBase.cs b/M2Mqtt/Messages/MqttMsgBase.cs index 870fe5fe..bc17bf32 100644 --- a/M2Mqtt/Messages/MqttMsgBase.cs +++ b/M2Mqtt/Messages/MqttMsgBase.cs @@ -174,6 +174,9 @@ protected int encodeRemainingLength(int remainingLength, byte[] buffer, int inde digit = digit | 0x80; buffer[index++] = (byte)digit; } while (remainingLength > 0); + + if (index > 4) // 4 bytes [0..3] is the maximum allowed (2.2.3 Remaining Length) + throw new MqttClientException(MqttClientErrorCode.InvalidLength); return index; } @@ -188,6 +191,7 @@ protected static int decodeRemainingLength(IMqttNetworkChannel channel) int value = 0; int digit = 0; byte[] nextByte = new byte[1]; + int index = 0; do { // next digit from stream @@ -195,6 +199,10 @@ protected static int decodeRemainingLength(IMqttNetworkChannel channel) digit = nextByte[0]; value += ((digit & 127) * multiplier); multiplier *= 128; + ++index; + + if (index > 4) // 4 bytes [0..3] is the maximum allowed (2.2.3 Remaining Length) + throw new MqttClientException(MqttClientErrorCode.InvalidLength); } while ((digit & 128) != 0); return value; }