Skip to content

Commit

Permalink
Fixes #585 MessageId not limited to 65535
Browse files Browse the repository at this point in the history
Message ID should always be in the range 1 - 65535. This adds a test,
and, and resets the counter to 1 when needed.
  • Loading branch information
hylkevds committed May 9, 2021
1 parent f6f3f6e commit 3692323
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
17 changes: 16 additions & 1 deletion broker/src/main/java/io/moquette/broker/MQTTConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,22 @@ public void resendNotAckedPublishes() {
}

int nextPacketId() {
return lastPacketId.incrementAndGet();
final int next = lastPacketId.incrementAndGet();
if (next <= 65_535) {
return next;
}
return resetPacketId();
}

private int resetPacketId() {
synchronized(lastPacketId) {
if (lastPacketId.get() <= 65_535) {
// Another thread reset it before us...
return lastPacketId.incrementAndGet();
}
lastPacketId.set(1);
return 1;
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -319,4 +319,13 @@ public void testForceClientDisconnection_issue116() {
assertFalse(channel.isOpen(), "First 'FAKE_CLIENT_ID' channel MUST be closed by the broker");
assertTrue(anotherChannel.isOpen(), "Second 'FAKE_CLIENT_ID' channel MUST be still open");
}

@Test
public void testMessageIdGeneration() {
for (int i = 0; i < 65_536; i++) {
int nextPacketId = sut.nextPacketId();
assertTrue(nextPacketId > 0, "Packet ID must be > 0");
assertTrue(nextPacketId <= 65_535, "Packet ID must be <= 65_535");
}
}
}

0 comments on commit 3692323

Please sign in to comment.