Skip to content

Commit 4eeffda

Browse files
Fuslmadolson
andauthored
Properly escape double quotes and backslash in sdscatrepr (#2036)
Fixes #2035, a bug introduced in #1342 --------- Signed-off-by: Fusl <fusl@meo.ws> Signed-off-by: Madelyn Olson <madelyneolson@gmail.com> Co-authored-by: Madelyn Olson <madelyneolson@gmail.com>
1 parent dd772c4 commit 4eeffda

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/sds.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -952,9 +952,12 @@ sds sdscatrepr(sds s, const char *p, size_t len) {
952952
s = sdsMakeRoomFor(s, len + 2);
953953
s = sdscatlen(s, "\"", 1);
954954
while (len) {
955-
if (isprint(*p)) {
955+
/* The condition here in combination with the loop inside ensures we're calling sdscatlen only once for an
956+
* entire string chunk rather than calling it for every character. This reduces the amount of memcpy calls.
957+
* \ and " are valid isprint characters but we need to handle them in the else block below to escape them. */
958+
if (isprint(*p) && *p != '\\' && *p != '"') {
956959
const char *start = p;
957-
while (len && isprint(*p)) {
960+
while (len && isprint(*p) && *p != '\\' && *p != '"') {
958961
len--;
959962
p++;
960963
}

tests/unit/introspection.tcl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,15 @@ start_server {tags {"introspection"}} {
678678
set _ $res
679679
} {*"set" "foo"*"get" "foo"*}
680680

681+
test {MONITOR properly escapes special characters through sdscatrepr} {
682+
set rd [valkey_deferring_client]
683+
$rd monitor
684+
assert_match {*OK*} [$rd read]
685+
r echo "backslash\\quotes\"newline\ncarriagereturn\rtab\talert\abackspace\bhexnormal\x7Ahexspecial\x7F"
686+
assert_match {*"echo" "backslash\\\\quotes\\"newline\\ncarriagereturn\\rtab\\talert\\abackspace\\bhexnormalzhexspecial\\x7f"*} [$rd read]
687+
$rd close
688+
}
689+
681690
test {MONITOR can log commands issued by the scripting engine} {
682691
set rd [valkey_deferring_client]
683692
$rd monitor

0 commit comments

Comments
 (0)