1 /*
2  * Copyright (c) 2020 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef ZCBOR_DECODE_H__
8 #define ZCBOR_DECODE_H__
9 
10 #include <stdint.h>
11 #include <stdbool.h>
12 #include <stddef.h>
13 #include "zcbor_common.h"
14 
15 #ifdef __cplusplus
16 extern "C" {
17 #endif
18 
19 /** The zcbor_decode library provides functions for decoding CBOR data elements.
20  *
21  * See The README for an introduction to CBOR, including the meaning of pint,
22  * nint, bstr etc.
23  */
24 
25 
26 /** See @ref zcbor_new_state() */
27 void zcbor_new_decode_state(zcbor_state_t *state_array, size_t n_states,
28 		const uint8_t *payload, size_t payload_len, size_t elem_count,
29 		uint8_t *elem_state, size_t elem_state_bytes);
30 
31 /** Convenience macro for declaring and initializing a decoding state with backups.
32  *
33  *  This gives you a state variable named @p name. The variable functions like
34  *  a pointer.
35  *
36  *  @param[in]  name          The name of the new state variable.
37  *  @param[in]  num_backups   The number of backup slots to keep in the state.
38  *  @param[in]  payload       The payload to work on.
39  *  @param[in]  payload_size  The size (in bytes) of @p payload.
40  *  @param[in]  elem_count    The starting elem_count (typically 1).
41  *  @param[in]  n_flags       For use if ZCBOR_MAP_SMART_SEARCH is enabled, ignored otherwise.
42  *                            The total number of unordered map search flags needed.
43  *                            I.e. the largest number of elements expected in an unordered map,
44  *                            including elements in nested unordered maps.
45  */
46 #define ZCBOR_STATE_D(name, num_backups, payload, payload_size, elem_count, n_flags) \
47 zcbor_state_t name[((num_backups) + 2 + ZCBOR_FLAG_STATES(n_flags))]; \
48 do { \
49 	zcbor_new_decode_state(name, ZCBOR_ARRAY_SIZE(name), payload, payload_size, elem_count, \
50 			(uint8_t *)&name[(num_backups) + 1], ZCBOR_FLAG_STATES(n_flags) * sizeof(zcbor_state_t)); \
51 } while(0)
52 
53 
54 /** The following applies to all _decode() functions listed directly below.
55  *
56  * @param[inout] state        The current state of the decoding.
57  * @param[out]   result       Where to place the decoded value.
58  * @param[in]    result_size  (if present) Size in bytes of the memory at @p result
59  *
60  * @retval true   If the value was decoded correctly.
61  * @retval false  If the value has the wrong type, the payload overflowed, the
62  *                element count was exhausted, or the value was larger than can
63  *                fit in the result variable.
64  *                Use zcbor_peek_error() to see the error code.
65  */
66 bool zcbor_int32_decode(zcbor_state_t *state, int32_t *result); /* pint/nint */
67 bool zcbor_int64_decode(zcbor_state_t *state, int64_t *result); /* pint/nint */
68 bool zcbor_uint32_decode(zcbor_state_t *state, uint32_t *result); /* pint */
69 bool zcbor_uint64_decode(zcbor_state_t *state, uint64_t *result); /* pint */
70 bool zcbor_size_decode(zcbor_state_t *state, size_t *result); /* pint */
71 bool zcbor_int_decode(zcbor_state_t *state, void *result, size_t result_size); /* pint/nint */
72 bool zcbor_uint_decode(zcbor_state_t *state, void *result, size_t result_size); /* pint */
73 bool zcbor_bstr_decode(zcbor_state_t *state, struct zcbor_string *result); /* bstr */
74 bool zcbor_tstr_decode(zcbor_state_t *state, struct zcbor_string *result); /* tstr */
75 bool zcbor_tag_decode(zcbor_state_t *state, uint32_t *result);  /* CBOR tag */
76 bool zcbor_bool_decode(zcbor_state_t *state, bool *result); /* boolean CBOR simple value */
77 bool zcbor_float16_decode(zcbor_state_t *state, float *result); /* IEEE754 float16 */
78 bool zcbor_float16_bytes_decode(zcbor_state_t *state, uint16_t *result); /* IEEE754 float16 raw bytes */
79 bool zcbor_float16_32_decode(zcbor_state_t *state, float *result); /* IEEE754 float16 or float32 */
80 bool zcbor_float32_decode(zcbor_state_t *state, float *result); /* IEEE754 float32 */
81 bool zcbor_float32_64_decode(zcbor_state_t *state, double *result); /* IEEE754 float32 or float64 */
82 bool zcbor_float64_decode(zcbor_state_t *state, double *result); /* IEEE754 float64 */
83 bool zcbor_float_decode(zcbor_state_t *state, double *result); /* IEEE754 float16, float32, or float64 */
84 
85 /** The following applies to all _expect() and _pexpect() functions listed directly below.
86  *
87  * @param[inout] state     The current state of the decoding.
88  * @param[in]    expected  The expected value.
89  *
90  * @retval true   If the result was decoded correctly and has the expected value.
91  * @retval false  If the decoding failed or the result doesn't have the
92  *                expected value.
93  *                Use zcbor_peek_error() to see the error code.
94  */
95 bool zcbor_int32_expect(zcbor_state_t *state, int32_t expected); /* pint/nint */
96 bool zcbor_int64_expect(zcbor_state_t *state, int64_t expected); /* pint/nint */
97 bool zcbor_uint32_expect(zcbor_state_t *state, uint32_t expected); /* pint */
98 bool zcbor_uint64_expect(zcbor_state_t *state, uint64_t expected); /* pint */
99 bool zcbor_size_expect(zcbor_state_t *state, size_t expected); /* pint */
100 bool zcbor_bstr_expect(zcbor_state_t *state, struct zcbor_string *expected); /* bstr */
101 bool zcbor_tstr_expect(zcbor_state_t *state, struct zcbor_string *expected); /* tstr */
102 bool zcbor_tag_expect(zcbor_state_t *state, uint32_t expected); /* CBOR tag */
103 bool zcbor_bool_expect(zcbor_state_t *state, bool expected); /* boolean CBOR simple value */
104 bool zcbor_nil_expect(zcbor_state_t *state, void *unused); /* 'nil' CBOR simple value */
105 bool zcbor_undefined_expect(zcbor_state_t *state, void *unused); /* 'undefined' CBOR simple value */
106 bool zcbor_float16_expect(zcbor_state_t *state, float expected); /* IEEE754 float16 */
107 bool zcbor_float16_bytes_expect(zcbor_state_t *state, uint16_t expected); /* IEEE754 float16 raw bytes */
108 bool zcbor_float16_32_expect(zcbor_state_t *state, float expected); /* IEEE754 float16 or float32 */
109 bool zcbor_float32_expect(zcbor_state_t *state, float expected); /* IEEE754 float32 */
110 bool zcbor_float32_64_expect(zcbor_state_t *state, double expected); /* IEEE754 float32 or float64 */
111 bool zcbor_float64_expect(zcbor_state_t *state, double expected); /* IEEE754 float64 */
112 bool zcbor_float_expect(zcbor_state_t *state, double expected); /* IEEE754 float16, float32, or float64 */
113 
114 /** Like the _expect() functions but the value is passed through a pointer.
115  * (for use as a zcbor_decoder_t function) */
116 bool zcbor_int32_pexpect(zcbor_state_t *state, int32_t *expected); /* pint/nint */
117 bool zcbor_int64_pexpect(zcbor_state_t *state, int64_t *expected); /* pint/nint */
118 bool zcbor_uint32_pexpect(zcbor_state_t *state, uint32_t *expected); /* pint */
119 bool zcbor_uint64_pexpect(zcbor_state_t *state, uint64_t *expected); /* pint */
120 bool zcbor_size_pexpect(zcbor_state_t *state, size_t *expected); /* pint */
121 bool zcbor_tag_pexpect(zcbor_state_t *state, uint32_t *expected); /* CBOR tag */
122 bool zcbor_bool_pexpect(zcbor_state_t *state, bool *expected); /* boolean CBOR simple value */
123 bool zcbor_float16_pexpect(zcbor_state_t *state, float *expected); /* IEEE754 float16 */
124 bool zcbor_float16_bytes_pexpect(zcbor_state_t *state, uint16_t *expected); /* IEEE754 float16 raw bytes */
125 bool zcbor_float16_32_pexpect(zcbor_state_t *state, float *expected); /* IEEE754 float16 or float32 */
126 bool zcbor_float32_pexpect(zcbor_state_t *state, float *expected); /* IEEE754 float32 */
127 bool zcbor_float32_64_pexpect(zcbor_state_t *state, double *expected); /* IEEE754 float32 or float64 */
128 bool zcbor_float64_pexpect(zcbor_state_t *state, double *expected); /* IEEE754 float64 */
129 bool zcbor_float_pexpect(zcbor_state_t *state, double *expected); /* IEEE754 float16, float32, or float64 */
130 
131 /** Consume and expect a pint/nint with a certain value, within a union.
132  *
133  * Calls @ref zcbor_union_elem_code then @ref zcbor_[u]int[32|64]_expect.
134  */
135 bool zcbor_int32_expect_union(zcbor_state_t *state, int32_t expected);
136 bool zcbor_int64_expect_union(zcbor_state_t *state, int64_t expected);
137 bool zcbor_uint32_expect_union(zcbor_state_t *state, uint32_t expected);
138 bool zcbor_uint64_expect_union(zcbor_state_t *state, uint64_t expected);
139 
140 /** Decode and consume a list/map header.
141  *
142  * The contents of the list can be decoded via subsequent function calls.
143  * A state backup is created to keep track of the element count.
144  * Call @ref zcbor_list_end_decode / @ref zcbor_map_end_decode when done
145  * decoding the contents of the list/map
146  *
147  * @retval true   Header decoded correctly
148  * @retval false  Header decoded incorrectly, or backup failed.
149  */
150 bool zcbor_list_start_decode(zcbor_state_t *state);
151 bool zcbor_map_start_decode(zcbor_state_t *state);
152 bool zcbor_unordered_map_start_decode(zcbor_state_t *state);
153 
154 /** Search for a key in a map.
155  *
156  * The CBOR spec allows elements (key-value pairs) in maps to appear in any order.
157  * This function should be used when the order of elements is unknown.
158  *
159  * This must only be used while inside a map that has been entered via
160  * @ref zcbor_unordered_map_start_decode. Use @ref zcbor_unordered_map_end_decode
161  * when leaving the map.
162  *
163  * This function searches for keys. When this function returns successfully,
164  * the @p state is pointing to the value corresponding to the found key.
165  * Therefore, to be able to call this function again, the value must first be
166  * decoded or skipped.
167  *
168  * When searching unordered maps, the found elements must be kept track of.
169  * By default, this function automatically keeps track, which means it keeps a
170  * running count of the number of found elements, which is checked when exiting
171  * the map. You can do this manually instead, see @ref zcbor_elem_processed and
172  * @ref manually_process_elem. If ZCBOR_MAP_SMART_SEARCH is defined, a flag is
173  * kept for each element, instead of a rolling count.
174  *
175  * @note Unless ZCBOR_MAP_SMART_SEARCH is defined,
176  *       elements are not individually marked as processed, so they may
177  *       be returned again in a subsequent call to this function, if it is
178  *       matched by the @p key_decoder of that call. Because of this, you should
179  *       only use this function when you know the @p key_decoder matches no more
180  *       than one of the keys. Typically this means all keys are known strings
181  *       or integers, i.e. the @p key_decoder is typically a _pexpect() function.
182  *
183  * When searching for strings, there are convenience functions available,
184  * see the zcbor_search_key_* functions.
185  *
186  * @param[in] key_decoder  A decoding function that will be tried against all
187  *                         keys in the map until it returns true, at which point
188  *                         @ref zcbor_unordered_map_search will return true.
189  *                         For example, a zcbor_*_pexpect() function.
190  * @param[inout] state  The current state of decoding. Must be currently decoding
191  *                      the contents of a map, and pointing to one (any) of the
192  *                      keys, not one of the values. If successful, the @p state
193  *                      will be pointing to the value corresponding to the
194  *                      matched key. If unsuccessful, the @p state will be
195  *                      unchanged.
196  * @param[inout] key_result  This will be passed as the second argument to the
197  *                           @p key_decoder.
198  *
199  * @retval true   If the key was found, i.e. @p key_decoder returned true.
200  * @retval false  If the key was not found after searching all map elements.
201  *                Or the map was pointing to a value (not a key).
202  *                Or an unexpected error happened while skipping elements or
203  *                jumping from the end of the map to the start.
204  */
205 bool zcbor_unordered_map_search(zcbor_decoder_t key_decoder, zcbor_state_t *state, void *key_result);
206 
207 /** Find a specific bstr/tstr key as part of a map with unknown element order.
208  *
209  * Uses @ref zcbor_unordered_map_search under the hood. Please refer to those docs
210  * for the conditions under which this can be called.
211  * Refer to the docs for zcbor_(t|b)str_expect_* (e.g. @ref zcbor_bstr_expect_ptr)
212  * for parameter docs.
213  */
214 bool zcbor_search_key_bstr_ptr(zcbor_state_t *state, char const *ptr, size_t len);
215 bool zcbor_search_key_tstr_ptr(zcbor_state_t *state, char const *ptr, size_t len);
216 bool zcbor_search_key_bstr_term(zcbor_state_t *state, char const *str, size_t maxlen);
217 bool zcbor_search_key_tstr_term(zcbor_state_t *state, char const *str, size_t maxlen);
218 #define zcbor_search_key_bstr_lit(state, str) zcbor_search_key_bstr_ptr(state, str, sizeof(str) - 1)
219 #define zcbor_search_key_tstr_lit(state, str) zcbor_search_key_tstr_ptr(state, str, sizeof(str) - 1)
220 #define zcbor_search_key_bstr_arr(state, str) zcbor_search_key_bstr_ptr(state, str, (sizeof(str)))
221 #define zcbor_search_key_tstr_arr(state, str) zcbor_search_key_tstr_ptr(state, str, (sizeof(str)))
222 
223 /** (Optional) Call this function to mark an (unordered map) element as processed.
224  *
225  * @note This should not be called unless the @ref manually_process_elem flag is set.
226  *       By default, i.e. when @ref manually_process_elem is not set, this function is
227  *       called internally by @ref zcbor_unordered_map_search whenever a key is found.
228  *
229  * By default, this function increments the internal count @ref map_elems_processed.
230  *
231  * If ZCBOR_MAP_SMART_SEARCH is defined, this function instead clears a flag for the
232  * element (key-value pair) that is currently being processed, or that has just been
233  * processed, meaning the element won't be found again via @ref zcbor_unordered_map_search.
234  *
235  * @ref zcbor_unordered_map_end_decode will fail if @ref map_elems_processed does not
236  * match the number of elements in the map, or if any of the map element's flag is set.
237  */
238 bool zcbor_elem_processed(zcbor_state_t *state);
239 
240 /** Finalize decoding a list/map
241  *
242  * Check that the list/map had the correct number of elements, and restore the
243  * previous element count from the backup.
244  *
245  * Use @ref zcbor_list_map_end_force_decode to forcibly consume the backup if
246  * something has gone wrong.
247  *
248  * In all successful cases, the state is returned pointing to the byte/element
249  * after the list/map in the payload.
250  *
251  * @retval true   Everything ok.
252  * @retval false  Element count not correct.
253  */
254 bool zcbor_list_end_decode(zcbor_state_t *state);
255 bool zcbor_map_end_decode(zcbor_state_t *state);
256 bool zcbor_unordered_map_end_decode(zcbor_state_t *state);
257 bool zcbor_list_map_end_force_decode(zcbor_state_t *state);
258 
259 /** Find whether the state is at the end of a list or map.
260  */
261 bool zcbor_array_at_end(zcbor_state_t *state);
262 
263 /** Skip a single element, regardless of type and value.
264  *
265  * This means if the element is a map or list, this function will recursively
266  * skip all its contents.
267  * This function will also skip any tags preceeding the element.
268  *
269  * @param[inout] state   The current state of the decoding.
270  * @param[in]    unused  Unused parameter to maintain signature parity with
271  *                       @ref zcbor_decoder_t.
272  */
273 bool zcbor_any_skip(zcbor_state_t *state, void *unused);
274 
275 /** Decode 0 or more elements with the same type and constraints.
276  *
277  * The decoded values will appear consecutively in the @p result array.
278  *
279  * The following is an example of decoding a list containing 3 INTS followed by
280  * 0 to 2 bstrs:
281  *
282  * @code{c}
283  *     uint32_t ints[3];
284  *     struct zcbor_string bstrs[2];
285  *     uint32_t num_decode;
286  *     bool res;
287  *
288  *     res = zcbor_list_start_decode(state);
289  *     res = res && zcbor_multi_decode(3, 3, &num_decode, zcbor_uint32_decode,
290  *                  state, ints, sizeof(ints[0]));
291  *     res = res && zcbor_multi_decode(0, 2, &num_decode, zcbor_bstr_decode,
292  *                  state, bstrs, sizeof(bstrs[0]));
293  *     res = res && zcbor_list_end_decode(state);
294  *     // check res
295  * @endcode
296  *
297  * The @ref zcbor_decoder_t type is designed to be compatible with all single-
298  * value decoder functions in this library, e.g. @ref zcbor_uint32_decode,
299  * @ref zcbor_tstr_expect, @ref zcbor_nil_expect, etc. For _expect() functions,
300  * @p result will be used as a value instead of an array/pointer, so
301  * @p result_len will determine how much the value changes for each call.
302  * To decode the same value multiple times, use a @p result_len of 0.
303  * This function can also be used with custom decoder functions, such as those
304  * generated by the zcbor.py script, which for example decodes larger chunks of
305  * the data at once.
306  *
307  * @param[in]  min_decode    The minimum acceptable number of elements.
308  * @param[in]  max_decode    The maximum acceptable number of elements.
309  * @param[out] num_decode    The actual number of elements decoded.
310  * @param[in]  decoder       The decoder function to call under the hood. This
311  *                           function will be called with the provided arguments
312  *                           repeatedly until the function fails (returns false)
313  *                           or until it has been called @p max_decode times.
314  *                           The result pointer is moved @p result_len bytes for
315  *                           each call to @p decoder, i.e. @p result refers to
316  *                           an array of result variables.
317  *                           Should not be an _expect() function, use
318  *                           _pexpect() instead.
319  * @param[out] result        Where to place the decoded values. Must be an array
320  *                           of at least @p max_decode elements.
321  * @param[in]  result_len    The length of each result variable. Must be the
322  *                           length of the individual elements of @p result.
323  *
324  * @retval true   If at least @p min_decode variables were correctly decoded.
325  * @retval false  If @p decoder failed before having decoded @p min_decode
326  *                values.
327  */
328 bool zcbor_multi_decode(size_t min_decode, size_t max_decode, size_t *num_decode,
329 		zcbor_decoder_t decoder, zcbor_state_t *state, void *result,
330 		size_t result_len);
331 
332 /** Attempt to decode a value that might not be present in the data.
333  *
334  * Works like @ref zcbor_multi_decode, with @p present as num_decode.
335  * Will return true, even if the data is not present.
336  *
337  * @param[out] present  Whether or not the data was present and successfully decoded.
338  * @param[in]  decoder  The decoder to attempt.
339  * @param[out] result   The result, if present.
340  *
341  * @return Should always return true.
342  */
343 bool zcbor_present_decode(bool *present,
344 		zcbor_decoder_t decoder,
345 		zcbor_state_t *state,
346 		void *result);
347 
348 
349 /** Supplementary string (bstr/tstr) decoding functions: */
350 
351 /** Consume and expect a bstr/tstr with the value of the provided char/uint8_t array.
352  *
353  * @param[inout] state   The current state of the decoding.
354  * @param[in]    str     The value to expect. A pointer to the string/array.
355  *                       _term() uses strnlen(), so @p str must be null-terminated.
356  *                       _lit() uses sizeof()-1, so @p str must be a (null-terminated) string literal.
357  *                       _arr() uses sizeof(), so @p str must be a uint8_t array (not null-terminated).
358  * @param[in]    len     (if present) The length of the string pointed to by @p str
359  * @param[in]    maxlen  (if present) The maximum length of the string pointed to by @p str.
360  *                       This value is passed to strnlen.
361  */
362 bool zcbor_bstr_expect_ptr(zcbor_state_t *state, char const *ptr, size_t len);
363 bool zcbor_tstr_expect_ptr(zcbor_state_t *state, char const *ptr, size_t len);
364 bool zcbor_bstr_expect_term(zcbor_state_t *state, char const *str, size_t maxlen);
365 bool zcbor_tstr_expect_term(zcbor_state_t *state, char const *str, size_t maxlen);
366 #define zcbor_bstr_expect_lit(state, str) zcbor_bstr_expect_ptr(state, str, sizeof(str) - 1)
367 #define zcbor_tstr_expect_lit(state, str) zcbor_tstr_expect_ptr(state, str, sizeof(str) - 1)
368 #define zcbor_bstr_expect_arr(state, str) zcbor_bstr_expect_ptr(state, str, sizeof(str))
369 #define zcbor_tstr_expect_arr(state, str) zcbor_tstr_expect_ptr(state, str, sizeof(str))
370 
371 /** Decode and consume a bstr header.
372  *
373  * The rest of the string can be decoded as CBOR.
374  * A state backup is created to keep track of the element count.
375  * Call @ref zcbor_bstr_end_decode when done decoding the contents of the bstr.
376  *
377  * @param[inout] state   The current state of the decoding.
378  * @param[out]   result  The resulting string, for reference. The string should be decoded via
379  *                       functions from this API since state is pointing to the start of the string,
380  *                       not the end.
381  *
382  * @retval true   Header decoded correctly
383  * @retval false  Header decoded incorrectly, or backup failed, or payload is not large enough
384  *                to contain the contents of the string. Use @ref zcbor_bstr_start_decode_fragment
385  *                for decoding fragmented payloads.
386  */
387 bool zcbor_bstr_start_decode(zcbor_state_t *state, struct zcbor_string *result);
388 
389 /** Finalize decoding a CBOR-encoded bstr.
390  *
391  * Restore element count from backup.
392  */
393 bool zcbor_bstr_end_decode(zcbor_state_t *state);
394 
395 
396 /** Supplementary string (bstr/tstr) decoding functions for fragmented payloads: */
397 
398 /** Start decoding a bstr/tstr, even if the payload contains only part of it.
399  *
400  * This must be followed by a call to @ref zcbor_update_state, which can be
401  * followed by a call to @ref zcbor_next_fragment. Do not call this function
402  * again on subsequent fragments of the same string.
403  *
404  * This consumes the remaining payload as long as it belongs to the string.
405  */
406 bool zcbor_bstr_decode_fragment(zcbor_state_t *state, struct zcbor_string_fragment *result);
407 bool zcbor_tstr_decode_fragment(zcbor_state_t *state, struct zcbor_string_fragment *result);
408 
409 /** Extract the next fragment of a string.
410  *
411  * Use this function to extract all but the first fragment.
412  */
413 void zcbor_next_fragment(zcbor_state_t *state,
414 	struct zcbor_string_fragment *prev_fragment,
415 	struct zcbor_string_fragment *result);
416 
417 /** Decode and consume a bstr header, assuming the payload does not contain the whole bstr.
418  *
419  * The rest of the string can be decoded as CBOR.
420  * A state backup is created to keep track of the element count.
421  * Call @ref zcbor_update_state followed by @ref zcbor_bstr_next_fragment when
422  * the current payload has been exhausted.
423  * Call @ref zcbor_bstr_end_decode when done decoding the contents of the bstr.
424  */
425 bool zcbor_bstr_start_decode_fragment(zcbor_state_t *state,
426 	struct zcbor_string_fragment *result);
427 
428 /** Start decoding the next fragment of a string.
429  *
430  * Use this function to extract all but the first fragment of a CBOR-encoded
431  * bstr.
432  */
433 void zcbor_bstr_next_fragment(zcbor_state_t *state,
434 	struct zcbor_string_fragment *prev_fragment,
435 	struct zcbor_string_fragment *result);
436 
437 /** Can be used on any fragment to tell if it is the final fragment of the string. */
438 bool zcbor_is_last_fragment(const struct zcbor_string_fragment *fragment);
439 
440 #ifdef __cplusplus
441 }
442 #endif
443 
444 #endif /* ZCBOR_DECODE_H__ */
445