Conversation
…WritePos type for better compatibility
| return false; | ||
| } | ||
| size_t payloadLen = length - payloadOffset; // safe: payloadOffset <= length guaranteed above | ||
| uint8_t* payload = _buffer + payloadOffset; |
There was a problem hiding this comment.
Hmm a bit hard to see by just browsing the code in the browser on GH, but shouldn't here also be some check against _bufferSize
There was a problem hiding this comment.
You are right, I forgot some checks
There was a problem hiding this comment.
No, not at that location handlePacket() can't be called without readPacket(). But I would suggest checking in loop(), with that nothing will ever be read.
There was a problem hiding this comment.
I proposed a solution, could you check if it is ok for you?
hmueller01
left a comment
There was a problem hiding this comment.
A first glimps over the changes ... lots of good stuff, but still a few changes.
src/PubSubClient.cpp
Outdated
| uint16_t payloadOffset = hdrLen + 3 + topicLen; // payload starts after header and topic (if there is no packet identifier) | ||
| size_t payloadLen = length - payloadOffset; // this might change by 2 if we have a QoS 1 or 2 message | ||
| uint8_t* payload = _buffer + payloadOffset; | ||
| size_t payloadOffset = (size_t)hdrLen + 3u + topicLen; // use size_t to avoid uint16_t overflow on large topics |
There was a problem hiding this comment.
Agreed. But please leave the comment.
| size_t payloadOffset = (size_t)hdrLen + 3u + topicLen; // use size_t to avoid uint16_t overflow on large topics | |
| size_t payloadOffset = (size_t)hdrLen + 3u + topicLen; // payload starts after header and topic (if there is no packet identifier) |
src/PubSubClient.cpp
Outdated
| size_t payloadOffset = (size_t)hdrLen + 3u + topicLen; // use size_t to avoid uint16_t overflow on large topics | ||
|
|
||
| if (length < payloadOffset) { // do not move outside the max bufferSize | ||
| // Guard BEFORE computing payloadLen to prevent size_t underflow (payloadOffset > length) |
There was a problem hiding this comment.
Yes, we can do it so. But there will be no exception here. payloadLen might be calculated wrong, but never used.
…h and message ID in PubSubClient
…re adequate buffer size for MQTT packets
…ing buffer safety checks and memory management improvements
c3c8dc0 to
a9abbe0
Compare
Summary
This merge request significantly improves the robustness and safety of the PubSubClient library, without changing its public API or breaking existing usage. All changes are fully covered by the test suite (57/57 tests passing).
Key Fixes
The buffer size and pointer are only updated after a successful allocation. If allocation fails, the previous buffer and size remain unchanged, preventing inconsistent internal state.
Rationale
These changes address potential edge cases that could lead to:
All fixes are implemented with minimal code changes and maintain full backward compatibility.