fix scan parse buf

This commit is contained in:
denniszgyu 2026-01-15 14:26:21 +08:00
parent b059744c5f
commit 83e887fc77

View File

@ -841,12 +841,28 @@ void Handler::handleResponse(ConnectConnection* s, Request* req, Response* res)
}
} else if (req->type() == Command::Scan && s && res->type() == Reply::Array) {
SegmentStr<64> str(res->body());
if (const char* p = strchr(str.data() + sizeof("*2\r\n$"), '\n')) {
// SCAN response format: *2\r\n$<len>\r\n<cursor>\r\n*<count>\r\n...
// Skip "*2\r\n$" (5 bytes) and find the first '\n' after the length number
// Add boundary check to prevent buffer overflow
const char* start = str.data();
int len = str.length();
if (len >= 5) {
const char* end = start + len;
const char* p = start + 5; // Skip "*2\r\n$" (5 bytes, not sizeof which returns 8!)
// Find '\n' within buffer boundary (safer than strchr)
while (p < end && *p != '\n') {
p++;
}
if (p < end) { // Found '\n'
// Use 128-bit integer to handle large cursor values (Kvrocks may return cursor close to 64-bit limit)
__uint128_t cursor = 0;
const char* cursorStr = p + 1;
const char* cursorStart = cursorStr;
while (*cursorStr >= '0' && *cursorStr <= '9') {
// Parse cursor digits within buffer boundary
while (cursorStr < end && *cursorStr >= '0' && *cursorStr <= '9') {
cursor = cursor * 10 + (*cursorStr - '0');
cursorStr++;
}
@ -868,7 +884,14 @@ void Handler::handleResponse(ConnectConnection* s, Request* req, Response* res)
// Use 128-bit integer for left shift, will not overflow
cursor <<= Const::ServGroupBits;
cursor |= g->id();
if ((p = strchr(p, '*')) != nullptr) {
// Find '*' within buffer boundary
const char* asteriskPos = p + 1;
while (asteriskPos < end && *asteriskPos != '*') {
asteriskPos++;
}
if (asteriskPos < end) { // Found '*'
// Convert 128-bit integer to string
char buf[64]; // 128-bit needs at most 39 decimal digits
int n = Util::uint128ToString(cursor, buf);
@ -882,7 +905,7 @@ void Handler::handleResponse(ConnectConnection* s, Request* req, Response* res)
"$%d\r\n"
"%s\r\n",
n, buf);
res->body().cut(p - str.data());
res->body().cut(asteriskPos - start);
}
} else {
// Scan completed, return 0 to client
@ -891,6 +914,7 @@ void Handler::handleResponse(ConnectConnection* s, Request* req, Response* res)
}
}
}
}
if (req->leader()) {
res->adjustForLeader(req);
}