mirror of
https://github.com/meshcore-dev/MeshCore.git
synced 2026-09-21 16:06:51 +00:00
Ensure command buffers stay NUL-terminated to prevent overflow
The serial command buffers must stay NUL-terminated within their bounds: if they ever aren't, strlen() can return >= sizeof(command) and the read loop would index past the buffer. Additionally, a full buffer now becomes a completed line (end-of-line marker placed inside the buffer, NUL terminator kept) instead of overwriting the terminator and silently corrupting the buffer for the next pass. Applies to the serial CLI readers of the repeater, room server, sensor and secure chat examples, and to the CLI rescue reader of the companion example.
This commit is contained in:
@@ -122,6 +122,13 @@ void setup() {
|
||||
|
||||
void loop() {
|
||||
int len = strlen(command);
|
||||
// `command` must stay NUL-terminated within its bounds. If it ever isn't,
|
||||
// strlen() above can return >= sizeof(command) and the loop below would then
|
||||
// index past the buffer, so clamp defensively.
|
||||
if (len >= (int)sizeof(command)) {
|
||||
command[0] = 0;
|
||||
len = 0;
|
||||
}
|
||||
while (Serial.available() && len < sizeof(command)-1) {
|
||||
char c = Serial.read();
|
||||
if (c != '\n') {
|
||||
@@ -130,8 +137,9 @@ void loop() {
|
||||
}
|
||||
Serial.print(c);
|
||||
}
|
||||
if (len == sizeof(command)-1) { // command buffer full
|
||||
command[sizeof(command)-1] = '\r';
|
||||
if (len == sizeof(command)-1) { // buffer full: treat as a completed line
|
||||
command[sizeof(command)-2] = '\r'; // place end-of-line marker inside the buffer
|
||||
command[sizeof(command)-1] = 0; // keep the buffer NUL-terminated
|
||||
}
|
||||
|
||||
if (len > 0 && command[len - 1] == '\r') { // received complete line
|
||||
|
||||
Reference in New Issue
Block a user