Skip to content

Commit 323a5f5

Browse files
authored
MqttMsgBase - implement mqtt message length requirements (2.2.3 Remaining Length)
1 parent e6ad811 commit 323a5f5

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

M2Mqtt/Exceptions/MqttClientException.cs

+7-1
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,12 @@ public enum MqttClientErrorCode
127127
/// <summary>
128128
/// Invalid protocol name
129129
/// </summary>
130-
InvalidProtocolName
130+
InvalidProtocolName,
131+
132+
// [v3.1.1]
133+
/// <summary>
134+
/// Invalid message length
135+
/// </summary>
136+
InvalidLength
131137
}
132138
}

M2Mqtt/Messages/MqttMsgBase.cs

+8
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,9 @@ protected int encodeRemainingLength(int remainingLength, byte[] buffer, int inde
174174
digit = digit | 0x80;
175175
buffer[index++] = (byte)digit;
176176
} while (remainingLength > 0);
177+
178+
if (index > 4) // 4 bytes [0..3] is the maximum allowed (2.2.3 Remaining Length)
179+
throw new MqttClientException(MqttClientErrorCode.InvalidLength);
177180
return index;
178181
}
179182

@@ -188,13 +191,18 @@ protected static int decodeRemainingLength(IMqttNetworkChannel channel)
188191
int value = 0;
189192
int digit = 0;
190193
byte[] nextByte = new byte[1];
194+
int index = 0;
191195
do
192196
{
193197
// next digit from stream
194198
channel.Receive(nextByte);
195199
digit = nextByte[0];
196200
value += ((digit & 127) * multiplier);
197201
multiplier *= 128;
202+
++index;
203+
204+
if (index > 4) // 4 bytes [0..3] is the maximum allowed (2.2.3 Remaining Length)
205+
throw new MqttClientException(MqttClientErrorCode.InvalidLength);
198206
} while ((digit & 128) != 0);
199207
return value;
200208
}

0 commit comments

Comments
 (0)