pack: msgpack2json: new function to write safe strings
@@ -311,6 +311,66 @@ static inline int try_to_write(char *buf, int *off, size_t left,
return FLB_TRUE;
}
+static inline int try_to_write_str(char *buf, int *off, size_t left,
+ char *str, size_t str_len)
+{
+ int i;
+ int written = 0;
+ int required;
+ char c;
+ char *p;
+
+ required = *off + str_len;
+ if (left <= required) {
+ return FLB_FALSE;
+ }
+
+ written = *off;
+ p = buf + *off;
+ for (i = 0; i < str_len; i++) {
+ required = written + 2;
+ if (left <= required) {
+ return FLB_FALSE;
+ }
+
+ c = str[i];
+ switch (c) {
+ case '\\':
+ case '"':
+ *p++ = '\\';
+ *p++ = c;
+ break;
+ case '\b':
+ *p++ = '\\';
+ *p++ = '\b';
+ break;
+ case '\t':
+ *p++ = '\\';
+ *p++ = '\t';
+ break;
+ case '\n':
+ *p++ = '\\';
+ *p++ = '\n';
+ break;
+ case '\f':
+ *p++ = '\\';
+ *p++ = '\f';
+ break;
+ case '\r':
+ *p++ = '\\';
+ *p++ = '\r';
+ break;
+ default:
+ *p++ = c;
+ }
+
+ written = (p - (buf + *off));
+ }
+
+ *off += written;
+ return FLB_TRUE;
+}
+
static int msgpack2json(char *buf, int *off, size_t left, msgpack_object *o)
{
int ret = FLB_FALSE;
@@ -355,7 +415,7 @@ static int msgpack2json(char *buf, int *off, size_t left, msgpack_object *o)
case MSGPACK_OBJECT_STR:
if (try_to_write(buf, off, left, "\"", 1) &&
(o->via.str.size > 0 ?
- try_to_write(buf, off, left, (char*)o->via.str.ptr, o->via.str.size)
+ try_to_write_str(buf, off, left, (char*)o->via.str.ptr, o->via.str.size)
: 1/* nothing to do */) &&
try_to_write(buf, off, left, "\"", 1)) {
ret = FLB_TRUE;
@@ -507,7 +567,7 @@ char *flb_msgpack_to_json_str(size_t size, msgpack_unpacked *data)
while(1) {
buf = (char *)flb_malloc(size);
if (buf == NULL) {
- flb_warn("[%s] can't allocate buffer");
+ flb_errno();
return NULL;
}
