blob: a968a8e8ce41a18d9174227e217599d95f966fbc [file] [log] [blame]
Thiago Macieira54a0e102015-05-05 21:25:06 -07001/****************************************************************************
2**
Thiago Macieira46a818e2015-10-08 15:13:05 +02003** Copyright (C) 2016 Intel Corporation
Thiago Macieira54a0e102015-05-05 21:25:06 -07004**
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
Thiago Macieiraed5b57c2015-07-07 16:38:27 -070025#define _BSD_SOURCE 1
Otavio Pontese2d5dd52016-07-08 09:49:38 -030026#define _DEFAULT_SOURCE 1
Thiago Macieira54a0e102015-05-05 21:25:06 -070027#include "cbor.h"
28#include "cborconstants_p.h"
29#include "compilersupport_p.h"
Thiago Macieira4e9626c2015-09-21 14:57:17 -070030#include "extract_number_p.h"
Thiago Macieira54a0e102015-05-05 21:25:06 -070031
32#include <assert.h>
Thiago Macieira54a0e102015-05-05 21:25:06 -070033#include <string.h>
34
Thiago Macieira8f3fb782015-06-16 16:27:01 -070035#include "assert_p.h" /* Always include last */
36
Thiago Macieira4a99af92015-05-12 10:41:45 +090037#ifndef CBOR_PARSER_MAX_RECURSIONS
38# define CBOR_PARSER_MAX_RECURSIONS 1024
39#endif
40
Thiago Macieira54a0e102015-05-05 21:25:06 -070041/**
Thiago Macieira46a818e2015-10-08 15:13:05 +020042 * \defgroup CborParsing Parsing CBOR streams
43 * \brief Group of functions used to parse CBOR streams.
Thiago Macieira54a0e102015-05-05 21:25:06 -070044 *
Thiago Macieira46a818e2015-10-08 15:13:05 +020045 * TinyCBOR provides functions for pull-based stream parsing of a CBOR-encoded
46 * payload. The main data type for the parsing is a CborValue, which behaves
47 * like an iterator and can be used to extract the encoded data. It is first
48 * initialized with a call to cbor_parser_init() and is usually used to extract
49 * exactly one item, most often an array or map.
Thiago Macieira54a0e102015-05-05 21:25:06 -070050 *
Thiago Macieira46a818e2015-10-08 15:13:05 +020051 * Nested CborValue objects can be parsed using cbor_value_enter_container().
52 * Each call to cbor_value_enter_container() must be matched by a call to
53 * cbor_value_leave_container(), with the exact same parameters.
Thiago Macieira54a0e102015-05-05 21:25:06 -070054 *
Thiago Macieira46a818e2015-10-08 15:13:05 +020055 * The example below initializes a CborParser object, begins the parsing with a
56 * CborValue and decodes a single integer:
57 *
58 * \code
59 * int extract_int(const uint8_t *buffer, size_t len)
60 * {
61 * CborParser parser;
62 * CborValue value;
63 * int result;
64 * cbor_parser_init(buffer, len, 0, &buffer, &value);
65 * cbor_value_get_int(&value, &result);
66 * return result;
67 * }
68 * \endcode
69 *
70 * The code above does no error checking, which means it assumes the data comes
71 * from a source trusted to send one properly-encoded integer. The following
72 * example does the exact same operation, but includes error parsing and
73 * returns 0 on parsing failure:
74 *
75 * \code
76 * int extract_int(const uint8_t *buffer, size_t len)
77 * {
78 * CborParser parser;
79 * CborValue value;
80 * int result;
81 * if (cbor_parser_init(buffer, len, 0, &buffer, &value) != CborNoError)
82 * return 0;
83 * if (!cbor_value_is_integer(&value) ||
84 * cbor_value_get_int(&value, &result) != CborNoError)
85 * return 0;
86 * return result;
87 * }
88 * \endcode
89 *
90 * Note, in the example above, that one can't distinguish a parsing failure
91 * from an encoded value of zero. Reporting a parsing error is left as an
92 * exercise to the reader.
93 *
94 * The code above does not execute a range-check either: it is possible that
95 * the value decoded from the CBOR stream encodes a number larger than what can
96 * be represented in a variable of type \c{int}. If detecting that case is
97 * important, the code should call cbor_value_get_int_checked() instead.
98 *
99 * <h3 class="groupheader">Memory and parsing constraints</h3>
100 *
101 * TinyCBOR is designed to run with little memory and with minimal overhead.
102 * Except where otherwise noted, the parser functions always run on constant
103 * time (O(1)), do not recurse and never allocate memory (thus, stack usage is
104 * bounded and is O(1)).
105 *
106 * <h3 class="groupheader">Error handling and preconditions</h3>
107 *
108 * All functions operating on a CborValue return a CborError condition, with
109 * CborNoError standing for the normal situation in which no parsing error
110 * occurred. All functions may return parsing errors in case the stream cannot
111 * be decoded properly, be it due to corrupted data or due to reaching the end
112 * of the input buffer.
113 *
114 * Error conditions must not be ignored. All decoder functions have undefined
115 * behavior if called after an error has been reported, and may crash.
116 *
117 * Some functions are also documented to have preconditions, like
118 * cbor_value_get_int() requiring that the input be an integral value.
119 * Violation of preconditions also results in undefined behavior and the
120 * program may crash.
121 */
122
123/**
124 * \addtogroup CborParsing
125 * @{
126 */
127
128/**
129 * \struct CborValue
130 *
131 * This type contains one value parsed from the CBOR stream. Each CborValue
132 * behaves as an iterator in a StAX-style parser.
133 *
134 * \if privatedocs
Thiago Macieira54a0e102015-05-05 21:25:06 -0700135 * Implementation details: the CborValue contains these fields:
136 * \list
137 * \li ptr: pointer to the actual data
138 * \li flags: flags from the decoder
Thiago Macieira2312efd2015-05-06 16:07:48 -0700139 * \li extra: partially decoded integer value (0, 1 or 2 bytes)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700140 * \li remaining: remaining items in this collection after this item or UINT32_MAX if length is unknown
141 * \endlist
Thiago Macieira46a818e2015-10-08 15:13:05 +0200142 * \endif
Thiago Macieira54a0e102015-05-05 21:25:06 -0700143 */
144
Thiago Macieiraf5cb94b2015-06-16 16:10:49 -0700145static CborError extract_length(const CborParser *parser, const uint8_t **ptr, size_t *len)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700146{
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700147 uint64_t v;
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700148 CborError err = extract_number(ptr, parser->end, &v);
Mike Colagrosso629d5b72016-02-24 15:12:34 -0700149 if (err) {
150 *len = 0;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700151 return err;
Mike Colagrosso629d5b72016-02-24 15:12:34 -0700152 }
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700153
154 *len = v;
155 if (v != *len)
156 return CborErrorDataTooLarge;
157 return CborNoError;
158}
159
160static bool is_fixed_type(uint8_t type)
161{
162 return type != CborTextStringType && type != CborByteStringType && type != CborArrayType &&
163 type != CborMapType;
164}
165
166static CborError preparse_value(CborValue *it)
167{
168 const CborParser *parser = it->parser;
Thiago Macieira11e913f2015-05-07 13:01:18 -0700169 it->type = CborInvalidType;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700170
Thiago Macieiradbc01292016-06-06 17:02:25 -0700171 /* are we at the end? */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700172 if (it->ptr == parser->end)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700173 return CborErrorUnexpectedEOF;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700174
175 uint8_t descriptor = *it->ptr;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700176 uint8_t type = descriptor & MajorTypeMask;
Thiago Macieira851c4812015-05-08 15:23:20 -0700177 it->type = type;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700178 it->flags = 0;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700179 it->extra = (descriptor &= SmallValueMask);
180
Thiago Macieira56d99832015-05-07 14:34:27 -0700181 if (descriptor > Value64Bit) {
182 if (unlikely(descriptor != IndefiniteLength))
Thiago Macieira3f76f632015-05-12 10:10:09 +0900183 return type == CborSimpleType ? CborErrorUnknownType : CborErrorIllegalNumber;
Thiago Macieira56d99832015-05-07 14:34:27 -0700184 if (likely(!is_fixed_type(type))) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700185 /* special case */
Thiago Macieira56d99832015-05-07 14:34:27 -0700186 it->flags |= CborIteratorFlag_UnknownLength;
187 it->type = type;
188 return CborNoError;
189 }
190 return type == CborSimpleType ? CborErrorUnexpectedBreak : CborErrorIllegalNumber;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700191 }
Thiago Macieira54a0e102015-05-05 21:25:06 -0700192
Thiago Macieirac70169f2015-05-06 07:49:44 -0700193 size_t bytesNeeded = descriptor < Value8Bit ? 0 : (1 << (descriptor - Value8Bit));
Thiago Macieira63abed92015-10-28 17:01:14 -0700194 if (bytesNeeded + 1 > (size_t)(parser->end - it->ptr))
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700195 return CborErrorUnexpectedEOF;
Thiago Macieirac70169f2015-05-06 07:49:44 -0700196
Thiago Macieira851c4812015-05-08 15:23:20 -0700197 uint8_t majortype = type >> MajorTypeShift;
198 if (majortype == NegativeIntegerType) {
Thiago Macieira54a0e102015-05-05 21:25:06 -0700199 it->flags |= CborIteratorFlag_NegativeInteger;
Thiago Macieira851c4812015-05-08 15:23:20 -0700200 it->type = CborIntegerType;
201 } else if (majortype == SimpleTypesType) {
Thiago Macieira54a0e102015-05-05 21:25:06 -0700202 switch (descriptor) {
203 case FalseValue:
204 it->extra = false;
Thiago Macieira851c4812015-05-08 15:23:20 -0700205 it->type = CborBooleanType;
Thiago Macieira991dd922015-05-07 11:57:59 -0700206 break;
207
Thiago Macieira851c4812015-05-08 15:23:20 -0700208 case SinglePrecisionFloat:
209 case DoublePrecisionFloat:
210 it->flags |= CborIteratorFlag_IntegerValueTooLarge;
Thiago Macieiradbc01292016-06-06 17:02:25 -0700211 /* fall through */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700212 case TrueValue:
213 case NullValue:
214 case UndefinedValue:
215 case HalfPrecisionFloat:
Thiago Macieira851c4812015-05-08 15:23:20 -0700216 it->type = *it->ptr;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700217 break;
218
219 case SimpleTypeInNextByte:
Thiago Macieira851c4812015-05-08 15:23:20 -0700220 it->extra = (uint8_t)it->ptr[1];
Thiago Macieira54a0e102015-05-05 21:25:06 -0700221#ifndef CBOR_PARSER_NO_STRICT_CHECKS
Thiago Macieira851c4812015-05-08 15:23:20 -0700222 if (unlikely(it->extra < 32)) {
223 it->type = CborInvalidType;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700224 return CborErrorIllegalSimpleType;
Thiago Macieira851c4812015-05-08 15:23:20 -0700225 }
Thiago Macieira54a0e102015-05-05 21:25:06 -0700226#endif
Thiago Macieira991dd922015-05-07 11:57:59 -0700227 break;
228
Thiago Macieira54a0e102015-05-05 21:25:06 -0700229 case 28:
230 case 29:
231 case 30:
Thiago Macieira54a0e102015-05-05 21:25:06 -0700232 case Break:
Thiago Macieiradbc01292016-06-06 17:02:25 -0700233 assert(false); /* these conditions can't be reached */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700234 return CborErrorUnexpectedBreak;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700235 }
Thiago Macieira851c4812015-05-08 15:23:20 -0700236 return CborNoError;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700237 }
238
Thiago Macieiradbc01292016-06-06 17:02:25 -0700239 /* try to decode up to 16 bits */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700240 if (descriptor < Value8Bit)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700241 return CborNoError;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700242
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700243 if (descriptor == Value8Bit)
244 it->extra = (uint8_t)it->ptr[1];
245 else if (descriptor == Value16Bit)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700246 it->extra = get16(it->ptr + 1);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700247 else
Thiago Macieiradbc01292016-06-06 17:02:25 -0700248 it->flags |= CborIteratorFlag_IntegerValueTooLarge; /* Value32Bit or Value64Bit */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700249 return CborNoError;
250}
Thiago Macieira54a0e102015-05-05 21:25:06 -0700251
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700252static CborError preparse_next_value(CborValue *it)
253{
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700254 if (it->remaining != UINT32_MAX) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700255 /* don't decrement the item count if the current item is tag: they don't count */
Thiago Macieira11e913f2015-05-07 13:01:18 -0700256 if (it->type != CborTagType && !--it->remaining) {
257 it->type = CborInvalidType;
Thiago Macieira56d99832015-05-07 14:34:27 -0700258 return CborNoError;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700259 }
Thiago Macieira5752ce52015-06-16 12:10:03 -0700260 } else if (it->remaining == UINT32_MAX && it->ptr != it->parser->end && *it->ptr == (uint8_t)BreakByte) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700261 /* end of map or array */
Thiago Macieira56d99832015-05-07 14:34:27 -0700262 ++it->ptr;
263 it->type = CborInvalidType;
264 it->remaining = 0;
265 return CborNoError;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700266 }
Thiago Macieira56d99832015-05-07 14:34:27 -0700267
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700268 return preparse_value(it);
269}
270
271static CborError advance_internal(CborValue *it)
272{
273 uint64_t length;
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700274 CborError err = extract_number(&it->ptr, it->parser->end, &length);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700275 assert(err == CborNoError);
276
Thiago Macieira56d99832015-05-07 14:34:27 -0700277 if (it->type == CborByteStringType || it->type == CborTextStringType) {
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700278 assert(length == (size_t)length);
Thiago Macieira56d99832015-05-07 14:34:27 -0700279 assert((it->flags & CborIteratorFlag_UnknownLength) == 0);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700280 it->ptr += length;
281 }
282
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700283 return preparse_next_value(it);
Thiago Macieira54a0e102015-05-05 21:25:06 -0700284}
285
Thiago Macieira2312efd2015-05-06 16:07:48 -0700286/** \internal
287 *
288 * Decodes the CBOR integer value when it is larger than the 16 bits available
289 * in value->extra. This function requires that value->flags have the
290 * CborIteratorFlag_IntegerValueTooLarge flag set.
291 *
292 * This function is also used to extract single- and double-precision floating
293 * point values (SinglePrecisionFloat == Value32Bit and DoublePrecisionFloat ==
294 * Value64Bit).
295 */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700296uint64_t _cbor_value_decode_int64_internal(const CborValue *value)
297{
Thiago Macieira2312efd2015-05-06 16:07:48 -0700298 assert(value->flags & CborIteratorFlag_IntegerValueTooLarge ||
299 value->type == CborFloatType || value->type == CborDoubleType);
Thiago Macieira851c4812015-05-08 15:23:20 -0700300
Thiago Macieiradbc01292016-06-06 17:02:25 -0700301 /* since the additional information can only be Value32Bit or Value64Bit,
302 * we just need to test for the one bit those two options differ */
Thiago Macieira851c4812015-05-08 15:23:20 -0700303 assert((*value->ptr & SmallValueMask) == Value32Bit || (*value->ptr & SmallValueMask) == Value64Bit);
304 if ((*value->ptr & 1) == (Value32Bit & 1))
Thiago Macieira54a0e102015-05-05 21:25:06 -0700305 return get32(value->ptr + 1);
306
307 assert((*value->ptr & SmallValueMask) == Value64Bit);
308 return get64(value->ptr + 1);
309}
310
311/**
312 * Initializes the CBOR parser for parsing \a size bytes beginning at \a
313 * buffer. Parsing will use flags set in \a flags. The iterator to the first
314 * element is returned in \a it.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700315 *
316 * The \a parser structure needs to remain valid throughout the decoding
317 * process. It is not thread-safe to share one CborParser among multiple
318 * threads iterating at the same time, but the object can be copied so multiple
319 * threads can iterate.
Thiago Macieira54a0e102015-05-05 21:25:06 -0700320 */
Thiago Macieira5752ce52015-06-16 12:10:03 -0700321CborError cbor_parser_init(const uint8_t *buffer, size_t size, int flags, CborParser *parser, CborValue *it)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700322{
323 memset(parser, 0, sizeof(*parser));
324 parser->end = buffer + size;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700325 parser->flags = flags;
326 it->parser = parser;
327 it->ptr = buffer;
Thiago Macieiradbc01292016-06-06 17:02:25 -0700328 it->remaining = 1; /* there's one type altogether, usually an array or map */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700329 return preparse_value(it);
Thiago Macieira2312efd2015-05-06 16:07:48 -0700330}
331
332/**
Thiago Macieira46a818e2015-10-08 15:13:05 +0200333 * \fn bool cbor_value_at_end(const CborValue *it)
334 *
335 * Returns true if \a it has reached the end of the iteration, usually when
Thiago Macieira740e29d2016-07-07 13:32:47 -0700336 * advancing after the last item in an array or map.
Thiago Macieira46a818e2015-10-08 15:13:05 +0200337 *
Thiago Macieira740e29d2016-07-07 13:32:47 -0700338 * In the case of the outermost CborValue object, this function returns true
339 * after decoding a single element. A pointer to the first byte of the
340 * remaining data (if any) can be obtained with cbor_value_get_next_byte().
341 *
342 * \sa cbor_value_advance(), cbor_value_is_valid(), cbor_value_get_next_byte()
343 */
344
345/**
346 * \fn const uint8_t *cbor_value_get_next_byte(const CborValue *it)
347 *
348 * Returns a pointer to the next byte that would be decoded if this CborValue
349 * object were advanced.
350 *
351 * This function is useful if cbor_value_at_end() returns true for the
352 * outermost CborValue: the pointer returned is the first byte of the data
353 * remaining in the buffer, if any. Code can decide whether to begin decoding a
354 * new CBOR data stream from this point, or parse some other data appended to
355 * the same buffer.
356 *
357 * This function may be used even after a parsing error. If that occurred,
358 * then this function returns a pointer to where the parsing error occurred.
359 * Note that the error recovery is not precise and the pointer may not indicate
360 * the exact byte containing bad data.
361 *
362 * \sa cbor_value_at_end()
Thiago Macieira46a818e2015-10-08 15:13:05 +0200363 */
364
365/**
366 * \fn bool cbor_value_is_valid(const CborValue *it)
367 *
368 * Returns true if the iterator \a it contains a valid value. Invalid iterators
369 * happen when iteration reaches the end of a container (see \ref
370 * cbor_value_at_end()) or when a search function resulted in no matches.
371 *
372 * \sa cbor_value_advance(), cbor_valie_at_end(), cbor_value_get_type()
373 */
374
375/**
Thiago Macieira2312efd2015-05-06 16:07:48 -0700376 * Advances the CBOR value \a it by one fixed-size position. Fixed-size types
377 * are: integers, tags, simple types (including boolean, null and undefined
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700378 * values) and floating point types.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700379 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200380 * If the type is not of fixed size, this function has undefined behavior. Code
381 * must be sure that the current type is one of the fixed-size types before
382 * calling this function. This function is provided because it can guarantee
383 * that runs in constant time (O(1)).
384 *
385 * If the caller is not able to determine whether the type is fixed or not, code
386 * can use the cbor_value_advance() function instead.
387 *
388 * \sa cbor_value_at_end(), cbor_value_advance(), cbor_value_enter_container(), cbor_value_leave_container()
Thiago Macieira2312efd2015-05-06 16:07:48 -0700389 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700390CborError cbor_value_advance_fixed(CborValue *it)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700391{
Thiago Macieira2312efd2015-05-06 16:07:48 -0700392 assert(it->type != CborInvalidType);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700393 assert(is_fixed_type(it->type));
394 if (!it->remaining)
395 return CborErrorAdvancePastEOF;
396 return advance_internal(it);
Thiago Macieira54a0e102015-05-05 21:25:06 -0700397}
398
Thiago Macieira4a99af92015-05-12 10:41:45 +0900399static CborError advance_recursive(CborValue *it, int nestingLevel)
400{
401 if (is_fixed_type(it->type))
402 return advance_internal(it);
403
404 if (!cbor_value_is_container(it)) {
405 size_t len = SIZE_MAX;
Thiago Macieiraff130bc2015-06-19 15:15:33 -0700406 return _cbor_value_copy_string(it, NULL, &len, it);
Thiago Macieira4a99af92015-05-12 10:41:45 +0900407 }
408
Thiago Macieiradbc01292016-06-06 17:02:25 -0700409 /* map or array */
Thiago Macieira4a99af92015-05-12 10:41:45 +0900410 if (nestingLevel == CBOR_PARSER_MAX_RECURSIONS)
411 return CborErrorNestingTooDeep;
412
413 CborError err;
414 CborValue recursed;
415 err = cbor_value_enter_container(it, &recursed);
416 if (err)
417 return err;
418 while (!cbor_value_at_end(&recursed)) {
419 err = advance_recursive(&recursed, nestingLevel + 1);
420 if (err)
421 return err;
422 }
423 return cbor_value_leave_container(it, &recursed);
424}
425
426
Thiago Macieira2312efd2015-05-06 16:07:48 -0700427/**
428 * Advances the CBOR value \a it by one element, skipping over containers.
429 * Unlike cbor_value_advance_fixed(), this function can be called on a CBOR
430 * value of any type. However, if the type is a container (map or array) or a
431 * string with a chunked payload, this function will not run in constant time
432 * and will recurse into itself (it will run on O(n) time for the number of
433 * elements or chunks and will use O(n) memory for the number of nested
434 * containers).
435 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200436 * \sa cbor_value_at_end(), cbor_value_advance_fixed(), cbor_value_enter_container(), cbor_value_leave_container()
Thiago Macieira2312efd2015-05-06 16:07:48 -0700437 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700438CborError cbor_value_advance(CborValue *it)
Thiago Macieira2312efd2015-05-06 16:07:48 -0700439{
440 assert(it->type != CborInvalidType);
441 if (!it->remaining)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700442 return CborErrorAdvancePastEOF;
Thiago Macieira4a99af92015-05-12 10:41:45 +0900443 return advance_recursive(it, 0);
Thiago Macieira2312efd2015-05-06 16:07:48 -0700444}
445
446/**
Thiago Macieira46a818e2015-10-08 15:13:05 +0200447 * \fn bool cbor_value_is_tag(const CborValue *value)
448 *
449 * Returns true if the iterator \a value is valid and points to a CBOR tag.
450 *
451 * \sa cbor_value_get_tag(), cbor_value_skip_tag()
452 */
453
454/**
455 * \fn CborError cbor_value_get_tag(const CborValue *value, CborTag *result)
456 *
457 * Retrieves the CBOR tag value that \a value points to and stores it in \a
458 * result. If the iterator \a value does not point to a CBOR tag value, the
459 * behavior is undefined, so checking with \ref cbor_value_get_type or with
460 * \ref cbor_value_is_tag is recommended.
461 *
462 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_tag()
463 */
464
465/**
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700466 * Advances the CBOR value \a it until it no longer points to a tag. If \a it is
467 * already not pointing to a tag, then this function returns it unchanged.
468 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200469 * This function does not run in constant time: it will run on O(n) for n being
470 * the number of tags. It does use constant memory (O(1) memory requirements).
471 *
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700472 * \sa cbor_value_advance_fixed(), cbor_value_advance()
473 */
474CborError cbor_value_skip_tag(CborValue *it)
475{
476 while (cbor_value_is_tag(it)) {
477 CborError err = cbor_value_advance_fixed(it);
478 if (err)
479 return err;
480 }
481 return CborNoError;
482}
483
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700484/**
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700485 * \fn bool cbor_value_is_container(const CborValue *it)
486 *
Thiago Macieira2312efd2015-05-06 16:07:48 -0700487 * Returns true if the \a it value is a container and requires recursion in
488 * order to decode (maps and arrays), false otherwise.
489 */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700490
Thiago Macieira2312efd2015-05-06 16:07:48 -0700491/**
492 * Creates a CborValue iterator pointing to the first element of the container
493 * represented by \a it and saves it in \a recursed. The \a it container object
494 * needs to be kept and passed again to cbor_value_leave_container() in order
495 * to continue iterating past this container.
496 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200497 * The \a it CborValue iterator must point to a container.
498 *
Thiago Macieira2312efd2015-05-06 16:07:48 -0700499 * \sa cbor_value_is_container(), cbor_value_leave_container(), cbor_value_advance()
500 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700501CborError cbor_value_enter_container(const CborValue *it, CborValue *recursed)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700502{
Thiago Macieira56d99832015-05-07 14:34:27 -0700503 CborError err;
Thiago Macieira2312efd2015-05-06 16:07:48 -0700504 assert(cbor_value_is_container(it));
Thiago Macieira54a0e102015-05-05 21:25:06 -0700505 *recursed = *it;
Thiago Macieira56d99832015-05-07 14:34:27 -0700506
Thiago Macieira54a0e102015-05-05 21:25:06 -0700507 if (it->flags & CborIteratorFlag_UnknownLength) {
508 recursed->remaining = UINT32_MAX;
Thiago Macieira56d99832015-05-07 14:34:27 -0700509 ++recursed->ptr;
510 err = preparse_value(recursed);
511 if (err != CborErrorUnexpectedBreak)
512 return err;
Thiago Macieiradbc01292016-06-06 17:02:25 -0700513 /* actually, break was expected here
514 * it's just an empty container */
Thiago Macieira56d99832015-05-07 14:34:27 -0700515 ++recursed->ptr;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700516 } else {
Thiago Macieira56d99832015-05-07 14:34:27 -0700517 uint64_t len;
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700518 err = extract_number(&recursed->ptr, recursed->parser->end, &len);
Thiago Macieira56d99832015-05-07 14:34:27 -0700519 assert(err == CborNoError);
Thiago Macieira56d99832015-05-07 14:34:27 -0700520
Thiago Macieirae12dfd02016-06-07 16:29:25 -0700521 recursed->remaining = (uint32_t)len;
Thiago Macieira3f76f632015-05-12 10:10:09 +0900522 if (recursed->remaining != len || len == UINT32_MAX) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700523 /* back track the pointer to indicate where the error occurred */
Thiago Macieira3f76f632015-05-12 10:10:09 +0900524 recursed->ptr = it->ptr;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700525 return CborErrorDataTooLarge;
Thiago Macieira3f76f632015-05-12 10:10:09 +0900526 }
Thiago Macieirace16f052015-05-07 23:14:25 -0700527 if (recursed->type == CborMapType) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700528 /* maps have keys and values, so we need to multiply by 2 */
Thiago Macieira3f76f632015-05-12 10:10:09 +0900529 if (recursed->remaining > UINT32_MAX / 2) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700530 /* back track the pointer to indicate where the error occurred */
Thiago Macieira3f76f632015-05-12 10:10:09 +0900531 recursed->ptr = it->ptr;
Thiago Macieirace16f052015-05-07 23:14:25 -0700532 return CborErrorDataTooLarge;
Thiago Macieira3f76f632015-05-12 10:10:09 +0900533 }
Thiago Macieirace16f052015-05-07 23:14:25 -0700534 recursed->remaining *= 2;
535 }
Thiago Macieira56d99832015-05-07 14:34:27 -0700536 if (len != 0)
537 return preparse_value(recursed);
Thiago Macieira54a0e102015-05-05 21:25:06 -0700538 }
Thiago Macieira56d99832015-05-07 14:34:27 -0700539
Thiago Macieiradbc01292016-06-06 17:02:25 -0700540 /* the case of the empty container */
Thiago Macieira56d99832015-05-07 14:34:27 -0700541 recursed->type = CborInvalidType;
542 recursed->remaining = 0;
543 return CborNoError;
Thiago Macieirac70169f2015-05-06 07:49:44 -0700544}
545
Thiago Macieira2312efd2015-05-06 16:07:48 -0700546/**
547 * Updates \a it to point to the next element after the container. The \a
Thiago Macieira56d99832015-05-07 14:34:27 -0700548 * recursed object needs to point to the element obtained either by advancing
549 * the last element of the container (via cbor_value_advance(),
550 * cbor_value_advance_fixed(), a nested cbor_value_leave_container(), or the \c
551 * next pointer from cbor_value_copy_string() or cbor_value_dup_string()).
Thiago Macieira2312efd2015-05-06 16:07:48 -0700552 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200553 * The \a it and \a recursed parameters must be the exact same as passed to
554 * cbor_value_enter_container().
555 *
Thiago Macieira2312efd2015-05-06 16:07:48 -0700556 * \sa cbor_value_enter_container(), cbor_value_at_end()
557 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700558CborError cbor_value_leave_container(CborValue *it, const CborValue *recursed)
Thiago Macieirac70169f2015-05-06 07:49:44 -0700559{
Thiago Macieira2312efd2015-05-06 16:07:48 -0700560 assert(cbor_value_is_container(it));
Thiago Macieira56d99832015-05-07 14:34:27 -0700561 assert(recursed->type == CborInvalidType);
Thiago Macieirac70169f2015-05-06 07:49:44 -0700562 it->ptr = recursed->ptr;
Thiago Macieira56d99832015-05-07 14:34:27 -0700563 return preparse_next_value(it);
Thiago Macieirac70169f2015-05-06 07:49:44 -0700564}
565
Thiago Macieira46a818e2015-10-08 15:13:05 +0200566
Thiago Macieira2312efd2015-05-06 16:07:48 -0700567/**
Thiago Macieira46a818e2015-10-08 15:13:05 +0200568 * \fn CborType cbor_value_get_type(const CborValue *value)
569 *
570 * Returns the type of the CBOR value that the iterator \a value points to. If
571 * \a value does not point to a valid value, this function returns \ref
572 * CborInvalidType.
573 *
574 * TinyCBOR also provides functions to test directly if a given CborValue object
575 * is of a given type, like cbor_value_is_text_string() and cbor_value_is_null().
576 *
577 * \sa cbor_value_is_valid()
578 */
579
580/**
581 * \fn bool cbor_value_is_null(const CborValue *value)
582 *
583 * Returns true if the iterator \a value is valid and points to a CBOR null type.
584 *
585 * \sa cbor_value_is_valid(), cbor_value_is_undefined()
586 */
587
588/**
589 * \fn bool cbor_value_is_undefined(const CborValue *value)
590 *
591 * Returns true if the iterator \a value is valid and points to a CBOR undefined type.
592 *
593 * \sa cbor_value_is_valid(), cbor_value_is_null()
594 */
595
596/**
597 * \fn bool cbor_value_is_boolean(const CborValue *value)
598 *
599 * Returns true if the iterator \a value is valid and points to a CBOR boolean
600 * type (true or false).
601 *
602 * \sa cbor_value_is_valid(), cbor_value_get_boolean()
603 */
604
605/**
606 * \fn CborError cbor_value_get_boolean(const CborValue *value, bool *result)
607 *
608 * Retrieves the boolean value that \a value points to and stores it in \a
609 * result. If the iterator \a value does not point to a boolean value, the
610 * behavior is undefined, so checking with \ref cbor_value_get_type or with
611 * \ref cbor_value_is_boolean is recommended.
612 *
613 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_boolean()
614 */
615
616/**
617 * \fn bool cbor_value_is_simple_type(const CborValue *value)
618 *
619 * Returns true if the iterator \a value is valid and points to a CBOR Simple Type
620 * type (other than true, false, null and undefined).
621 *
622 * \sa cbor_value_is_valid(), cbor_value_get_simple_type()
623 */
624
625/**
626 * \fn CborError cbor_value_get_simple_type(const CborValue *value, uint8_t *result)
627 *
628 * Retrieves the CBOR Simple Type value that \a value points to and stores it
629 * in \a result. If the iterator \a value does not point to a simple_type
630 * value, the behavior is undefined, so checking with \ref cbor_value_get_type
631 * or with \ref cbor_value_is_simple_type is recommended.
632 *
633 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_simple_type()
634 */
635
636/**
637 * \fn bool cbor_value_is_integer(const CborValue *value)
638 *
639 * Returns true if the iterator \a value is valid and points to a CBOR integer
640 * type.
641 *
642 * \sa cbor_value_is_valid(), cbor_value_get_int, cbor_value_get_int64, cbor_value_get_uint64, cbor_value_get_raw_integer
643 */
644
645/**
646 * \fn bool cbor_value_is_unsigned_integer(const CborValue *value)
647 *
648 * Returns true if the iterator \a value is valid and points to a CBOR unsigned
649 * integer type (positive values or zero).
650 *
651 * \sa cbor_value_is_valid(), cbor_value_get_uint64()
652 */
653
654/**
655 * \fn bool cbor_value_is_negative_integer(const CborValue *value)
656 *
657 * Returns true if the iterator \a value is valid and points to a CBOR negative
658 * integer type.
659 *
660 * \sa cbor_value_is_valid(), cbor_value_get_int, cbor_value_get_int64, cbor_value_get_raw_integer
661 */
662
663/**
664 * \fn CborError cbor_value_get_int(const CborValue *value, int *result)
665 *
666 * Retrieves the CBOR integer value that \a value points to and stores it in \a
667 * result. If the iterator \a value does not point to an integer value, the
668 * behavior is undefined, so checking with \ref cbor_value_get_type or with
669 * \ref cbor_value_is_integer is recommended.
670 *
671 * Note that this function does not do range-checking: integral values that do
672 * not fit in a variable of type \c{int} are silently truncated to fit. Use
673 * cbor_value_get_int_checked() that is not acceptable.
674 *
675 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
676 */
677
678/**
679 * \fn CborError cbor_value_get_int64(const CborValue *value, int64_t *result)
680 *
681 * Retrieves the CBOR integer value that \a value points to and stores it in \a
682 * result. If the iterator \a value does not point to an integer value, the
683 * behavior is undefined, so checking with \ref cbor_value_get_type or with
684 * \ref cbor_value_is_integer is recommended.
685 *
686 * Note that this function does not do range-checking: integral values that do
687 * not fit in a variable of type \c{int64_t} are silently truncated to fit. Use
688 * cbor_value_get_int64_checked() that is not acceptable.
689 *
690 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
691 */
692
693/**
694 * \fn CborError cbor_value_get_uint64(const CborValue *value, uint64_t *result)
695 *
696 * Retrieves the CBOR integer value that \a value points to and stores it in \a
697 * result. If the iterator \a value does not point to an unsigned integer
698 * value, the behavior is undefined, so checking with \ref cbor_value_get_type
699 * or with \ref cbor_value_is_unsigned_integer is recommended.
700 *
701 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_unsigned_integer()
702 */
703
704/**
705 * \fn CborError cbor_value_get_raw_integer(const CborValue *value, uint64_t *result)
706 *
707 * Retrieves the CBOR integer value that \a value points to and stores it in \a
708 * result. If the iterator \a value does not point to an integer value, the
709 * behavior is undefined, so checking with \ref cbor_value_get_type or with
710 * \ref cbor_value_is_integer is recommended.
711 *
712 * This function is provided because CBOR negative integers can assume values
713 * that cannot be represented with normal 64-bit integer variables.
714 *
715 * If the integer is unsigned (that is, if cbor_value_is_unsigned_integer()
716 * returns true), then \a result will contain the actual value. If the integer
717 * is negative, then \a result will contain the absolute value of that integer,
718 * minus one. That is, \c {actual = -result - 1}. On architectures using two's
719 * complement for representation of negative integers, it is equivalent to say
720 * that \a result will contain the bitwise negation of the actual value.
721 *
722 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
723 */
724
725/**
Thiago Macieira0f02e792016-07-07 19:55:08 -0700726 * Retrieves the CBOR integer value that \a value points to and stores it in \a
727 * result. If the iterator \a value does not point to an integer value, the
728 * behavior is undefined, so checking with \ref cbor_value_get_type or with
729 * \ref cbor_value_is_integer is recommended.
730 *
731 * Unlike cbor_value_get_int64(), this function performs a check to see if the
732 * stored integer fits in \a result without data loss. If the number is outside
733 * the valid range for the data type, this function returns the recoverable
734 * error CborErrorDataTooLarge. In that case, use either
735 * cbor_value_get_uint64() (if the number is positive) or
736 * cbor_value_get_raw_integer().
737 *
738 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer(), cbor_value_get_int64()
739 */
740CborError cbor_value_get_int64_checked(const CborValue *value, int64_t *result)
741{
742 assert(cbor_value_is_integer(value));
743 uint64_t v = _cbor_value_extract_int64_helper(value);
744
745 /* Check before converting, as the standard says (C11 6.3.1.3 paragraph 3):
746 * "[if] the new type is signed and the value cannot be represented in it; either the
747 * result is implementation-defined or an implementation-defined signal is raised."
748 *
749 * The range for int64_t is -2^63 to 2^63-1 (int64_t is required to be
750 * two's complement, C11 7.20.1.1 paragraph 3), which in CBOR is
751 * represented the same way, differing only on the "sign bit" (the major
752 * type).
753 */
754
755 if (unlikely(v > (uint64_t)INT64_MAX))
756 return CborErrorDataTooLarge;
757
758 *result = v;
759 if (value->flags & CborIteratorFlag_NegativeInteger)
760 *result = -*result - 1;
761 return CborNoError;
762}
763
764/**
765 * Retrieves the CBOR integer value that \a value points to and stores it in \a
766 * result. If the iterator \a value does not point to an integer value, the
767 * behavior is undefined, so checking with \ref cbor_value_get_type or with
768 * \ref cbor_value_is_integer is recommended.
769 *
770 * Unlike cbor_value_get_int(), this function performs a check to see if the
771 * stored integer fits in \a result without data loss. If the number is outside
772 * the valid range for the data type, this function returns the recoverable
773 * error CborErrorDataTooLarge. In that case, use one of the other integer
774 * functions to obtain the value.
775 *
776 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer(), cbor_value_get_int64(),
777 * cbor_value_get_uint64(), cbor_value_get_int64_checked(), cbor_value_get_raw_integer()
778 */
779CborError cbor_value_get_int_checked(const CborValue *value, int *result)
780{
781 assert(cbor_value_is_integer(value));
782 uint64_t v = _cbor_value_extract_int64_helper(value);
783
784 /* Check before converting, as the standard says (C11 6.3.1.3 paragraph 3):
785 * "[if] the new type is signed and the value cannot be represented in it; either the
786 * result is implementation-defined or an implementation-defined signal is raised."
787 *
788 * But we can convert from signed to unsigned without fault (paragraph 2).
789 *
790 * The range for int is implementation-defined and int is not guaranteed use
791 * two's complement representation (int32_t is).
792 */
793
794 if (value->flags & CborIteratorFlag_NegativeInteger) {
795 if (unlikely(v > (unsigned) -(INT_MIN + 1)))
796 return CborErrorDataTooLarge;
797
798 *result = v;
799 *result = -*result - 1;
800 } else {
801 if (unlikely(v > (uint64_t)INT_MAX))
802 return CborErrorDataTooLarge;
803
804 *result = v;
805 }
806 return CborNoError;
807
808}
809
810/**
Thiago Macieira46a818e2015-10-08 15:13:05 +0200811 * \fn bool cbor_value_is_length_known(const CborValue *value)
812 *
813 * Returns true if the length of this type is known without calculation. That
814 * is, if the length of this CBOR string, map or array is encoded in the data
815 * stream, this function returns true. If the length is not encoded, it returns
816 * false.
817 *
818 * If the length is known, code can call cbor_value_get_string_length(),
819 * cbor_value_get_array_length() or cbor_value_get_map_length() to obtain the
820 * length. If the length is not known but is necessary, code can use the
821 * cbor_value_calculate_string_length() function (no equivalent function is
822 * provided for maps and arrays).
823 */
824
825/**
826 * \fn bool cbor_value_is_text_string(const CborValue *value)
827 *
828 * Returns true if the iterator \a value is valid and points to a CBOR text
829 * string. CBOR text strings are UTF-8 encoded and usually contain
830 * human-readable text.
831 *
832 * \sa cbor_value_is_valid(), cbor_value_get_string_length(), cbor_value_calculate_string_length(),
833 * cbor_value_copy_text_string(), cbor_value_dup_text_string()
834 */
835
836/**
837 * \fn bool cbor_value_is_byte_string(const CborValue *value)
838 *
839 * Returns true if the iterator \a value is valid and points to a CBOR text
840 * string. CBOR byte strings are binary data with no specified encoding or
841 * format.
842 *
843 * \sa cbor_value_is_valid(), cbor_value_get_string_length(), cbor_value_calculate_string_length(),
844 * cbor_value_copy_byte_string(), cbor_value_dup_byte_string()
845 */
846
847/**
848 * \fn CborError cbor_value_get_string_length(const CborValue *value, size_t *length)
849 *
850 * Extracts the length of the byte or text string that \a value points to and
851 * stores it in \a result. If the iterator \a value does not point to a text
852 * string or a byte string, the behaviour is undefined, so checking with \ref
853 * cbor_value_get_type, with \ref cbor_value_is_text_string or \ref
854 * cbor_value_is_byte_string is recommended.
855 *
856 * If the length of this string is not encoded in the CBOR data stream, this
857 * function will return the recoverable error CborErrorUnknownLength. You may
858 * also check whether that is the case by using cbor_value_is_length_known().
859 *
860 * If the length of the string is required but the length was not encoded, use
861 * cbor_value_calculate_string_length(), but note that that function does not
862 * run in constant time.
863 *
864 * \note On 32-bit platforms, this function will return error condition of \ref
865 * CborErrorDataTooLarge if the stream indicates a length that is too big to
866 * fit in 32-bit.
867 *
868 * \sa cbor_value_is_valid(), cbor_value_is_length_known(), cbor_value_calculate_string_length()
869 */
870
871/**
872 * Calculates the length of the byte or text string that \a value points to and
873 * stores it in \a len. If the iterator \a value does not point to a text
874 * string or a byte string, the behaviour is undefined, so checking with \ref
875 * cbor_value_get_type, with \ref cbor_value_is_text_string or \ref
876 * cbor_value_is_byte_string is recommended.
877 *
878 * This function is different from cbor_value_get_string_length() in that it
879 * calculates the length even for strings sent in chunks. For that reason, this
880 * function may not run in constant time (it will run in O(n) time on the
881 * number of chunks). It does use constant memory (O(1)).
Thiago Macieira2312efd2015-05-06 16:07:48 -0700882 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700883 * \note On 32-bit platforms, this function will return error condition of \ref
884 * CborErrorDataTooLarge if the stream indicates a length that is too big to
885 * fit in 32-bit.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700886 *
887 * \sa cbor_value_get_string_length(), cbor_value_copy_string(), cbor_value_is_length_known()
888 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700889CborError cbor_value_calculate_string_length(const CborValue *value, size_t *len)
Thiago Macieira2312efd2015-05-06 16:07:48 -0700890{
Thiago Macieira9ae05812015-05-11 15:09:09 +0900891 *len = SIZE_MAX;
Thiago Macieiraff130bc2015-06-19 15:15:33 -0700892 return _cbor_value_copy_string(value, NULL, len, NULL);
Thiago Macieirac70169f2015-05-06 07:49:44 -0700893}
894
Thiago Macieiradbc01292016-06-06 17:02:25 -0700895/* We return uintptr_t so that we can pass memcpy directly as the iteration
896 * function. The choice is to optimize for memcpy, which is used in the base
897 * parser API (cbor_value_copy_string), while memcmp is used in convenience API
898 * only. */
Thiago Macieira5752ce52015-06-16 12:10:03 -0700899typedef uintptr_t (*IterateFunction)(char *, const uint8_t *, size_t);
Thiago Macieira9ae05812015-05-11 15:09:09 +0900900
Thiago Macieira5752ce52015-06-16 12:10:03 -0700901static uintptr_t iterate_noop(char *dest, const uint8_t *src, size_t len)
Thiago Macieira9ae05812015-05-11 15:09:09 +0900902{
903 (void)dest;
904 (void)src;
905 (void)len;
906 return true;
907}
908
Thiago Macieira5752ce52015-06-16 12:10:03 -0700909static uintptr_t iterate_memcmp(char *s1, const uint8_t *s2, size_t len)
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700910{
Thiago Macieira5752ce52015-06-16 12:10:03 -0700911 return memcmp(s1, (const char *)s2, len) == 0;
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700912}
913
Thiago Macieira9ae05812015-05-11 15:09:09 +0900914static CborError iterate_string_chunks(const CborValue *value, char *buffer, size_t *buflen,
915 bool *result, CborValue *next, IterateFunction func)
916{
917 assert(cbor_value_is_byte_string(value) || cbor_value_is_text_string(value));
918
919 size_t total;
920 CborError err;
Thiago Macieira5752ce52015-06-16 12:10:03 -0700921 const uint8_t *ptr = value->ptr;
Thiago Macieira9ae05812015-05-11 15:09:09 +0900922 if (cbor_value_is_length_known(value)) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700923 /* easy case: fixed length */
Thiago Macieira9ae05812015-05-11 15:09:09 +0900924 err = extract_length(value->parser, &ptr, &total);
925 if (err)
926 return err;
Thiago Macieira63abed92015-10-28 17:01:14 -0700927 if (total > (size_t)(value->parser->end - ptr))
Thiago Macieira9ae05812015-05-11 15:09:09 +0900928 return CborErrorUnexpectedEOF;
929 if (total <= *buflen)
Thiago Macieirae12dfd02016-06-07 16:29:25 -0700930 *result = !!func(buffer, ptr, total);
Thiago Macieira9ae05812015-05-11 15:09:09 +0900931 else
932 *result = false;
933 ptr += total;
934 } else {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700935 /* chunked */
Thiago Macieira9ae05812015-05-11 15:09:09 +0900936 ++ptr;
937 total = 0;
938 *result = true;
939 while (true) {
940 size_t chunkLen;
941 size_t newTotal;
942
943 if (ptr == value->parser->end)
944 return CborErrorUnexpectedEOF;
945
Thiago Macieira5752ce52015-06-16 12:10:03 -0700946 if (*ptr == (uint8_t)BreakByte) {
Thiago Macieira9ae05812015-05-11 15:09:09 +0900947 ++ptr;
948 break;
949 }
950
Thiago Macieiradbc01292016-06-06 17:02:25 -0700951 /* is this the right type? */
Thiago Macieira9ae05812015-05-11 15:09:09 +0900952 if ((*ptr & MajorTypeMask) != value->type)
953 return CborErrorIllegalType;
954
955 err = extract_length(value->parser, &ptr, &chunkLen);
956 if (err)
957 return err;
958
Thiago Macieira1de31a42015-06-16 16:01:16 -0700959 if (unlikely(add_check_overflow(total, chunkLen, &newTotal)))
Thiago Macieira9ae05812015-05-11 15:09:09 +0900960 return CborErrorDataTooLarge;
961
Thiago Macieira63abed92015-10-28 17:01:14 -0700962 if (chunkLen > (size_t)(value->parser->end - ptr))
Thiago Macieira9ae05812015-05-11 15:09:09 +0900963 return CborErrorUnexpectedEOF;
964
965 if (*result && *buflen >= newTotal)
Thiago Macieirae12dfd02016-06-07 16:29:25 -0700966 *result = !!func(buffer + total, ptr, chunkLen);
Thiago Macieira9ae05812015-05-11 15:09:09 +0900967 else
968 *result = false;
969
970 ptr += chunkLen;
971 total = newTotal;
972 }
973 }
974
Thiago Macieiradbc01292016-06-06 17:02:25 -0700975 /* is there enough room for the ending NUL byte? */
Thiago Macieira9ae05812015-05-11 15:09:09 +0900976 if (*result && *buflen > total)
Thiago Macieirae12dfd02016-06-07 16:29:25 -0700977 *result = !!func(buffer + total, (const uint8_t *)"", 1);
Thiago Macieira9ae05812015-05-11 15:09:09 +0900978 *buflen = total;
979
980 if (next) {
981 *next = *value;
982 next->ptr = ptr;
983 return preparse_next_value(next);
984 }
985 return CborNoError;
986}
987
Thiago Macieira2312efd2015-05-06 16:07:48 -0700988/**
Thiago Macieiraff130bc2015-06-19 15:15:33 -0700989 * \fn CborError cbor_value_copy_text_string(const CborValue *value, char *buffer, size_t *buflen, CborValue *next)
990 *
Thiago Macieira2312efd2015-05-06 16:07:48 -0700991 * Copies the string pointed by \a value into the buffer provided at \a buffer
992 * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
993 * copy anything and will only update the \a next value.
994 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200995 * If the iterator \a value does not point to a text string, the behaviour is
996 * undefined, so checking with \ref cbor_value_get_type or \ref
997 * cbor_value_is_text_string is recommended.
998 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700999 * If the provided buffer length was too small, this function returns an error
1000 * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
1001 * of the string in order to preallocate a buffer, use
Thiago Macieira2312efd2015-05-06 16:07:48 -07001002 * cbor_value_calculate_string_length().
1003 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -07001004 * On success, this function sets the number of bytes copied to \c{*buflen}. If
1005 * the buffer is large enough, this function will insert a null byte after the
1006 * last copied byte, to facilitate manipulation of text strings. That byte is
1007 * not included in the returned value of \c{*buflen}.
Thiago Macieira2312efd2015-05-06 16:07:48 -07001008 *
1009 * The \a next pointer, if not null, will be updated to point to the next item
1010 * after this string. If \a value points to the last item, then \a next will be
1011 * invalid.
1012 *
Thiago Macieira46a818e2015-10-08 15:13:05 +02001013 * This function may not run in constant time (it will run in O(n) time on the
1014 * number of chunks). It requires constant memory (O(1)).
1015 *
Thiago Macieira2312efd2015-05-06 16:07:48 -07001016 * \note This function does not perform UTF-8 validation on the incoming text
1017 * string.
1018 *
Thiago Macieiraff130bc2015-06-19 15:15:33 -07001019 * \sa cbor_value_dup_text_string(), cbor_value_copy_byte_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
Thiago Macieira2312efd2015-05-06 16:07:48 -07001020 */
Thiago Macieiraff130bc2015-06-19 15:15:33 -07001021
1022/**
1023 * \fn CborError cbor_value_copy_byte_string(const CborValue *value, uint8_t *buffer, size_t *buflen, CborValue *next)
1024 *
1025 * Copies the string pointed by \a value into the buffer provided at \a buffer
1026 * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
1027 * copy anything and will only update the \a next value.
1028 *
Thiago Macieira46a818e2015-10-08 15:13:05 +02001029 * If the iterator \a value does not point to a byte string, the behaviour is
1030 * undefined, so checking with \ref cbor_value_get_type or \ref
1031 * cbor_value_is_byte_string is recommended.
1032 *
Thiago Macieiraff130bc2015-06-19 15:15:33 -07001033 * If the provided buffer length was too small, this function returns an error
1034 * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
1035 * of the string in order to preallocate a buffer, use
1036 * cbor_value_calculate_string_length().
1037 *
1038 * On success, this function sets the number of bytes copied to \c{*buflen}. If
1039 * the buffer is large enough, this function will insert a null byte after the
1040 * last copied byte, to facilitate manipulation of null-terminated strings.
1041 * That byte is not included in the returned value of \c{*buflen}.
1042 *
1043 * The \a next pointer, if not null, will be updated to point to the next item
1044 * after this string. If \a value points to the last item, then \a next will be
1045 * invalid.
1046 *
Thiago Macieira46a818e2015-10-08 15:13:05 +02001047 * This function may not run in constant time (it will run in O(n) time on the
1048 * number of chunks). It requires constant memory (O(1)).
1049 *
Thiago Macieiraff130bc2015-06-19 15:15:33 -07001050 * \sa cbor_value_dup_text_string(), cbor_value_copy_text_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
1051 */
1052
1053CborError _cbor_value_copy_string(const CborValue *value, void *buffer,
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -07001054 size_t *buflen, CborValue *next)
Thiago Macieira2312efd2015-05-06 16:07:48 -07001055{
Thiago Macieira9ae05812015-05-11 15:09:09 +09001056 bool copied_all;
Thiago Macieiraed5b57c2015-07-07 16:38:27 -07001057 CborError err = iterate_string_chunks(value, (char*)buffer, buflen, &copied_all, next,
Thiago Macieira9ae05812015-05-11 15:09:09 +09001058 buffer ? (IterateFunction)memcpy : iterate_noop);
1059 return err ? err :
1060 copied_all ? CborNoError : CborErrorOutOfMemory;
Thiago Macieirac70169f2015-05-06 07:49:44 -07001061}
1062
Thiago Macieirac4a73c62015-05-09 18:14:11 -07001063/**
1064 * Compares the entry \a value with the string \a string and store the result
Thiago Macieira46a818e2015-10-08 15:13:05 +02001065 * in \a result. If the value is different from \a string \a result will
1066 * contain \c false.
Thiago Macieirac4a73c62015-05-09 18:14:11 -07001067 *
1068 * The entry at \a value may be a tagged string. If \a is not a string or a
1069 * tagged string, the comparison result will be false.
Thiago Macieira46a818e2015-10-08 15:13:05 +02001070 *
1071 * CBOR requires text strings to be encoded in UTF-8, but this function does
1072 * not validate either the strings in the stream or the string \a string to be
1073 * matched. Moreover, comparison is done on strict codepoint comparison,
1074 * without any Unicode normalization.
1075 *
1076 * This function may not run in constant time (it will run in O(n) time on the
1077 * number of chunks). It requires constant memory (O(1)).
1078 *
1079 * \sa cbor_value_skip_tag(), cbor_value_copy_text_string()
Thiago Macieirac4a73c62015-05-09 18:14:11 -07001080 */
1081CborError cbor_value_text_string_equals(const CborValue *value, const char *string, bool *result)
1082{
1083 CborValue copy = *value;
1084 CborError err = cbor_value_skip_tag(&copy);
1085 if (err)
1086 return err;
1087 if (!cbor_value_is_text_string(&copy)) {
1088 *result = false;
1089 return CborNoError;
1090 }
1091
1092 size_t len = strlen(string);
1093 return iterate_string_chunks(&copy, CONST_CAST(char *, string), &len, result, NULL, iterate_memcmp);
1094}
1095
1096/**
Thiago Macieira46a818e2015-10-08 15:13:05 +02001097 * \fn bool cbor_value_is_array(const CborValue *value)
Thiago Macieira7b623c22015-05-11 15:52:14 +09001098 *
Thiago Macieira46a818e2015-10-08 15:13:05 +02001099 * Returns true if the iterator \a value is valid and points to a CBOR array.
1100 *
1101 * \sa cbor_value_is_valid(), cbor_value_is_map()
1102 */
1103
1104/**
1105 * \fn CborError cbor_value_get_array_length(const CborValue *value, size_t *length)
1106 *
1107 * Extracts the length of the CBOR array that \a value points to and stores it
1108 * in \a result. If the iterator \a value does not point to a CBOR array, the
1109 * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
1110 * cbor_value_is_array is recommended.
1111 *
1112 * If the length of this array is not encoded in the CBOR data stream, this
1113 * function will return the recoverable error CborErrorUnknownLength. You may
1114 * also check whether that is the case by using cbor_value_is_length_known().
1115 *
1116 * \note On 32-bit platforms, this function will return error condition of \ref
1117 * CborErrorDataTooLarge if the stream indicates a length that is too big to
1118 * fit in 32-bit.
1119 *
1120 * \sa cbor_value_is_valid(), cbor_value_is_length_known()
1121 */
1122
1123/**
1124 * \fn bool cbor_value_is_map(const CborValue *value)
1125 *
1126 * Returns true if the iterator \a value is valid and points to a CBOR map.
1127 *
1128 * \sa cbor_value_is_valid(), cbor_value_is_array()
1129 */
1130
1131/**
1132 * \fn CborError cbor_value_get_map_length(const CborValue *value, size_t *length)
1133 *
1134 * Extracts the length of the CBOR map that \a value points to and stores it in
1135 * \a result. If the iterator \a value does not point to a CBOR map, the
1136 * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
1137 * cbor_value_is_map is recommended.
1138 *
1139 * If the length of this map is not encoded in the CBOR data stream, this
1140 * function will return the recoverable error CborErrorUnknownLength. You may
1141 * also check whether that is the case by using cbor_value_is_length_known().
1142 *
1143 * \note On 32-bit platforms, this function will return error condition of \ref
1144 * CborErrorDataTooLarge if the stream indicates a length that is too big to
1145 * fit in 32-bit.
1146 *
1147 * \sa cbor_value_is_valid(), cbor_value_is_length_known()
1148 */
1149
1150/**
1151 * Attempts to find the value in map \a map that corresponds to the text string
1152 * entry \a string. If the iterator \a value does not point to a CBOR map, the
1153 * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
1154 * cbor_value_is_map is recommended.
1155 *
1156 * If the item is found, it is stored in \a result. If no item is found
1157 * matching the key, then \a result will contain an element of type \ref
1158 * CborInvalidType. Matching is performed using
1159 * cbor_value_text_string_equals(), so tagged strings will also match.
1160 *
1161 * This function has a time complexity of O(n) where n is the number of
1162 * elements in the map to be searched. In addition, this function is has O(n)
1163 * memory requirement based on the number of nested containers (maps or arrays)
1164 * found as elements of this map.
1165 *
1166 * \sa cbor_value_is_valid(), cbor_value_text_string_equals(), cbor_value_advance()
Thiago Macieira7b623c22015-05-11 15:52:14 +09001167 */
1168CborError cbor_value_map_find_value(const CborValue *map, const char *string, CborValue *element)
1169{
1170 assert(cbor_value_is_map(map));
1171 size_t len = strlen(string);
1172 CborError err = cbor_value_enter_container(map, element);
1173 if (err)
1174 goto error;
1175
1176 while (!cbor_value_at_end(element)) {
Thiago Macieiradbc01292016-06-06 17:02:25 -07001177 /* find the non-tag so we can compare */
Thiago Macieira7b623c22015-05-11 15:52:14 +09001178 err = cbor_value_skip_tag(element);
1179 if (err)
1180 goto error;
1181 if (cbor_value_is_text_string(element)) {
1182 bool equals;
1183 size_t dummyLen = len;
1184 err = iterate_string_chunks(element, CONST_CAST(char *, string), &dummyLen,
1185 &equals, element, iterate_memcmp);
1186 if (err)
1187 goto error;
1188 if (equals)
1189 return preparse_value(element);
1190 } else {
Thiago Macieiradbc01292016-06-06 17:02:25 -07001191 /* skip this key */
Thiago Macieira7b623c22015-05-11 15:52:14 +09001192 err = cbor_value_advance(element);
1193 if (err)
1194 goto error;
1195 }
1196
Thiago Macieiradbc01292016-06-06 17:02:25 -07001197 /* skip this value */
Thiago Macieira7b623c22015-05-11 15:52:14 +09001198 err = cbor_value_skip_tag(element);
1199 if (err)
1200 goto error;
1201 err = cbor_value_advance(element);
1202 if (err)
1203 goto error;
1204 }
1205
Thiago Macieiradbc01292016-06-06 17:02:25 -07001206 /* not found */
Thiago Macieira7b623c22015-05-11 15:52:14 +09001207 element->type = CborInvalidType;
1208 return CborNoError;
1209
1210error:
1211 element->type = CborInvalidType;
1212 return err;
1213}
1214
1215/**
Thiago Macieira46a818e2015-10-08 15:13:05 +02001216 * \fn bool cbor_value_is_float(const CborValue *value)
1217 *
1218 * Returns true if the iterator \a value is valid and points to a CBOR
1219 * single-precision floating point (32-bit).
1220 *
1221 * \sa cbor_value_is_valid(), cbor_value_is_double(), cbor_value_is_half_float()
1222 */
1223
1224/**
1225 * \fn CborError cbor_value_get_float(const CborValue *value, float *result)
1226 *
1227 * Retrieves the CBOR single-precision floating point (32-bit) value that \a
1228 * value points to and stores it in \a result. If the iterator \a value does
1229 * not point to a single-precision floating point value, the behavior is
1230 * undefined, so checking with \ref cbor_value_get_type or with \ref
1231 * cbor_value_is_float is recommended.
1232 *
1233 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_float(), cbor_value_get_double()
1234 */
1235
1236/**
1237 * \fn bool cbor_value_is_double(const CborValue *value)
1238 *
1239 * Returns true if the iterator \a value is valid and points to a CBOR
1240 * double-precision floating point (64-bit).
1241 *
1242 * \sa cbor_value_is_valid(), cbor_value_is_float(), cbor_value_is_half_float()
1243 */
1244
1245/**
1246 * \fn CborError cbor_value_get_double(const CborValue *value, float *result)
1247 *
1248 * Retrieves the CBOR double-precision floating point (64-bit) value that \a
1249 * value points to and stores it in \a result. If the iterator \a value does
1250 * not point to a double-precision floating point value, the behavior is
1251 * undefined, so checking with \ref cbor_value_get_type or with \ref
1252 * cbor_value_is_double is recommended.
1253 *
1254 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_double(), cbor_value_get_float()
1255 */
1256
1257/**
1258 * \fn bool cbor_value_is_half_float(const CborValue *value)
1259 *
1260 * Returns true if the iterator \a value is valid and points to a CBOR
1261 * single-precision floating point (16-bit).
1262 *
1263 * \sa cbor_value_is_valid(), cbor_value_is_double(), cbor_value_is_float()
1264 */
1265
1266/**
1267 * Retrieves the CBOR half-precision floating point (16-bit) value that \a
1268 * value points to and stores it in \a result. If the iterator \a value does
1269 * not point to a half-precision floating point value, the behavior is
1270 * undefined, so checking with \ref cbor_value_get_type or with \ref
1271 * cbor_value_is_half_float is recommended.
1272 *
1273 * Note: since the C language does not have a standard type for half-precision
1274 * floating point, this function takes a \c{void *} as a parameter for the
1275 * storage area, which must be at least 16 bits wide.
1276 *
1277 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_half_float(), cbor_value_get_float()
Thiago Macieirac4a73c62015-05-09 18:14:11 -07001278 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -07001279CborError cbor_value_get_half_float(const CborValue *value, void *result)
Thiago Macieirac70169f2015-05-06 07:49:44 -07001280{
Thiago Macieiracac5db52016-07-07 15:50:59 -07001281 assert(cbor_value_is_half_float(value));
Thiago Macieirac70169f2015-05-06 07:49:44 -07001282
Thiago Macieiradbc01292016-06-06 17:02:25 -07001283 /* size has been computed already */
Thiago Macieirac70169f2015-05-06 07:49:44 -07001284 uint16_t v = get16(value->ptr + 1);
1285 memcpy(result, &v, sizeof(v));
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -07001286 return CborNoError;
Thiago Macieira54a0e102015-05-05 21:25:06 -07001287}
Thiago Macieira46a818e2015-10-08 15:13:05 +02001288
1289/** @} */