Skip to content

Commit 7d11db8

Browse files
authored
Merge pull request DeusData#527 from Ravandevil25/fix/json-escape
fix(foundation): properly escape JSON control characters as \u00XX
2 parents 1c3c557 + 078e9e2 commit 7d11db8

3 files changed

Lines changed: 21 additions & 3 deletions

File tree

‎src/foundation/str_util.c‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include "foundation/constants.h"
77
#include <string.h>
88
#include <ctype.h>
9+
#include <stdio.h>
910

1011
enum {
1112
JSON_ESC_LEN = 2, /* escaped char takes 2 bytes (backslash + char) */
@@ -328,8 +329,11 @@ int cbm_json_escape(char *buf, int bufsize, const char *src) {
328329
buf[pos++] = '\\';
329330
buf[pos++] = 't';
330331
} else if (c < JSON_CTRL_LIMIT) {
331-
/* Other control chars: skip */
332-
continue;
332+
/* Other control chars: escape as \u00XX */
333+
if (pos + 6 > bufsize - JSON_NUL_RESERVE) {
334+
break;
335+
}
336+
pos += snprintf(buf + pos, 7, "\\u%04x", c);
333337
} else {
334338
buf[pos++] = (char)c;
335339
}

‎src/git/git_context.c‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,7 @@ static int json_escaped_len(const char *src) {
316316
if (c == '"' || c == '\\' || c == '\n' || c == '\r' || c == '\t') {
317317
len += 2;
318318
} else if (c < 0x20) {
319-
continue;
319+
len += 6; /* \u00XX */
320320
} else {
321321
len++;
322322
}

‎tests/test_str_util.c‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,18 @@ TEST(validate_shell_arg_spaces) {
424424
PASS();
425425
}
426426

427+
/* ── JSON Escaping tests ──────────────────────────────────────── */
428+
429+
TEST(json_escape_control_chars) {
430+
char buf[64];
431+
const char *input = "A\x01"
432+
"B\n";
433+
int len = cbm_json_escape(buf, sizeof(buf), input);
434+
ASSERT_STR_EQ(buf, "A\\u0001B\\n");
435+
ASSERT_EQ(len, 10);
436+
PASS();
437+
}
438+
427439
/* ── SNPRINTF_APPEND tests ────────────────────────────────────── */
428440

429441
TEST(snprintf_append_basic) {
@@ -533,6 +545,8 @@ SUITE(str_util) {
533545
RUN_TEST(validate_shell_arg_backslash);
534546
RUN_TEST(validate_shell_arg_empty);
535547
RUN_TEST(validate_shell_arg_spaces);
548+
/* JSON Escaping */
549+
RUN_TEST(json_escape_control_chars);
536550
/* SNPRINTF_APPEND */
537551
RUN_TEST(snprintf_append_basic);
538552
RUN_TEST(snprintf_append_fills_exactly);

0 commit comments

Comments
 (0)