From 1da0539a0098edbc35854c3513183e4acd72a23f Mon Sep 17 00:00:00 2001 From: iphydf Date: Tue, 5 Jul 2016 20:39:31 +0100 Subject: [PATCH] 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). --- src/objectc.c | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/objectc.c b/src/objectc.c index 72f2ffee..95e05cd3 100644 --- a/src/objectc.c +++ b/src/objectc.c @@ -9,6 +9,7 @@ */ #include "msgpack/object.h" #include "msgpack/pack.h" +#include #include #include @@ -112,6 +113,21 @@ int msgpack_pack_object(msgpack_packer* pk, msgpack_object d) } +static void msgpack_object_bin_print(FILE* out, const char *ptr, size_t size) +{ + size_t i; + for (i = 0; i < size; i++) { + if (ptr[i] == '"') { + fputs("\\\"", out); + } else if (isprint(ptr[i])) { + fputc(ptr[i], out); + } else { + fprintf(out, "\\x%02x", (unsigned char)ptr[i]); + } + } +} + + void msgpack_object_print(FILE* out, msgpack_object o) { switch(o.type) { @@ -159,7 +175,7 @@ void msgpack_object_print(FILE* out, msgpack_object o) case MSGPACK_OBJECT_BIN: fprintf(out, "\""); - fwrite(o.via.bin.ptr, o.via.bin.size, 1, out); + msgpack_object_bin_print(out, o.via.bin.ptr, o.via.bin.size); fprintf(out, "\""); break; @@ -170,7 +186,7 @@ void msgpack_object_print(FILE* out, msgpack_object o) fprintf(out, "(ext: %d)", (int)o.via.ext.type); #endif fprintf(out, "\""); - fwrite(o.via.ext.ptr, o.via.ext.size, 1, out); + msgpack_object_bin_print(out, o.via.ext.ptr, o.via.ext.size); fprintf(out, "\""); break;