Skip to contentSkip to conversation

docparse: Handle special characters in JSON

PATCH New Petr Vorel 2 participants 6 messages May 6, 2021 – May 7, 2021

lore
Share & tools
lore

Petr Vorel

author
#0 lore raw

PATCH v4 1/1 docparse: Handle special characters in JSON

* escape backslash (/) and double quote (")
escaping backslash effectively escapes other C escaped strings (\t, \n, ...), which we sometimes want (in the comment) but sometimes not (in .option we want to have them interpreted)
* replace tab with 8x space
* skip and TWARN invalid chars (< 0x20, i.e. anything before space) defined by RFC 8259 (https://tools.ietf.org/html/rfc8259#page-9)

NOTE: atm fix is required only for ", but tab was problematic in the past.

TODO: This is just a "hot fix" solution before release. Proper solution would be to check if chars needed to be escaped (", \, /) aren't already escaped.

Also for correct decision whether \n, \t should be escaped or interpreted we should decide in the parser which has the context. C string should be probably interpreted (thus nothing needed to be done as it escapes in a compatible way with JSON), but comments probably should display \n, \t thus add extra \.

Fixes c39b29f0a ("bpf: Check truncation on 32bit div/mod by zero")
---
 docparse/data_storage.h | 36 +++++++++++++++++++++++++++++++++++-
 1 file changed, 35 insertions(+), 1 deletion(-)
docparse/data_storage.h +35 -1
index ef420c08f..9f36dd6f0 100644
@@ -256,6 +256,40 @@ static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ...
 	va_end(va);
 }
 
+
+static inline void data_fprintf_esc(FILE *f, unsigned int padd, const char *str)
+{
+	while (padd-- > 0)
+		fputc(' ', f);
+
+	fputc('"', f);
+
+	while (*str) {
+		switch (*str) {
+		case '\\':
+			fputs("\\\\", f);
+			break;
+		case '"':
+			fputs("\\\"", f);
+			break;
+		case '\t':
+			fputs("        ", f);
+			break;
+		default:
+			/* RFC 8259 specify  chars before 0x20 as invalid */
+			if (*str >= 0x20)
+				putc(*str, f);
+			else
+				fprintf(stderr, "%s:%d %s(): invalid character for JSON: %x\n",
+						__FILE__, __LINE__, __func__, *str);
+			break;
+		}
+		str++;
+	}
+
+	fputc('"', f);
+}
+
 static inline void data_to_json_(struct data_node *self, FILE *f, unsigned int padd, int do_padd)
 {
 	unsigned int i;
@@ -263,7 +297,7 @@ static inline void data_to_json_(struct data_node *self, FILE *f, unsigned int p
 	switch (self->type) {
 	case DATA_STRING:
 		padd = do_padd ? padd : 0;
-		data_fprintf(f, padd, "\"%s\"", self->string.val);
+		data_fprintf_esc(f, padd, self->string.val);
 	break;
 	case DATA_HASH:
 		for (i = 0; i < self->hash.elems_used; i++) {
Signature · 1 line
2.31.1
#1 lore raw

PATCH v4 1/1 docparse: Handle special characters in JSON

Hi!

Quoted 1 line

* escape backslash (/) and double quote (")

                      ^
		      \
Quoted 5 lines

escaping backslash effectively escapes other C escaped strings (\t, \n, ...), which we sometimes want (in the comment) but sometimes not (in .option we want to have them interpreted)
* replace tab with 8x space
* skip and TWARN invalid chars (< 0x20, i.e. anything before space)

^
warn on? We are not actually using TWARN o here right?

Quoted 28 lines

defined by RFC 8259 (https://tools.ietf.org/html/rfc8259#page-9)

NOTE: atm fix is required only for ", but tab was problematic in the past.

TODO: This is just a "hot fix" solution before release. Proper solution would be to check if chars needed to be escaped (", \, /) aren't already escaped.

Also for correct decision whether \n, \t should be escaped or interpreted we should decide in the parser which has the context. C string should be probably interpreted (thus nothing needed to be done as it escapes in a compatible way with JSON), but comments probably should display \n, \t thus add extra \.

Fixes c39b29f0a ("bpf: Check truncation on 32bit div/mod by zero")
---
 docparse/data_storage.h | 36 +++++++++++++++++++++++++++++++++++-
 1 file changed, 35 insertions(+), 1 deletion(-)
docparse/data_storage.h +0 -0
index ef420c08f..9f36dd6f0 100644

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 265

Quoted 10 lines
docparse/data_storage.h +7 -0
@@ -256,6 +256,40 @@ static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ...
 	va_end(va);
 }
 
+
+static inline void data_fprintf_esc(FILE *f, unsigned int padd, const char *str)
+{
+	while (padd-- > 0)
+		fputc(' ', f);
+
+	fputc('"', f);
	int was_backslash = 0;

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 273

Quoted 6 lines
docparse/data_storage.h +6 -0
+	while (*str) {
+		switch (*str) {
+		case '\\':
+		break;
+		case '"':
+			fputs("\\\"", f);
			was_backslash = 0;

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 286

Quoted 13 lines
docparse/data_storage.h +13 -0
+			break;
+		case '\t':
+			fputs("        ", f);
+			break;
+		default:
+			/* RFC 8259 specify  chars before 0x20 as invalid */
+			if (*str >= 0x20)
+				putc(*str, f);
+			else
+				fprintf(stderr, "%s:%d %s(): invalid character for JSON: %x\n",
+						__FILE__, __LINE__, __func__, *str);
+			break;
+		}
		if (was_backslash)
			fputs("\\\\", f);

		was_backslash = (*str == '\\');

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 291

Quoted 5 lines
docparse/data_storage.h +5 -0
+		str++;
+	}
+
+	fputc('"', f);
+}

This should avoid "unescaping" an escaped double quote. We deffer printing the backslash until we know the character after it and we make sure that we do not excape backslash before ".

Consider what would happen if someone did put a "\"text\"" into options strings, the original code would escape the backslashes and we would end up with "\\"text"\\" which would break parser again.

This way we can at least avoid parsing errors until we fix the problem one level down in the parser where we have the context required for a proper fix.

Quoted 15 lines
docparse/data_storage.h +1 -1
 static inline void data_to_json_(struct data_node *self, FILE *f, unsigned int padd, int do_padd)
 {
 	unsigned int i;
@@ -263,7 +297,7 @@ static inline void data_to_json_(struct data_node *self, FILE *f, unsigned int p
 	switch (self->type) {
 	case DATA_STRING:
 		padd = do_padd ? padd : 0;
-		data_fprintf(f, padd, "\"%s\"", self->string.val);
+		data_fprintf_esc(f, padd, self->string.val);
 	break;
 	case DATA_HASH:
 		for (i = 0; i < self->hash.elems_used; i++) {
Signature · 1 line
2.31.1
Signature · 2 lines
Cyril Hrubis
[email protected]
author
#2 lore raw

PATCH v4 1/1 docparse: Handle special characters in JSON

Hi Cyril,

Quoted 4 lines

Hi!

Quoted 1 line

* escape backslash (/) and double quote (")

                      ^
		      \

+1

Quoted 7 lines
Quoted 5 lines

escaping backslash effectively escapes other C escaped strings (\t, \n, ...), which we sometimes want (in the comment) but sometimes not (in .option we want to have them interpreted)
* replace tab with 8x space
* skip and TWARN invalid chars (< 0x20, i.e. anything before space)

^
warn on? We are not actually using TWARN o here right?

Yep, I didn't update commit message (first I included tst_test.h with TST_NO_DEFAULT_MAIN but there was missing include path => stderr is enough).

Quoted 76 lines
Quoted 28 lines

defined by RFC 8259 (https://tools.ietf.org/html/rfc8259#page-9)

NOTE: atm fix is required only for ", but tab was problematic in the past.

TODO: This is just a "hot fix" solution before release. Proper solution would be to check if chars needed to be escaped (", \, /) aren't already escaped.

Also for correct decision whether \n, \t should be escaped or interpreted we should decide in the parser which has the context. C string should be probably interpreted (thus nothing needed to be done as it escapes in a compatible way with JSON), but comments probably should display \n, \t thus add extra \.

Fixes c39b29f0a ("bpf: Check truncation on 32bit div/mod by zero")
---
 docparse/data_storage.h | 36 +++++++++++++++++++++++++++++++++++-
 1 file changed, 35 insertions(+), 1 deletion(-)
docparse/data_storage.h +0 -0
index ef420c08f..9f36dd6f0 100644

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 265

Quoted 10 lines
docparse/data_storage.h +7 -0
@@ -256,6 +256,40 @@ static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ...
 	va_end(va);
 }
 
+
+static inline void data_fprintf_esc(FILE *f, unsigned int padd, const char *str)
+{
+	while (padd-- > 0)
+		fputc(' ', f);
+
+	fputc('"', f);
	int was_backslash = 0;

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 273

Quoted 6 lines
docparse/data_storage.h +6 -0
+	while (*str) {
+		switch (*str) {
+		case '\\':
+		break;
+		case '"':
+			fputs("\\\"", f);
			was_backslash = 0;

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 286

Quoted 13 lines
docparse/data_storage.h +13 -0
+			break;
+		case '\t':
+			fputs("        ", f);
+			break;
+		default:
+			/* RFC 8259 specify  chars before 0x20 as invalid */
+			if (*str >= 0x20)
+				putc(*str, f);
+			else
+				fprintf(stderr, "%s:%d %s(): invalid character for JSON: %x\n",
+						__FILE__, __LINE__, __func__, *str);
+			break;
+		}
		if (was_backslash)
			fputs("\\\\", f);

		was_backslash = (*str == '\\');

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 291

Quoted 5 lines
docparse/data_storage.h +5 -0
+		str++;
+	}
+
+	fputc('"', f);
+}

This should avoid "unescaping" an escaped double quote. We deffer printing the backslash until we know the character after it and we make sure that we do not excape backslash before ".

Quoted 7 lines

Consider what would happen if someone did put a "\"text\"" into options strings, the original code would escape the backslashes and we would end up with "\\"text"\\" which would break parser again.

This way we can at least avoid parsing errors until we fix the problem one level down in the parser where we have the context required for a proper fix.

+1.

I'll test it and merge under your as it's basically your work :). Thanks!

Kind regards,
Petr

author
#3 lore raw

PATCH v4 1/1 docparse: Handle special characters in JSON

In reply to Cyril Hrubis

Hi Cyril,

Looking at your code, I'm not sure if it's needed.

Quoted 44 lines

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 265

Quoted 6 lines
docparse/data_storage.h +6 -0
+static inline void data_fprintf_esc(FILE *f, unsigned int padd, const char *str)
+{
+	while (padd-- > 0)
+		fputc(' ', f);
+
+	fputc('"', f);
	int was_backslash = 0;

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 273

Quoted 6 lines
docparse/data_storage.h +6 -0
+	while (*str) {
+		switch (*str) {
+		case '\\':
+		break;
+		case '"':
+			fputs("\\\"", f);
			was_backslash = 0;

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 286

Quoted 13 lines
docparse/data_storage.h +13 -0
+			break;
+		case '\t':
+			fputs("        ", f);
+			break;
+		default:
+			/* RFC 8259 specify  chars before 0x20 as invalid */
+			if (*str >= 0x20)
+				putc(*str, f);
+			else
+				fprintf(stderr, "%s:%d %s(): invalid character for JSON: %x\n",
+						__FILE__, __LINE__, __func__, *str);
+			break;
+		}
		if (was_backslash)
			fputs("\\\\", f);

		was_backslash = (*str == '\\');

docparse/data_storage.h static inline void data_fprintf(FILE *f, unsigned int padd, const char *fmt, ... · line 291

Quoted 5 lines
docparse/data_storage.h +5 -0
+		str++;
+	}
+
+	fputc('"', f);
+}

This should avoid "unescaping" an escaped double quote. We deffer printing the backslash until we know the character after it and we make sure that we do not excape backslash before ".

Quoted 7 lines

Consider what would happen if someone did put a "\"text\"" into options strings, the original code would escape the backslashes and we would end up with "\\"text"\\" which would break parser again.

This way we can at least avoid parsing errors until we fix the problem one level down in the parser where we have the context required for a proper fix.

It looks to me it it works exactly the same with and w/a was_backslash.

Trying to escape \" will results in first escape \ (=> \\), then " (=> \")

Example C code:

/*\
* [Description]
* "expected" \\ behaviour "\"text\""
*/

static struct tst_test test = {
	.options = (struct tst_option[]) {
		{"a:", &can_dev_name, "\"text \\ \""},
		{}
	},
};

results from both original code and your with was_backslash are valid JSON, but was_backslash add extra backslashes.

result from original code:

  "testfile": {
   "options": [
     [
      "a:",
      "can_dev_name",
      "\\\"text \\\\ \\\""
     ]
    ],
   "doc": [
     "[Description]",
     "\"expected\" \\\\ behaviour \"\\\"text\\\"\""
    ],
   "fname": "testfile.c"
  }

result from was_backslash:
"testfile": {
"options": [

     [
      "a:",
      "can_dev_name",
      "\\\"text \\\\\\ \\\\\""
     ]
    ],
   "doc": [
     "[Description]",
     "\"expected\" \\\\\\ \\behaviour \"\\\"text\\\"\""
    ],

"fname": "testfile.c"
}

What am I missing?

Kind regards,
Petr

#4 lore raw

PATCH v4 1/1 docparse: Handle special characters in JSON

Hi!

Quoted 1 line

What am I missing?

Nothing I got confused again and the original code works fine, just produces ugly output as you described.

Signature · 2 lines
Cyril Hrubis
[email protected]
author
#5 lore raw

PATCH v4 1/1 docparse: Handle special characters in JSON

Hi Cyril,

Quoted 5 lines

Hi!

Quoted 1 line

What am I missing?

Nothing I got confused again and the original code works fine, just produces ugly output as you described.

OK, pushed original version. Travis should be fixed now and we have TODO after release :).

Kind regards,
Petr