Properly print arbitrary strings as valid JSON.#1362
Properly print arbitrary strings as valid JSON.#1362emanuele6 wants to merge 1 commit intobaskerville:masterfrom
Conversation
|
This patch simply prints all the (C locale) control characters as We could print these special sequences when possible if we want, but it is not necessary. (passing the JSON through Here is a possible implementation if we want to do it: #define SPECIAL_SEQUENCE(f, c, json) \
case c: \
fputs(json, f); \
continue;
void print_string_as_json(FILE *f, char *str)
{
fputc('"', f);
for (char *ptr = str; *ptr != '\0'; ++ptr) {
switch (*ptr) {
SPECIAL_SEQUENCE(f, '"', "\\\"")
SPECIAL_SEQUENCE(f, '\\', "\\\\")
SPECIAL_SEQUENCE(f, '\b', "\\b")
SPECIAL_SEQUENCE(f, '\f', "\\f")
SPECIAL_SEQUENCE(f, '\n', "\\n")
SPECIAL_SEQUENCE(f, '\r', "\\r")
SPECIAL_SEQUENCE(f, '\t', "\\t")
}
if (*ptr == '\x7f' || (*ptr >= '\x01' && *ptr <= '\x1f')) {
fprintf(f, "\\u%04x", *ptr);
continue;
}
fputc(*ptr, f);
}
fputc('"', f);
}
#undef SPECIAL_SEQUENCE |
eae9899 to
3c56412
Compare
..instead of injecting them in the output between a pair of `"`
charcters.
This prevents windows with a `"` character in their class or instance
name, or desktop and monitors with `"` character in their name from
generating invalid or "malicious" JSON.
The main problems that this was causing were:
* JSON tools like jq were not able to parse the JSON output of
"query -T" and "wm -d";
* if the JSON was invalid (e.g. one extra quote or `\` at the end of
desktop name), bspwm would not adopt orphans after a "wm -r" command;
* if the arbitrary strings contained JSON code: e.g.
bspc desktop -n '","name":"hello'
the JSON will be interpreted by bspwm after a reload. (in the example
above, that desktop will be renamed to "hello" after a reload.)
3c56412 to
97438ef
Compare
|
I just realised that |

..instead of injecting them in the output between a pair of '"' charcters.
This prevents windows with a
"character in their class or instance name (e.g.urxvt -name 'quote "'), or desktop and monitors with"character in their name from generating invalid or "malicious" JSON.The main problems that this was causing were:
JSON tools like
jqwere not able to parse the JSON output of "query -T" and "wm -d";if the JSON was invalid (e.g. one extra quote or
\at the end of desktop name), bspwm would not adopt orphans after a "wm -r" command.if the arbitrary strings contained JSON code: e.g.
bspc desktop -n '","name":"hello'the JSON will be interpreted by bspwm after a reload. (in the example above, that desktop will be renamed to "hello" after a reload.)