Skip to content

Commit dae49eb

Browse files
committed
Improve bin/ext printer for unprintable characters.
msgpack_object_print used fwrite to write binary data to a stream. The intention of the function is to produce a human-readable representation of the object for debugging purposes. Having arbitrary data dumped as is can cause issues with terminals that interpret it as control sequences. This change prints printable characters as is and unprintable characters as hex-escapes ("\xNN"). Note that UTF-8 encoded characters will now be printed as escaped sequence of UTF-8 bytes. This is an acceptable compromise, as doing otherwise would require a light form of UTF-8 decoding and BIN-typed objects should not be used to transport UTF-8 strings anyway (STR should be used instead).
1 parent 4218128 commit dae49eb

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/objectc.c

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
*/
1010
#include "msgpack/object.h"
1111
#include "msgpack/pack.h"
12+
#include <ctype.h>
1213
#include <stdio.h>
1314
#include <string.h>
1415

@@ -112,6 +113,21 @@ int msgpack_pack_object(msgpack_packer* pk, msgpack_object d)
112113
}
113114

114115

116+
static void msgpack_object_bin_print(FILE* out, const char *ptr, size_t size)
117+
{
118+
size_t i;
119+
for (i = 0; i < size; i++) {
120+
if (ptr[i] == '"') {
121+
fputs("\\\"", out);
122+
} else if (isprint(ptr[i])) {
123+
fputc(ptr[i], out);
124+
} else {
125+
fprintf(out, "\\x%02x", (unsigned char)ptr[i]);
126+
}
127+
}
128+
}
129+
130+
115131
void msgpack_object_print(FILE* out, msgpack_object o)
116132
{
117133
switch(o.type) {
@@ -159,7 +175,7 @@ void msgpack_object_print(FILE* out, msgpack_object o)
159175

160176
case MSGPACK_OBJECT_BIN:
161177
fprintf(out, "\"");
162-
fwrite(o.via.bin.ptr, o.via.bin.size, 1, out);
178+
msgpack_object_bin_print(out, o.via.bin.ptr, o.via.bin.size);
163179
fprintf(out, "\"");
164180
break;
165181

@@ -170,7 +186,7 @@ void msgpack_object_print(FILE* out, msgpack_object o)
170186
fprintf(out, "(ext: %d)", (int)o.via.ext.type);
171187
#endif
172188
fprintf(out, "\"");
173-
fwrite(o.via.ext.ptr, o.via.ext.size, 1, out);
189+
msgpack_object_bin_print(out, o.via.ext.ptr, o.via.ext.size);
174190
fprintf(out, "\"");
175191
break;
176192

0 commit comments

Comments
 (0)