msgpack-c icon indicating copy to clipboard operation
msgpack-c copied to clipboard

Check the remaining size in the pack function

Open ygj6 opened this issue 4 years ago • 0 comments

If we want to pack strings, we will use msgpack_pack_str() and msgpack_pack_str_body(). But these two functions do not check the remaining size, please see the following code:

msgpack_pack_str(&pk, 3);
msgpack_pack_str_body(&pk, "ab", 2);    // 1 byte missing
msgpack_pack_str(&pk, 3);
msgpack_pack_str_body(&pk, "cdef", 4);  // 1 more byte
msgpack_pack_str(&pk, 3);
msgpack_pack_str_body(&pk, "ghi", 3);   // ok

This code will not go wrong, and the result is a3 61 62 a3 63 64 65 66 a3 67 68 69. But when unpacking it will get unexpected result.

Therefore, I consider calculating the remaining available size in msgpack_pack_str_body() and returning the result. like this:

msgpack_pack_str(&pk, 5);
msgpack_pack_str_body(&pk, "abc", 3);   // return 2 (5 - 3, The number of bytes that need to be packed in)
msgpack_pack_str_body(&pk, "de", 2);    // return 0 (Successfully packed string)
msgpack_pack_str_body(&pk, "fgh", 3);   // return -1 (Failed to pack string)

msgpack_pack_str(&pk, 5);
msgpack_pack_str_body(&pk, "abc", 3);   // return 2 (5 - 3, The number of bytes that need to be packed in)
msgpack_pack_str_body(&pk, "defg", 4);  // return 0 (Successfully packed string, extra strings, here "fg", will be discarded)

The results of the two pieces of code are both a5 61 62 63 64 65. Its unpack result is also normal.

Other functions, msgpack_pack_bin() and msgpack_pack_bin_body(), msgpack_pack_ext() and msgpack_pack_ext_body(), msgpack_pack_v4raw() and msgpack_pack_v4raw_body(), msgpack_pack_array(), msgpack_pack_map(), have the same problem.

Does anyone agree with this approach?

ygj6 avatar Apr 26 '20 14:04 ygj6