Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MqttMsgBase - implement mqtt message length requirements (2.2.3 Remaining Length) #146

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
8 changes: 7 additions & 1 deletion M2Mqtt/Exceptions/MqttClientException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,12 @@ public enum MqttClientErrorCode
/// <summary>
/// Invalid protocol name
/// </summary>
InvalidProtocolName
InvalidProtocolName,

// [v3.1.1]
/// <summary>
/// Invalid message length
/// </summary>
InvalidLength
}
}
8 changes: 8 additions & 0 deletions M2Mqtt/Messages/MqttMsgBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -188,13 +191,18 @@ 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
channel.Receive(nextByte);
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;
}
Expand Down