blob: b7df8f19f523a99d1e3fb571ddb317550d294863 [file] [log] [blame]
Thiago Macieira54a0e102015-05-05 21:25:06 -07001/****************************************************************************
2**
3** Copyright (C) 2015 Intel Corporation
4**
5** Permission is hereby granted, free of charge, to any person obtaining a copy
6** of this software and associated documentation files (the "Software"), to deal
7** in the Software without restriction, including without limitation the rights
8** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9** copies of the Software, and to permit persons to whom the Software is
10** furnished to do so, subject to the following conditions:
11**
12** The above copyright notice and this permission notice shall be included in
13** all copies or substantial portions of the Software.
14**
15** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21** THE SOFTWARE.
22**
23****************************************************************************/
24
25#define _BSD_SOURCE
26#include "cbor.h"
27#include "cborconstants_p.h"
28#include "compilersupport_p.h"
29
30#include <assert.h>
31#include <endian.h>
Thiago Macieira2312efd2015-05-06 16:07:48 -070032#include <stdlib.h>
Thiago Macieira54a0e102015-05-05 21:25:06 -070033#include <string.h>
34
35/**
36 * \typedef CborValue
37 * This type contains one value parsed from the CBOR stream.
38 *
39 * To get the actual type, use cbor_value_get_type(). Then extract the value
40 * using one of the corresponding functions: cbor_value_get_boolean(), cbor_value_get_int64(),
41 * cbor_value_get_int(), cbor_value_copy_string(), cbor_value_get_array(), cbor_value_get_map(),
42 * cbor_value_get_double(), cbor_value_get_float().
43 *
44 * In C++ and C11 modes, you can additionally use the cbor_value_get_integer()
45 * and cbor_value_get_floating_point() generic functions.
46 *
47 * \omit
48 * Implementation details: the CborValue contains these fields:
49 * \list
50 * \li ptr: pointer to the actual data
51 * \li flags: flags from the decoder
Thiago Macieira2312efd2015-05-06 16:07:48 -070052 * \li extra: partially decoded integer value (0, 1 or 2 bytes)
Thiago Macieira54a0e102015-05-05 21:25:06 -070053 * \li remaining: remaining items in this collection after this item or UINT32_MAX if length is unknown
54 * \endlist
55 * \endomit
56 */
57
Thiago Macieira54a0e102015-05-05 21:25:06 -070058static inline uint16_t get16(const char *ptr)
59{
60 uint16_t result;
61 memcpy(&result, ptr, sizeof(result));
62 return be16toh(result);
63}
64
65static inline uint32_t get32(const char *ptr)
66{
67 uint32_t result;
68 memcpy(&result, ptr, sizeof(result));
69 return be32toh(result);
70}
71
72static inline uint64_t get64(const char *ptr)
73{
74 uint64_t result;
75 memcpy(&result, ptr, sizeof(result));
76 return be64toh(result);
77}
78
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -070079static inline CborError extract_number(const CborParser *parser, const char **ptr, uint64_t *len)
Thiago Macieira2312efd2015-05-06 16:07:48 -070080{
81 uint8_t additional_information = **ptr & SmallValueMask;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -070082 ++*ptr;
Thiago Macieira2312efd2015-05-06 16:07:48 -070083 if (additional_information < Value8Bit) {
84 *len = additional_information;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -070085 return CborNoError;
Thiago Macieira2312efd2015-05-06 16:07:48 -070086 }
87 if (unlikely(additional_information > Value64Bit))
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -070088 return CborErrorIllegalNumber;
Thiago Macieira2312efd2015-05-06 16:07:48 -070089
90 size_t bytesNeeded = 1 << (additional_information - Value8Bit);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -070091 if (unlikely(*ptr + bytesNeeded > parser->end)) {
92 return CborErrorUnexpectedEOF;
Thiago Macieira2312efd2015-05-06 16:07:48 -070093 } else if (bytesNeeded == 1) {
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -070094 *len = (uint8_t)(*ptr)[0];
Thiago Macieira2312efd2015-05-06 16:07:48 -070095 } else if (bytesNeeded == 2) {
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -070096 *len = get16(*ptr);
Thiago Macieira2312efd2015-05-06 16:07:48 -070097 } else if (bytesNeeded == 4) {
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -070098 *len = get32(*ptr);
Thiago Macieira2312efd2015-05-06 16:07:48 -070099 } else {
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700100 *len = get64(*ptr);
Thiago Macieira2312efd2015-05-06 16:07:48 -0700101 }
102 *ptr += bytesNeeded;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700103 return CborNoError;
Thiago Macieira2312efd2015-05-06 16:07:48 -0700104}
105
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700106static inline CborError extract_length(const CborParser *parser, const char **ptr, size_t *len)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700107{
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700108 uint64_t v;
109 CborError err = extract_number(parser, ptr, &v);
110 if (err)
111 return err;
112
113 *len = v;
114 if (v != *len)
115 return CborErrorDataTooLarge;
116 return CborNoError;
117}
118
119static bool is_fixed_type(uint8_t type)
120{
121 return type != CborTextStringType && type != CborByteStringType && type != CborArrayType &&
122 type != CborMapType;
123}
124
125static CborError preparse_value(CborValue *it)
126{
127 const CborParser *parser = it->parser;
Thiago Macieira11e913f2015-05-07 13:01:18 -0700128 it->type = CborInvalidType;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700129
Thiago Macieira54a0e102015-05-05 21:25:06 -0700130 // are we at the end?
Thiago Macieira54a0e102015-05-05 21:25:06 -0700131 if (it->ptr == parser->end)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700132 return CborErrorUnexpectedEOF;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700133
134 uint8_t descriptor = *it->ptr;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700135 uint8_t type = descriptor & MajorTypeMask;
Thiago Macieira851c4812015-05-08 15:23:20 -0700136 it->type = type;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700137 it->flags = 0;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700138 it->extra = (descriptor &= SmallValueMask);
139
Thiago Macieira56d99832015-05-07 14:34:27 -0700140 if (descriptor > Value64Bit) {
141 if (unlikely(descriptor != IndefiniteLength))
142 return CborErrorIllegalNumber;
143 if (likely(!is_fixed_type(type))) {
144 // special case
145 it->flags |= CborIteratorFlag_UnknownLength;
146 it->type = type;
147 return CborNoError;
148 }
149 return type == CborSimpleType ? CborErrorUnexpectedBreak : CborErrorIllegalNumber;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700150 }
Thiago Macieira54a0e102015-05-05 21:25:06 -0700151
Thiago Macieirac70169f2015-05-06 07:49:44 -0700152 size_t bytesNeeded = descriptor < Value8Bit ? 0 : (1 << (descriptor - Value8Bit));
153 if (it->ptr + 1 + bytesNeeded > parser->end)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700154 return CborErrorUnexpectedEOF;
Thiago Macieirac70169f2015-05-06 07:49:44 -0700155
Thiago Macieira851c4812015-05-08 15:23:20 -0700156 uint8_t majortype = type >> MajorTypeShift;
157 if (majortype == NegativeIntegerType) {
Thiago Macieira54a0e102015-05-05 21:25:06 -0700158 it->flags |= CborIteratorFlag_NegativeInteger;
Thiago Macieira851c4812015-05-08 15:23:20 -0700159 it->type = CborIntegerType;
160 } else if (majortype == SimpleTypesType) {
Thiago Macieira54a0e102015-05-05 21:25:06 -0700161 switch (descriptor) {
162 case FalseValue:
163 it->extra = false;
Thiago Macieira851c4812015-05-08 15:23:20 -0700164 it->type = CborBooleanType;
Thiago Macieira991dd922015-05-07 11:57:59 -0700165 break;
166
Thiago Macieira851c4812015-05-08 15:23:20 -0700167 case SinglePrecisionFloat:
168 case DoublePrecisionFloat:
169 it->flags |= CborIteratorFlag_IntegerValueTooLarge;
170 // fall through
Thiago Macieira54a0e102015-05-05 21:25:06 -0700171 case TrueValue:
172 case NullValue:
173 case UndefinedValue:
174 case HalfPrecisionFloat:
Thiago Macieira851c4812015-05-08 15:23:20 -0700175 it->type = *it->ptr;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700176 break;
177
178 case SimpleTypeInNextByte:
Thiago Macieira851c4812015-05-08 15:23:20 -0700179 it->extra = (uint8_t)it->ptr[1];
Thiago Macieira54a0e102015-05-05 21:25:06 -0700180#ifndef CBOR_PARSER_NO_STRICT_CHECKS
Thiago Macieira851c4812015-05-08 15:23:20 -0700181 if (unlikely(it->extra < 32)) {
182 it->type = CborInvalidType;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700183 return CborErrorIllegalSimpleType;
Thiago Macieira851c4812015-05-08 15:23:20 -0700184 }
Thiago Macieira54a0e102015-05-05 21:25:06 -0700185#endif
Thiago Macieira991dd922015-05-07 11:57:59 -0700186 break;
187
Thiago Macieira54a0e102015-05-05 21:25:06 -0700188 case 28:
189 case 29:
190 case 30:
Thiago Macieira54a0e102015-05-05 21:25:06 -0700191 case Break:
Thiago Macieira851c4812015-05-08 15:23:20 -0700192 assert(false); // these conditions can't be reached
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700193 return CborErrorUnexpectedBreak;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700194 }
Thiago Macieira851c4812015-05-08 15:23:20 -0700195 return CborNoError;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700196 }
197
198 // try to decode up to 16 bits
199 if (descriptor < Value8Bit)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700200 return CborNoError;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700201
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700202 if (descriptor == Value8Bit)
203 it->extra = (uint8_t)it->ptr[1];
204 else if (descriptor == Value16Bit)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700205 it->extra = get16(it->ptr + 1);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700206 else
207 it->flags |= CborIteratorFlag_IntegerValueTooLarge; // Value32Bit or Value64Bit
208 return CborNoError;
209}
Thiago Macieira54a0e102015-05-05 21:25:06 -0700210
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700211static CborError preparse_next_value(CborValue *it)
212{
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700213 if (it->remaining != UINT32_MAX) {
Thiago Macieira11e913f2015-05-07 13:01:18 -0700214 // don't decrement the item count if the current item is tag: they don't count
215 if (it->type != CborTagType && !--it->remaining) {
216 it->type = CborInvalidType;
Thiago Macieira56d99832015-05-07 14:34:27 -0700217 return CborNoError;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700218 }
Thiago Macieira56d99832015-05-07 14:34:27 -0700219 } else if (it->remaining == UINT32_MAX && it->ptr != it->parser->end && *it->ptr == (char)BreakByte) {
220 // end of map or array
221 ++it->ptr;
222 it->type = CborInvalidType;
223 it->remaining = 0;
224 return CborNoError;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700225 }
Thiago Macieira56d99832015-05-07 14:34:27 -0700226
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700227 return preparse_value(it);
228}
229
230static CborError advance_internal(CborValue *it)
231{
232 uint64_t length;
233 CborError err = extract_number(it->parser, &it->ptr, &length);
234 assert(err == CborNoError);
235
Thiago Macieira56d99832015-05-07 14:34:27 -0700236 if (it->type == CborByteStringType || it->type == CborTextStringType) {
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700237 assert(length == (size_t)length);
Thiago Macieira56d99832015-05-07 14:34:27 -0700238 assert((it->flags & CborIteratorFlag_UnknownLength) == 0);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700239 it->ptr += length;
240 }
241
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700242 return preparse_next_value(it);
Thiago Macieira54a0e102015-05-05 21:25:06 -0700243}
244
Thiago Macieira2312efd2015-05-06 16:07:48 -0700245/** \internal
246 *
247 * Decodes the CBOR integer value when it is larger than the 16 bits available
248 * in value->extra. This function requires that value->flags have the
249 * CborIteratorFlag_IntegerValueTooLarge flag set.
250 *
251 * This function is also used to extract single- and double-precision floating
252 * point values (SinglePrecisionFloat == Value32Bit and DoublePrecisionFloat ==
253 * Value64Bit).
254 */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700255uint64_t _cbor_value_decode_int64_internal(const CborValue *value)
256{
Thiago Macieira2312efd2015-05-06 16:07:48 -0700257 assert(value->flags & CborIteratorFlag_IntegerValueTooLarge ||
258 value->type == CborFloatType || value->type == CborDoubleType);
Thiago Macieira851c4812015-05-08 15:23:20 -0700259
260 // since the additional information can only be Value32Bit or Value64Bit,
261 // we just need to test for the one bit those two options differ
262 assert((*value->ptr & SmallValueMask) == Value32Bit || (*value->ptr & SmallValueMask) == Value64Bit);
263 if ((*value->ptr & 1) == (Value32Bit & 1))
Thiago Macieira54a0e102015-05-05 21:25:06 -0700264 return get32(value->ptr + 1);
265
266 assert((*value->ptr & SmallValueMask) == Value64Bit);
267 return get64(value->ptr + 1);
268}
269
270/**
271 * Initializes the CBOR parser for parsing \a size bytes beginning at \a
272 * buffer. Parsing will use flags set in \a flags. The iterator to the first
273 * element is returned in \a it.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700274 *
275 * The \a parser structure needs to remain valid throughout the decoding
276 * process. It is not thread-safe to share one CborParser among multiple
277 * threads iterating at the same time, but the object can be copied so multiple
278 * threads can iterate.
279 *
280 * ### Write how to determine the end pointer
281 * ### Write how to do limited-buffer windowed decoding
Thiago Macieira54a0e102015-05-05 21:25:06 -0700282 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700283CborError cbor_parser_init(const char *buffer, size_t size, int flags, CborParser *parser, CborValue *it)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700284{
285 memset(parser, 0, sizeof(*parser));
286 parser->end = buffer + size;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700287 parser->flags = flags;
288 it->parser = parser;
289 it->ptr = buffer;
290 it->remaining = 1; // there's one type altogether, usually an array or map
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700291 return preparse_value(it);
Thiago Macieira2312efd2015-05-06 16:07:48 -0700292}
293
294/**
295 * Advances the CBOR value \a it by one fixed-size position. Fixed-size types
296 * are: integers, tags, simple types (including boolean, null and undefined
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700297 * values) and floating point types.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700298 *
299 * \sa cbor_value_at_end(), cbor_value_advance(), cbor_value_begin_recurse(), cbor_value_end_recurse()
300 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700301CborError cbor_value_advance_fixed(CborValue *it)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700302{
Thiago Macieira2312efd2015-05-06 16:07:48 -0700303 assert(it->type != CborInvalidType);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700304 assert(is_fixed_type(it->type));
305 if (!it->remaining)
306 return CborErrorAdvancePastEOF;
307 return advance_internal(it);
Thiago Macieira54a0e102015-05-05 21:25:06 -0700308}
309
Thiago Macieira2312efd2015-05-06 16:07:48 -0700310/**
311 * Advances the CBOR value \a it by one element, skipping over containers.
312 * Unlike cbor_value_advance_fixed(), this function can be called on a CBOR
313 * value of any type. However, if the type is a container (map or array) or a
314 * string with a chunked payload, this function will not run in constant time
315 * and will recurse into itself (it will run on O(n) time for the number of
316 * elements or chunks and will use O(n) memory for the number of nested
317 * containers).
318 *
Thiago Macieira2312efd2015-05-06 16:07:48 -0700319 * \sa cbor_value_at_end(), cbor_value_advance_fixed(), cbor_value_begin_recurse(), cbor_value_end_recurse()
320 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700321CborError cbor_value_advance(CborValue *it)
Thiago Macieira2312efd2015-05-06 16:07:48 -0700322{
323 assert(it->type != CborInvalidType);
324 if (!it->remaining)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700325 return CborErrorAdvancePastEOF;
Thiago Macieira2312efd2015-05-06 16:07:48 -0700326 if (is_fixed_type(it->type))
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700327 return advance_internal(it);
Thiago Macieira2312efd2015-05-06 16:07:48 -0700328
Thiago Macieira9ae05812015-05-11 15:09:09 +0900329 if (!cbor_value_is_container(it)) {
330 size_t len = SIZE_MAX;
331 return cbor_value_copy_string(it, NULL, &len, it);
332 }
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700333
334 // map or array
335 CborError err;
336 CborValue recursed;
337 err = cbor_value_enter_container(it, &recursed);
338 if (err)
339 return err;
340 while (!cbor_value_at_end(&recursed)) {
341 err = cbor_value_advance(&recursed);
342 if (err)
343 return err;
Thiago Macieira2312efd2015-05-06 16:07:48 -0700344 }
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700345 return cbor_value_leave_container(it, &recursed);
Thiago Macieira2312efd2015-05-06 16:07:48 -0700346}
347
348/**
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700349 * Advances the CBOR value \a it until it no longer points to a tag. If \a it is
350 * already not pointing to a tag, then this function returns it unchanged.
351 *
352 * \sa cbor_value_advance_fixed(), cbor_value_advance()
353 */
354CborError cbor_value_skip_tag(CborValue *it)
355{
356 while (cbor_value_is_tag(it)) {
357 CborError err = cbor_value_advance_fixed(it);
358 if (err)
359 return err;
360 }
361 return CborNoError;
362}
363
364
365/**
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700366 * \fn bool cbor_value_is_container(const CborValue *it)
367 *
Thiago Macieira2312efd2015-05-06 16:07:48 -0700368 * Returns true if the \a it value is a container and requires recursion in
369 * order to decode (maps and arrays), false otherwise.
370 */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700371
Thiago Macieira2312efd2015-05-06 16:07:48 -0700372/**
373 * Creates a CborValue iterator pointing to the first element of the container
374 * represented by \a it and saves it in \a recursed. The \a it container object
375 * needs to be kept and passed again to cbor_value_leave_container() in order
376 * to continue iterating past this container.
377 *
378 * \sa cbor_value_is_container(), cbor_value_leave_container(), cbor_value_advance()
379 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700380CborError cbor_value_enter_container(const CborValue *it, CborValue *recursed)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700381{
Thiago Macieira56d99832015-05-07 14:34:27 -0700382 CborError err;
Thiago Macieira2312efd2015-05-06 16:07:48 -0700383 assert(cbor_value_is_container(it));
Thiago Macieira54a0e102015-05-05 21:25:06 -0700384 *recursed = *it;
Thiago Macieira56d99832015-05-07 14:34:27 -0700385
Thiago Macieira54a0e102015-05-05 21:25:06 -0700386 if (it->flags & CborIteratorFlag_UnknownLength) {
387 recursed->remaining = UINT32_MAX;
Thiago Macieira56d99832015-05-07 14:34:27 -0700388 ++recursed->ptr;
389 err = preparse_value(recursed);
390 if (err != CborErrorUnexpectedBreak)
391 return err;
392 // actually, break was expected here
393 // it's just an empty container
394 ++recursed->ptr;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700395 } else {
Thiago Macieira56d99832015-05-07 14:34:27 -0700396 uint64_t len;
397 err = extract_number(recursed->parser, &recursed->ptr, &len);
398 assert(err == CborNoError);
Thiago Macieira56d99832015-05-07 14:34:27 -0700399
Thiago Macieira54a0e102015-05-05 21:25:06 -0700400 recursed->remaining = len;
401 if (recursed->remaining != len || len == UINT32_MAX)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700402 return CborErrorDataTooLarge;
Thiago Macieirace16f052015-05-07 23:14:25 -0700403 if (recursed->type == CborMapType) {
404 // maps have keys and values, so we need to multiply by 2
405 if (recursed->remaining > UINT32_MAX / 2)
406 return CborErrorDataTooLarge;
407 recursed->remaining *= 2;
408 }
Thiago Macieira56d99832015-05-07 14:34:27 -0700409 if (len != 0)
410 return preparse_value(recursed);
Thiago Macieira54a0e102015-05-05 21:25:06 -0700411 }
Thiago Macieira56d99832015-05-07 14:34:27 -0700412
413 // the case of the empty container
414 recursed->type = CborInvalidType;
415 recursed->remaining = 0;
416 return CborNoError;
Thiago Macieirac70169f2015-05-06 07:49:44 -0700417}
418
Thiago Macieira2312efd2015-05-06 16:07:48 -0700419/**
420 * Updates \a it to point to the next element after the container. The \a
Thiago Macieira56d99832015-05-07 14:34:27 -0700421 * recursed object needs to point to the element obtained either by advancing
422 * the last element of the container (via cbor_value_advance(),
423 * cbor_value_advance_fixed(), a nested cbor_value_leave_container(), or the \c
424 * next pointer from cbor_value_copy_string() or cbor_value_dup_string()).
Thiago Macieira2312efd2015-05-06 16:07:48 -0700425 *
426 * \sa cbor_value_enter_container(), cbor_value_at_end()
427 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700428CborError cbor_value_leave_container(CborValue *it, const CborValue *recursed)
Thiago Macieirac70169f2015-05-06 07:49:44 -0700429{
Thiago Macieira2312efd2015-05-06 16:07:48 -0700430 assert(cbor_value_is_container(it));
Thiago Macieira56d99832015-05-07 14:34:27 -0700431 assert(recursed->type == CborInvalidType);
Thiago Macieirac70169f2015-05-06 07:49:44 -0700432 it->ptr = recursed->ptr;
Thiago Macieira56d99832015-05-07 14:34:27 -0700433 return preparse_next_value(it);
Thiago Macieirac70169f2015-05-06 07:49:44 -0700434}
435
Thiago Macieira2312efd2015-05-06 16:07:48 -0700436/**
437 * Calculates the length of the string in \a value and stores the result in \a
438 * len. This function is different from cbor_value_get_string_length() in that
439 * it calculates the length even for strings sent in chunks. For that reason,
440 * this function may not run in constant time (it will run in O(n) time on the
441 * number of chunks).
442 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700443 * \note On 32-bit platforms, this function will return error condition of \ref
444 * CborErrorDataTooLarge if the stream indicates a length that is too big to
445 * fit in 32-bit.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700446 *
447 * \sa cbor_value_get_string_length(), cbor_value_copy_string(), cbor_value_is_length_known()
448 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700449CborError cbor_value_calculate_string_length(const CborValue *value, size_t *len)
Thiago Macieira2312efd2015-05-06 16:07:48 -0700450{
Thiago Macieira9ae05812015-05-11 15:09:09 +0900451 *len = SIZE_MAX;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700452 return cbor_value_copy_string(value, NULL, len, NULL);
Thiago Macieirac70169f2015-05-06 07:49:44 -0700453}
454
Thiago Macieira2312efd2015-05-06 16:07:48 -0700455/**
456 * Allocates memory for the string pointed by \a value and copies it into this
457 * buffer. The pointer to the buffer is stored in \a buffer and the number of
458 * bytes copied is stored in \a len (those variables must not be NULL).
459 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700460 * If \c malloc returns a NULL pointer, this function will return error
461 * condition \ref CborErrorOutOfMemory.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700462 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700463 * On success, \c{*buffer} will contain a valid pointer that must be freed by
464 * calling \c{free()}. This is the case even for zero-length strings.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700465 *
466 * The \a next pointer, if not null, will be updated to point to the next item
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700467 * after this string. If \a value points to the last item, then \a next will be
468 * invalid.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700469 *
470 * \note This function does not perform UTF-8 validation on the incoming text
471 * string.
472 *
473 * \sa cbor_value_copy_string()
474 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700475CborError cbor_value_dup_string(const CborValue *value, char **buffer, size_t *buflen, CborValue *next)
Thiago Macieirac70169f2015-05-06 07:49:44 -0700476{
Thiago Macieira2312efd2015-05-06 16:07:48 -0700477 assert(buffer);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700478 assert(buflen);
Thiago Macieira851c4812015-05-08 15:23:20 -0700479 CborError err = cbor_value_copy_string(value, NULL, buflen, NULL);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700480 if (err)
481 return err;
Thiago Macieirac70169f2015-05-06 07:49:44 -0700482
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700483 ++*buflen;
484 *buffer = malloc(*buflen);
Thiago Macieira2312efd2015-05-06 16:07:48 -0700485 if (!*buffer) {
Thiago Macieirac70169f2015-05-06 07:49:44 -0700486 // out of memory
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700487 return CborErrorOutOfMemory;
Thiago Macieirac70169f2015-05-06 07:49:44 -0700488 }
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700489 err = cbor_value_copy_string(value, *buffer, buflen, next);
490 if (err) {
Thiago Macieira2312efd2015-05-06 16:07:48 -0700491 free(*buffer);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700492 return err;
Thiago Macieirac70169f2015-05-06 07:49:44 -0700493 }
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700494 return CborNoError;
Thiago Macieira2312efd2015-05-06 16:07:48 -0700495}
496
Thiago Macieira9ae05812015-05-11 15:09:09 +0900497// We return uintptr_t so that we can pass memcpy directly as the iteration
498// function. The choice is to optimize for memcpy, which is used in the base
499// parser API (cbor_value_copy_string), while memcmp is used in convenience API
500// only.
501typedef uintptr_t (*IterateFunction)(char *, const char *, size_t);
502
503static uintptr_t iterate_noop(char *dest, const char *src, size_t len)
504{
505 (void)dest;
506 (void)src;
507 (void)len;
508 return true;
509}
510
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700511static uintptr_t iterate_memcmp(char *s1, const char *s2, size_t len)
512{
513 return memcmp(s1, s2, len) == 0;
514}
515
Thiago Macieira9ae05812015-05-11 15:09:09 +0900516static CborError iterate_string_chunks(const CborValue *value, char *buffer, size_t *buflen,
517 bool *result, CborValue *next, IterateFunction func)
518{
519 assert(cbor_value_is_byte_string(value) || cbor_value_is_text_string(value));
520
521 size_t total;
522 CborError err;
523 const char *ptr = value->ptr;
524 if (cbor_value_is_length_known(value)) {
525 // easy case: fixed length
526 err = extract_length(value->parser, &ptr, &total);
527 if (err)
528 return err;
529 if (ptr + total > value->parser->end)
530 return CborErrorUnexpectedEOF;
531 if (total <= *buflen)
532 *result = func(buffer, ptr, total);
533 else
534 *result = false;
535 ptr += total;
536 } else {
537 // chunked
538 ++ptr;
539 total = 0;
540 *result = true;
541 while (true) {
542 size_t chunkLen;
543 size_t newTotal;
544
545 if (ptr == value->parser->end)
546 return CborErrorUnexpectedEOF;
547
548 if (*ptr == (char)BreakByte) {
549 ++ptr;
550 break;
551 }
552
553 // is this the right type?
554 if ((*ptr & MajorTypeMask) != value->type)
555 return CborErrorIllegalType;
556
557 err = extract_length(value->parser, &ptr, &chunkLen);
558 if (err)
559 return err;
560
561 if (unlikely(!add_check_overflow(total, chunkLen, &newTotal)))
562 return CborErrorDataTooLarge;
563
564 if (ptr + chunkLen > value->parser->end)
565 return CborErrorUnexpectedEOF;
566
567 if (*result && *buflen >= newTotal)
568 *result = func(buffer + total, ptr, chunkLen);
569 else
570 *result = false;
571
572 ptr += chunkLen;
573 total = newTotal;
574 }
575 }
576
577 // is there enough room for the ending NUL byte?
578 if (*result && *buflen > total)
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700579 *result = func(buffer + total, "", 1);
Thiago Macieira9ae05812015-05-11 15:09:09 +0900580 *buflen = total;
581
582 if (next) {
583 *next = *value;
584 next->ptr = ptr;
585 return preparse_next_value(next);
586 }
587 return CborNoError;
588}
589
Thiago Macieira2312efd2015-05-06 16:07:48 -0700590/**
591 * Copies the string pointed by \a value into the buffer provided at \a buffer
592 * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
593 * copy anything and will only update the \a next value.
594 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700595 * If the provided buffer length was too small, this function returns an error
596 * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
597 * of the string in order to preallocate a buffer, use
Thiago Macieira2312efd2015-05-06 16:07:48 -0700598 * cbor_value_calculate_string_length().
599 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700600 * On success, this function sets the number of bytes copied to \c{*buflen}. If
601 * the buffer is large enough, this function will insert a null byte after the
602 * last copied byte, to facilitate manipulation of text strings. That byte is
603 * not included in the returned value of \c{*buflen}.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700604 *
605 * The \a next pointer, if not null, will be updated to point to the next item
606 * after this string. If \a value points to the last item, then \a next will be
607 * invalid.
608 *
609 * \note This function does not perform UTF-8 validation on the incoming text
610 * string.
611 *
612 * \sa cbor_value_dup_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
613 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700614CborError cbor_value_copy_string(const CborValue *value, char *buffer,
615 size_t *buflen, CborValue *next)
Thiago Macieira2312efd2015-05-06 16:07:48 -0700616{
Thiago Macieira9ae05812015-05-11 15:09:09 +0900617 bool copied_all;
618 CborError err = iterate_string_chunks(value, buffer, buflen, &copied_all, next,
619 buffer ? (IterateFunction)memcpy : iterate_noop);
620 return err ? err :
621 copied_all ? CborNoError : CborErrorOutOfMemory;
Thiago Macieirac70169f2015-05-06 07:49:44 -0700622}
623
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700624/**
625 * Compares the entry \a value with the string \a string and store the result
626 * in \a result. If the value is different from \a string or if it is not a
627 * text string, \a result will contain \c false.
628 *
629 * The entry at \a value may be a tagged string. If \a is not a string or a
630 * tagged string, the comparison result will be false.
631 */
632CborError cbor_value_text_string_equals(const CborValue *value, const char *string, bool *result)
633{
634 CborValue copy = *value;
635 CborError err = cbor_value_skip_tag(&copy);
636 if (err)
637 return err;
638 if (!cbor_value_is_text_string(&copy)) {
639 *result = false;
640 return CborNoError;
641 }
642
643 size_t len = strlen(string);
644 return iterate_string_chunks(&copy, CONST_CAST(char *, string), &len, result, NULL, iterate_memcmp);
645}
646
647/**
Thiago Macieira7b623c22015-05-11 15:52:14 +0900648 * Attempts to find the value in map \a map that corresponds to the text string
649 * entry \a string. If the item is found, it is stored in \a result. If no item
650 * is found matching the key, then \a result will contain an element of type
651 * \ref CborInvalidType.
652 *
653 * \note This function may be expensive to execute.
654 */
655CborError cbor_value_map_find_value(const CborValue *map, const char *string, CborValue *element)
656{
657 assert(cbor_value_is_map(map));
658 size_t len = strlen(string);
659 CborError err = cbor_value_enter_container(map, element);
660 if (err)
661 goto error;
662
663 while (!cbor_value_at_end(element)) {
664 // find the non-tag so we can compare
665 err = cbor_value_skip_tag(element);
666 if (err)
667 goto error;
668 if (cbor_value_is_text_string(element)) {
669 bool equals;
670 size_t dummyLen = len;
671 err = iterate_string_chunks(element, CONST_CAST(char *, string), &dummyLen,
672 &equals, element, iterate_memcmp);
673 if (err)
674 goto error;
675 if (equals)
676 return preparse_value(element);
677 } else {
678 // skip this key
679 err = cbor_value_advance(element);
680 if (err)
681 goto error;
682 }
683
684 // skip this value
685 err = cbor_value_skip_tag(element);
686 if (err)
687 goto error;
688 err = cbor_value_advance(element);
689 if (err)
690 goto error;
691 }
692
693 // not found
694 element->type = CborInvalidType;
695 return CborNoError;
696
697error:
698 element->type = CborInvalidType;
699 return err;
700}
701
702/**
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700703 * Extracts a half-precision floating point from \a value and stores it in \a
704 * result.
705 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700706CborError cbor_value_get_half_float(const CborValue *value, void *result)
Thiago Macieirac70169f2015-05-06 07:49:44 -0700707{
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700708 assert(value->type == CborHalfFloatType);
Thiago Macieirac70169f2015-05-06 07:49:44 -0700709
710 // size has been computed already
711 uint16_t v = get16(value->ptr + 1);
712 memcpy(result, &v, sizeof(v));
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700713 return CborNoError;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700714}