blob: 7f9c1690e8634d6450fa19eea3377289442222d1 [file] [log] [blame]
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001/*==============================================================================
Laurence Lundbladed92a6162018-11-01 11:38:35 +07002 Copyright (c) 2016-2018, The Linux Foundation.
Laurence Lundblade3f1318a2021-01-04 18:26:44 -08003 Copyright (c) 2018-2021, Laurence Lundblade.
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02004 Copyright (c) 2021, Arm Limited.
Laurence Lundbladed92a6162018-11-01 11:38:35 +07005 All rights reserved.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08006
Laurence Lundblade0dbc9172018-11-01 14:17:21 +07007Redistribution and use in source and binary forms, with or without
8modification, are permitted provided that the following conditions are
9met:
10 * Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12 * Redistributions in binary form must reproduce the above
13 copyright notice, this list of conditions and the following
14 disclaimer in the documentation and/or other materials provided
15 with the distribution.
16 * Neither the name of The Linux Foundation nor the names of its
17 contributors, nor the name "Laurence Lundblade" may be used to
18 endorse or promote products derived from this software without
19 specific prior written permission.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080020
Laurence Lundblade0dbc9172018-11-01 14:17:21 +070021THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
22WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
24ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
25BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
30OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
31IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Laurence Lundbladeee851742020-01-08 08:37:05 -080032 =============================================================================*/
Laurence Lundblade624405d2018-09-18 20:10:47 -070033
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080034
Laurence Lundblade844bb5c2020-03-01 17:27:25 -080035#include "qcbor/qcbor_encode.h"
Laurence Lundblade12d32c52018-09-19 11:25:27 -070036#include "ieee754.h"
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070037
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070038
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080039/**
40 * @file qcbor_encode.c
Laurence Lundblade3f1318a2021-01-04 18:26:44 -080041 *
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080042 * The entire implementation of the QCBOR encoder.
43 */
44
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070045
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070046/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080047 * == Nesting Tracking ==
48 *
49 * The following functions and data type QCBORTrackNesting implement
50 * the nesting management for encoding.
51 *
52 * CBOR's two nesting types, arrays and maps, are tracked here. There
53 * is a limit of QCBOR_MAX_ARRAY_NESTING to the number of arrays and
54 * maps that can be nested in one encoding so the encoding context
55 * stays small enough to fit on the stack.
56 *
57 * When an array/map is opened, pCurrentNesting points to the element
58 * in pArrays that records the type, start position and accumulates a
59 * count of the number of items added. When closed the start position
60 * is used to go back and fill in the type and number of items in the
61 * array/map.
62 *
63 * Encoded output can be a CBOR Sequence (RFC 8742) in which case
64 * there is no top-level array or map. It starts out with a string,
65 * integer or other non-aggregate type. It may have an array or map
66 * other than at the start, in which case that nesting is tracked
67 * here.
68 *
69 * QCBOR has a special feature to allow constructing byte string
70 * wrapped CBOR directly into the output buffer, so no extra buffer is
71 * needed for byte string wrapping. This is implemented as nesting
72 * with the type CBOR_MAJOR_TYPE_BYTE_STRING and is tracked here. Byte
73 * string wrapped CBOR is used by COSE for data that is to be hashed.
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070074 */
75inline static void Nesting_Init(QCBORTrackNesting *pNesting)
76{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080077 /* Assumes pNesting has been zeroed. */
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070078 pNesting->pCurrentNesting = &pNesting->pArrays[0];
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080079 /* Implied CBOR array at the top nesting level. This is never
80 * returned, but makes the item count work correctly.
81 */
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070082 pNesting->pCurrentNesting->uMajorType = CBOR_MAJOR_TYPE_ARRAY;
83}
84
Laurence Lundblade29497c02020-07-11 15:44:03 -070085inline static uint8_t Nesting_Increase(QCBORTrackNesting *pNesting,
Laurence Lundblade2c40ab82018-12-30 14:20:29 -080086 uint8_t uMajorType,
87 uint32_t uPos)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070088{
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070089 if(pNesting->pCurrentNesting == &pNesting->pArrays[QCBOR_MAX_ARRAY_NESTING]) {
Laurence Lundblade29497c02020-07-11 15:44:03 -070090 return QCBOR_ERR_ARRAY_NESTING_TOO_DEEP;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070091 } else {
92 pNesting->pCurrentNesting++;
93 pNesting->pCurrentNesting->uCount = 0;
94 pNesting->pCurrentNesting->uStart = uPos;
95 pNesting->pCurrentNesting->uMajorType = uMajorType;
Laurence Lundblade29497c02020-07-11 15:44:03 -070096 return QCBOR_SUCCESS;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070097 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070098}
99
100inline static void Nesting_Decrease(QCBORTrackNesting *pNesting)
101{
102 pNesting->pCurrentNesting--;
103}
104
Laurence Lundblade29497c02020-07-11 15:44:03 -0700105inline static uint8_t Nesting_Increment(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700106{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800107#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800108 if(1 >= QCBOR_MAX_ITEMS_IN_ARRAY - pNesting->pCurrentNesting->uCount) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700109 return QCBOR_ERR_ARRAY_TOO_LONG;
110 }
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800111#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800112
Laurence Lundbladee6bcef12020-04-01 10:56:27 -0700113 pNesting->pCurrentNesting->uCount++;
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800114
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700115 return QCBOR_SUCCESS;
116}
117
Laurence Lundblade8d3b8552021-06-10 11:11:54 -0700118inline static void Nesting_Decrement(QCBORTrackNesting *pNesting)
119{
120 /* No error check for going below 0 here needed because this
121 * is only used by QCBOREncode_CancelBstrWrap() and it checks
122 * the nesting level before calling this. */
123 pNesting->pCurrentNesting->uCount--;
124}
125
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700126inline static uint16_t Nesting_GetCount(QCBORTrackNesting *pNesting)
127{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800128 /* The nesting count recorded is always the actual number of
129 * individual data items in the array or map. For arrays CBOR uses
130 * the actual item count. For maps, CBOR uses the number of pairs.
131 * This function returns the number needed for the CBOR encoding,
132 * so it divides the number of items by two for maps to get the
133 * number of pairs.
134 */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800135 if(pNesting->pCurrentNesting->uMajorType == CBOR_MAJOR_TYPE_MAP) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800136 /* Cast back to uint16_t after integer promotion from bit shift */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800137 return (uint16_t)(pNesting->pCurrentNesting->uCount >> 1);
138 } else {
139 return pNesting->pCurrentNesting->uCount;
140 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700141}
142
143inline static uint32_t Nesting_GetStartPos(QCBORTrackNesting *pNesting)
144{
145 return pNesting->pCurrentNesting->uStart;
146}
147
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800148#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700149inline static uint8_t Nesting_GetMajorType(QCBORTrackNesting *pNesting)
150{
151 return pNesting->pCurrentNesting->uMajorType;
152}
153
Laurence Lundbladeee851742020-01-08 08:37:05 -0800154inline static bool Nesting_IsInNest(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700155{
Laurence Lundbladeee851742020-01-08 08:37:05 -0800156 return pNesting->pCurrentNesting == &pNesting->pArrays[0] ? false : true;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700157}
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800158#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700159
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700160
161
162
163/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800164 * == Major CBOR Types ==
165 *
166 * Encoding of the major CBOR types is by these functions:
167 *
Laurence Lundblade3f1318a2021-01-04 18:26:44 -0800168 * CBOR Major Type Public Function
169 * 0 QCBOREncode_AddUInt64()
170 * 0, 1 QCBOREncode_AddUInt64(), QCBOREncode_AddInt64()
171 * 2, 3 QCBOREncode_AddBuffer()
172 * 4, 5 QCBOREncode_OpenMapOrArray(), QCBOREncode_CloseMapOrArray(),
173 * QCBOREncode_OpenMapOrArrayIndefiniteLength(),
174 * QCBOREncode_CloseMapOrArrayIndefiniteLength()
175 * 6 QCBOREncode_AddTag()
176 * 7 QCBOREncode_AddDouble(), QCBOREncode_AddFloat(),
177 * QCBOREncode_AddDoubleNoPreferred(),
178 * QCBOREncode_AddFloatNoPreferred(), QCBOREncode_AddType7()
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800179 *
180 * Additionally, encoding of decimal fractions and bigfloats is by
181 * QCBOREncode_AddExponentAndMantissa() and byte strings that wrap
182 * encoded CBOR are handled by QCBOREncode_OpenMapOrArray() and
183 * QCBOREncode_CloseBstrWrap2().
184 *
185 *
186 * == Error Tracking Plan ==
187 *
188 * Errors are tracked internally and not returned until
189 * QCBOREncode_Finish() or QCBOREncode_GetErrorState() is called. The
190 * CBOR errors are in me->uError. UsefulOutBuf also tracks whether
191 * the buffer is full or not in its context. Once either of these
192 * errors is set they are never cleared. Only QCBOREncode_Init()
193 * resets them. Or said another way, they must never be cleared or
194 * we'll tell the caller all is good when it is not.
195 *
196 * Only one error code is reported by QCBOREncode_Finish() even if
197 * there are multiple errors. The last one set wins. The caller might
198 * have to fix one error to reveal the next one they have to fix.
199 * This is OK.
200 *
201 * The buffer full error tracked by UsefulBuf is only pulled out of
202 * UsefulBuf in QCBOREncode_Finish() so it is the one that usually
203 * wins. UsefulBuf will never go off the end of the buffer even if it
204 * is called again and again when full.
205 *
206 * QCBOR_DISABLE_ENCODE_USAGE_GUARDS disables about half of the error
207 * checks here to reduce code size by about 150 bytes leaving only the
208 * checks for size to avoid buffer overflow. If the calling code is
209 * completely correct, checks are completely unnecessary. For
210 * example, there is no need to check that all the opens are matched
211 * by a close.
212 *
213 * QCBOR_DISABLE_ENCODE_USAGE_GUARDS also disables the check for more
214 * than QCBOR_MAX_ITEMS_IN_ARRAY in an array. Since
215 * QCBOR_MAX_ITEMS_IN_ARRAY is very large (65,535) it is very unlikely
216 * to be reached. If it is reached, the count will wrap around to zero
217 * and CBOR that is not well formed will be produced, but there will
218 * be no buffers overrun and new security issues in the code.
219 *
220 * The 8 errors returned here fall into three categories:
221 *
222 * Sizes
223 * QCBOR_ERR_BUFFER_TOO_LARGE -- Encoded output exceeded UINT32_MAX
224 * QCBOR_ERR_BUFFER_TOO_SMALL -- Output buffer too small
225 * QCBOR_ERR_ARRAY_NESTING_TOO_DEEP -- Nesting > QCBOR_MAX_ARRAY_NESTING1
226 * QCBOR_ERR_ARRAY_TOO_LONG -- Too many items added to an array/map [1]
227 *
228 * Nesting constructed incorrectly
229 * QCBOR_ERR_TOO_MANY_CLOSES -- More close calls than opens [1]
230 * QCBOR_ERR_CLOSE_MISMATCH -- Type of close does not match open [1]
231 * QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN -- Finish called without enough closes [1]
232 *
233 * Would generate not-well-formed CBOR
234 * QCBOR_ERR_ENCODE_UNSUPPORTED -- Simple type between 24 and 31 [1]
235 *
236 * [1] indicated disabled by QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700237 */
238
239
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700240/*
Laurence Lundblade844bb5c2020-03-01 17:27:25 -0800241 Public function for initialization. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700242 */
Laurence Lundblade2296db52018-09-14 18:08:39 -0700243void QCBOREncode_Init(QCBOREncodeContext *me, UsefulBuf Storage)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700244{
245 memset(me, 0, sizeof(QCBOREncodeContext));
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800246 UsefulOutBuf_Init(&(me->OutBuf), Storage);
247 Nesting_Init(&(me->nesting));
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700248}
249
250
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000251/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800252 * Public function to encode a CBOR head. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700253 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000254UsefulBufC QCBOREncode_EncodeHead(UsefulBuf buffer,
255 uint8_t uMajorType,
256 uint8_t uMinLen,
257 uint64_t uArgument)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700258{
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800259 /*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800260 * == Description of the CBOR Head ==
261 *
262 * The head of a CBOR data item
263 * +---+-----+ +--------+ +--------+ +--------+ +--------+
264 * |M T| A R G U M E N T . . . |
265 * +---+-----+ +--------+ +--------+ +--------+ ... +--------+
266 *
267 * Every CBOR data item has a "head". It is made up of the "major
268 * type" and the "argument".
269 *
270 * The major type indicates whether the data item is an integer,
271 * string, array or such. It is encoded in 3 bits giving it a range
272 * from 0 to 7. 0 indicates the major type is a positive integer,
273 * 1 a negative integer, 2 a byte string and so on.
274 *
275 * These 3 bits are the first part of the "initial byte" in a data
276 * item. Every data item has an initial byte, and some only have
277 * the initial byte.
278 *
279 * The argument is essentially a number between 0 and UINT64_MAX
280 * (18446744073709551615). This number is interpreted to mean
281 * different things for the different major types. For major type
282 * 0, a positive integer, it is value of the data item. For major
283 * type 2, a byte string, it is the length in bytes of the byte
284 * string. For major type 4, an array, it is the number of data
285 * items in the array.
286 *
287 * Special encoding is used so that the argument values less than
288 * 24 can be encoded very compactly in the same byte as the major
289 * type is encoded. When the lower 5 bits of the initial byte have
290 * a value less than 24, then that is the value of the argument.
291 *
292 * If the lower 5 bits of the initial byte are less than 24, then
293 * they are the value of the argument. This allows integer values 0
294 * - 23 to be CBOR encoded in just one byte.
295 *
296 * When the value of lower 5 bits are 24, 25, 26, or 27 the
297 * argument is encoded in 1, 2, 4 or 8 bytes following the initial
298 * byte in network byte order (bit endian). The cases when it is
299 * 28, 29 and 30 are reserved for future use. The value 31 is a
300 * special indicator for indefinite length strings, arrays and
301 * maps.
302 *
303 * The lower 5 bits are called the "additional information."
304 *
305 * Thus the CBOR head may be 1, 2, 3, 5 or 9 bytes long.
306 *
307 * It is legal in CBOR to encode the argument using any of these
308 * lengths even if it could be encoded in a shorter length. For
309 * example it is legal to encode a data item representing the
310 * positive integer 0 in 9 bytes even though it could be encoded in
311 * only 0. This is legal to allow for for very simple code or even
312 * hardware-only implementations that just output a register
313 * directly.
314 *
315 * CBOR defines preferred encoding as the encoding of the argument
316 * in the smallest number of bytes needed to encode it.
317 *
318 * This function takes the major type and argument as inputs and
319 * outputs the encoded CBOR head for them. It does conversion to
320 * network byte order. It implements CBOR preferred encoding,
321 * outputting the shortest representation of the argument.
322 *
323 * == Endian Conversion ==
324 *
325 * This code does endian conversion without hton() or knowing the
326 * endianness of the machine by using masks and shifts. This avoids
327 * the dependency on hton() and the mess of figuring out how to
328 * find the machine's endianness.
329 *
330 * This is a good efficient implementation on little-endian
331 * machines. A faster and smaller implementation is possible on
332 * big-endian machines because CBOR/network byte order is
333 * big-endian. However big-endian machines are uncommon.
334 *
335 * On x86, this is about 150 bytes instead of 500 bytes for the
336 * original, more formal unoptimized code.
337 *
338 * This also does the CBOR preferred shortest encoding for integers
339 * and is called to do endian conversion for floats.
340 *
341 * It works backwards from the least significant byte to the most
342 * significant byte.
343 *
344 * == Floating Point ==
345 *
346 * When the major type is 7 and the 5 lower bits have the values
347 * 25, 26 or 27, the argument is a floating-point number that is
348 * half, single or double-precision. Note that it is not the
349 * conversion from a floating-point value to an integer value like
350 * converting 0x00 to 0.00, it is the interpretation of the bits in
351 * the argument as an IEEE 754 float-point number.
352 *
353 * Floating-point numbers must be converted to network byte
354 * order. That is accomplished here by exactly the same code that
355 * converts integer arguments to network byte order.
356 *
357 * There is preferred encoding for floating-point numbers in CBOR,
358 * but it is very different than for integers and it is not
359 * implemented here. Half-precision is preferred to
360 * single-precision which is preferred to double-precision only if
361 * the conversion can be performed without loss of precision. Zero
362 * and infinity can always be converted to half-precision, without
363 * loss but 3.141592653589 cannot.
364 *
365 * The way this function knows to not do preferred encoding on the
366 * argument passed here when it is a floating point number is the
367 * uMinLen parameter. It should be 2, 4 or 8 for half, single and
368 * double precision floating point values. This prevents and the
369 * incorrect removal of leading zeros when encoding arguments that
370 * are floating-point numbers.
371 *
372 * == Use of Type int and Static Analyzers ==
373 *
374 * The type int is used here for several variables because of the
375 * way integer promotion works in C for variables that are uint8_t
376 * or uint16_t. The basic rule is that they will always be promoted
377 * to int if they will fit. These integer variables here need only
378 * hold values less than 255 so they will always fit into an int.
379 *
380 * Most of values stored are never negative, so one might think
381 * that unsigned int would be more correct than int. However the C
382 * integer promotion rules only promote to unsigned int if the
383 * result won't fit into an int even if the promotion is for an
384 * unsigned variable like uint8_t.
385 *
386 * By declaring these int, there are few implicit conversions and
387 * fewer casts needed. Code size is reduced a little. It makes
388 * static analyzers happier.
389 *
390 * Note also that declaring these uint8_t won't stop integer wrap
391 * around if the code is wrong. It won't make the code more
392 * correct.
393 *
394 * https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules
395 * https://stackoverflow.com/questions/589575/what-does-the-c-standard-state-the-size-of-int-long-type-to-be
396 *
397 * Code Reviewers: THIS FUNCTION DOES POINTER MATH
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800398 */
Laurence Lundbladeee851742020-01-08 08:37:05 -0800399
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800400 /* The buffer must have room for the largest CBOR HEAD + one
401 * extra. The one extra is needed for this code to work as it does
402 * a pre-decrement.
403 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000404 if(buffer.len < QCBOR_HEAD_BUFFER_SIZE) {
405 return NULLUsefulBufC;
406 }
407
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800408 /* Pointer to last valid byte in the buffer */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000409 uint8_t * const pBufferEnd = &((uint8_t *)buffer.ptr)[QCBOR_HEAD_BUFFER_SIZE-1];
410
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800411 /* Point to the last byte and work backwards */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000412 uint8_t *pByte = pBufferEnd;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800413 /* The 5 bits in the initial byte that are not the major type */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800414 int nAdditionalInfo;
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800415
Laurence Lundblade8c858ab2020-11-02 19:53:49 -0800416 if(uMajorType > QCBOR_INDEFINITE_LEN_TYPE_MODIFIER) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800417 /* Special case for start & end of indefinite length */
Laurence Lundblade8c858ab2020-11-02 19:53:49 -0800418 uMajorType = uMajorType - QCBOR_INDEFINITE_LEN_TYPE_MODIFIER;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800419 /* This takes advantage of design of CBOR where additional info
420 * is 31 for both opening and closing indefinite length
421 * maps and arrays.
422 */
423 #if CBOR_SIMPLE_BREAK != LEN_IS_INDEFINITE
424 #error additional info for opening array not the same as for closing
425 #endif
Laurence Lundblade8c858ab2020-11-02 19:53:49 -0800426 nAdditionalInfo = CBOR_SIMPLE_BREAK;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800427
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000428 } else if (uArgument < CBOR_TWENTY_FOUR && uMinLen == 0) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800429 /* Simple case where argument is < 24 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000430 nAdditionalInfo = (int)uArgument;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800431
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800432 } else {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800433 /* This encodes the argument in 1,2,4 or 8 bytes. The outer loop
434 * runs once for 1 byte and 4 times for 8 bytes. The inner loop
435 * runs 1, 2 or 4 times depending on outer loop counter. This
436 * works backwards shifting 8 bits off the argument being
437 * encoded at a time until all bits from uArgument have been
438 * encoded and the minimum encoding size is reached. Minimum
439 * encoding size is for floating-point numbers that have some
440 * zero-value bytes that must be output.
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800441 */
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800442 static const uint8_t aIterate[] = {1,1,2,4};
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000443
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800444 /* uMinLen passed in is unsigned, but goes negative in the loop
445 * so it must be converted to a signed value.
446 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000447 int nMinLen = (int)uMinLen;
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800448 int i;
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000449 for(i = 0; uArgument || nMinLen > 0; i++) {
450 const int nIterations = (int)aIterate[i];
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800451 for(int j = 0; j < nIterations; j++) {
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000452 *--pByte = (uint8_t)(uArgument & 0xff);
453 uArgument = uArgument >> 8;
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800454 }
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800455 nMinLen -= nIterations;
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800456 }
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800457
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800458 nAdditionalInfo = LEN_IS_ONE_BYTE-1 + i;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700459 }
Laurence Lundbladef970f1d2018-12-14 01:44:23 -0800460
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800461 /* This expression integer-promotes to type int. The code above in
462 * function guarantees that nAdditionalInfo will never be larger
463 * than 0x1f. The caller may pass in a too-large uMajor type. The
464 * conversion to unint8_t will cause an integer wrap around and
465 * incorrect CBOR will be generated, but no security issue will
466 * occur.
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800467 */
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800468 const int nInitialByte = (uMajorType << 5) + nAdditionalInfo;
469 *--pByte = (uint8_t)nInitialByte;
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800470
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000471#ifdef EXTRA_ENCODE_HEAD_CHECK
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800472 /* This is a sanity check that can be turned on to verify the
473 * pointer math in this function is not going wrong. Turn it on and
474 * run the whole test suite to perform the check.
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800475 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000476 if(pBufferEnd - pByte > 9 || pBufferEnd - pByte < 1 || pByte < (uint8_t *)buffer.ptr) {
477 return NULLUsefulBufC;
478 }
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800479#endif /* EXTRA_ENCODE_HEAD_CHECK */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800480
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800481 /* Length will not go negative because the loops run for at most 8 decrements
482 * of pByte, only one other decrement is made, and the array is sized
483 * for this.
484 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000485 return (UsefulBufC){pByte, (size_t)(pBufferEnd - pByte)};
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700486}
487
488
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000489/**
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800490 * @brief Append the CBOR head, the major type and argument
491 *
492 * @param me Encoder context.
493 * @param uMajorType Major type to insert.
494 * @param uArgument The argument (an integer value or a length).
495 * @param uMinLen The minimum number of bytes for encoding the CBOR argument.
496 *
497 * This formats the CBOR "head" and appends it to the output.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000498 */
499static void AppendCBORHead(QCBOREncodeContext *me, uint8_t uMajorType, uint64_t uArgument, uint8_t uMinLen)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700500{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800501 /* A stack buffer large enough for a CBOR head */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000502 UsefulBuf_MAKE_STACK_UB (pBufferForEncodedHead, QCBOR_HEAD_BUFFER_SIZE);
503
504 UsefulBufC EncodedHead = QCBOREncode_EncodeHead(pBufferForEncodedHead,
505 uMajorType,
506 uMinLen,
507 uArgument);
508
509 /* No check for EncodedHead == NULLUsefulBufC is performed here to
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800510 * save object code. It is very clear that pBufferForEncodedHead is
511 * the correct size. If EncodedHead == NULLUsefulBufC then
512 * UsefulOutBuf_AppendUsefulBuf() will do nothing so there is no
513 * security hole introduced.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000514 */
515
516 UsefulOutBuf_AppendUsefulBuf(&(me->OutBuf), EncodedHead);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700517}
518
519
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000520/**
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800521 * @brief Insert the CBOR head for a map, array or wrapped bstr
522 *
523 * @param me QCBOR encoding context.
524 * @param uMajorType One of CBOR_MAJOR_TYPE_XXXX.
525 * @param uLen The length of the data item.
526 *
527 * When an array, map or bstr was opened, nothing was done but note
528 * the position. This function goes back to that position and inserts
529 * the CBOR Head with the major type and length.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000530 */
531static void InsertCBORHead(QCBOREncodeContext *me, uint8_t uMajorType, size_t uLen)
532{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800533#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000534 if(me->uError == QCBOR_SUCCESS) {
535 if(!Nesting_IsInNest(&(me->nesting))) {
536 me->uError = QCBOR_ERR_TOO_MANY_CLOSES;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800537 return;
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000538 } else if(Nesting_GetMajorType(&(me->nesting)) != uMajorType) {
539 me->uError = QCBOR_ERR_CLOSE_MISMATCH;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800540 return;
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000541 }
542 }
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800543#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800544
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800545 /* A stack buffer large enough for a CBOR head */
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800546 UsefulBuf_MAKE_STACK_UB(pBufferForEncodedHead, QCBOR_HEAD_BUFFER_SIZE);
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800547
548 UsefulBufC EncodedHead = QCBOREncode_EncodeHead(pBufferForEncodedHead,
549 uMajorType,
550 0,
551 uLen);
552
553 /* No check for EncodedHead == NULLUsefulBufC is performed here to
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800554 * save object code. It is very clear that pBufferForEncodedHead is
555 * the correct size. If EncodedHead == NULLUsefulBufC then
556 * UsefulOutBuf_InsertUsefulBuf() will do nothing so there is no
Laurence Lundblade9e2f7082021-05-17 02:10:48 -0700557 * security hole introduced.
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800558 */
559 UsefulOutBuf_InsertUsefulBuf(&(me->OutBuf),
560 EncodedHead,
561 Nesting_GetStartPos(&(me->nesting)));
562
563 Nesting_Decrease(&(me->nesting));
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000564}
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700565
Laurence Lundblade241705e2018-12-30 18:56:14 -0800566
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800567/**
568 * @brief Increment item counter for maps and arrays.
569 *
570 * @param pMe QCBOR encoding context.
571 *
572 * This is mostly a separate function to make code more readable and
573 * to have fewer occurrences of #ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800574 */
575static inline void IncrementMapOrArrayCount(QCBOREncodeContext *pMe)
576{
577#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
578 if(pMe->uError == QCBOR_SUCCESS) {
579 pMe->uError = Nesting_Increment(&(pMe->nesting));
580 }
581#else
582 (void)Nesting_Increment(&(pMe->nesting));
583#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
584}
585
586
587/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800588 * Public functions for adding unsigned integers. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700589 */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800590void QCBOREncode_AddUInt64(QCBOREncodeContext *me, uint64_t uValue)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700591{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800592 AppendCBORHead(me, CBOR_MAJOR_TYPE_POSITIVE_INT, uValue, 0);
593
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800594 IncrementMapOrArrayCount(me);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700595}
596
Laurence Lundblade56230d12018-11-01 11:14:51 +0700597
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700598/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800599 * Public functions for adding signed integers. See qcbor/qcbor_encode.h
Laurence Lundblade067035b2018-11-28 17:35:25 -0800600 */
601void QCBOREncode_AddInt64(QCBOREncodeContext *me, int64_t nNum)
602{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800603 uint8_t uMajorType;
604 uint64_t uValue;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800605
606 if(nNum < 0) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800607 /* In CBOR -1 encodes as 0x00 with major type negative int. */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800608 uValue = (uint64_t)(-nNum - 1);
609 uMajorType = CBOR_MAJOR_TYPE_NEGATIVE_INT;
610 } else {
611 uValue = (uint64_t)nNum;
612 uMajorType = CBOR_MAJOR_TYPE_POSITIVE_INT;
613 }
614 AppendCBORHead(me, uMajorType, uValue, 0);
615
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800616 IncrementMapOrArrayCount(me);
Laurence Lundblade067035b2018-11-28 17:35:25 -0800617}
618
619
620/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800621 * Semi-private function. It is exposed to user of the interface, but
622 * one of its inline wrappers will usually be called instead of this.
623 *
624 * See qcbor/qcbor_encode.h
625 *
626 * This does the work of adding actual strings bytes to the CBOR
627 * output (as opposed to adding numbers and opening / closing
628 * aggregate types).
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800629
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800630 * There are four use cases:
631 * CBOR_MAJOR_TYPE_BYTE_STRING -- Byte strings
632 * CBOR_MAJOR_TYPE_TEXT_STRING -- Text strings
633 * CBOR_MAJOR_NONE_TYPE_RAW -- Already-encoded CBOR
634 * CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY -- Special case
635 *
636 * The first two add the head plus the actual bytes. The third just
637 * adds the bytes as the heas is presumed to be in the bytes. The
638 * fourth just adds the head for the very special case of
639 * QCBOREncode_AddBytesLenOnly().
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700640 */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800641void QCBOREncode_AddBuffer(QCBOREncodeContext *me, uint8_t uMajorType, UsefulBufC Bytes)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700642{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800643 /* If it is not Raw CBOR, add the type and the length */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800644 if(uMajorType != CBOR_MAJOR_NONE_TYPE_RAW) {
645 uint8_t uRealMajorType = uMajorType;
646 if(uRealMajorType == CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY) {
647 uRealMajorType = CBOR_MAJOR_TYPE_BYTE_STRING;
648 }
649 AppendCBORHead(me, uRealMajorType, Bytes.len, 0);
650 }
651
652 if(uMajorType != CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800653 /* Actually add the bytes */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800654 UsefulOutBuf_AppendUsefulBuf(&(me->OutBuf), Bytes);
655 }
656
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800657 IncrementMapOrArrayCount(me);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700658}
659
Laurence Lundbladecafcfe12018-10-31 21:59:50 +0700660
Laurence Lundblade55a24832018-10-30 04:35:08 +0700661/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800662 * Public functions for adding a tag. See qcbor/qcbor_encode.h
Laurence Lundblade55a24832018-10-30 04:35:08 +0700663 */
664void QCBOREncode_AddTag(QCBOREncodeContext *me, uint64_t uTag)
665{
Laurence Lundblade3f1318a2021-01-04 18:26:44 -0800666 AppendCBORHead(me, CBOR_MAJOR_TYPE_TAG, uTag, 0);
Laurence Lundblade55a24832018-10-30 04:35:08 +0700667}
668
669
Laurence Lundblade56230d12018-11-01 11:14:51 +0700670/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800671 * Semi-private function. It is exposed to user of the interface, but
672 * one of its inline wrappers will usually be called instead of this.
673 *
674 * See header qcbor/qcbor_encode.h
Laurence Lundblade56230d12018-11-01 11:14:51 +0700675 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000676void QCBOREncode_AddType7(QCBOREncodeContext *me, uint8_t uMinLen, uint64_t uNum)
Laurence Lundblade55a24832018-10-30 04:35:08 +0700677{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800678#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade487930f2018-11-30 11:01:45 -0800679 if(me->uError == QCBOR_SUCCESS) {
Laurence Lundbladebb1062e2019-08-12 23:28:54 -0700680 if(uNum >= CBOR_SIMPLEV_RESERVED_START && uNum <= CBOR_SIMPLEV_RESERVED_END) {
Laurence Lundbladea9489f82020-09-12 13:50:56 -0700681 me->uError = QCBOR_ERR_ENCODE_UNSUPPORTED;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800682 return;
Laurence Lundbladebb1062e2019-08-12 23:28:54 -0700683 }
Laurence Lundblade487930f2018-11-30 11:01:45 -0800684 }
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800685#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
686
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800687 /* AppendCBORHead() does endian swapping for the float / double */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800688 AppendCBORHead(me, CBOR_MAJOR_TYPE_SIMPLE, uNum, uMinLen);
Laurence Lundblade3f1318a2021-01-04 18:26:44 -0800689
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800690 IncrementMapOrArrayCount(me);
Laurence Lundblade55a24832018-10-30 04:35:08 +0700691}
692
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700693
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +0200694#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Laurence Lundblade32f3e622020-07-13 20:35:11 -0700695/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800696 * Public functions for adding a double. See qcbor/qcbor_encode.h
697 */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700698void QCBOREncode_AddDoubleNoPreferred(QCBOREncodeContext *me, double dNum)
699{
Laurence Lundblade2feb1e12020-07-15 03:50:45 -0700700 QCBOREncode_AddType7(me,
701 sizeof(uint64_t),
702 UsefulBufUtil_CopyDoubleToUint64(dNum));
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700703}
704
Laurence Lundblade32f3e622020-07-13 20:35:11 -0700705
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700706/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800707 * Public functions for adding a double. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700708 */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800709void QCBOREncode_AddDouble(QCBOREncodeContext *me, double dNum)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700710{
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700711#ifndef QCBOR_DISABLE_PREFERRED_FLOAT
Laurence Lundblade067035b2018-11-28 17:35:25 -0800712 const IEEE754_union uNum = IEEE754_DoubleToSmallest(dNum);
Laurence Lundblade2feb1e12020-07-15 03:50:45 -0700713
Laurence Lundblade487930f2018-11-30 11:01:45 -0800714 QCBOREncode_AddType7(me, uNum.uSize, uNum.uValue);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800715#else /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700716 QCBOREncode_AddDoubleNoPreferred(me, dNum);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800717#endif /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700718}
Laurence Lundblade9682a532020-06-06 18:33:04 -0700719
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700720
Laurence Lundblade32f3e622020-07-13 20:35:11 -0700721/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800722 * Public functions for adding a float. See qcbor/qcbor_encode.h
723 */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700724void QCBOREncode_AddFloatNoPreferred(QCBOREncodeContext *me, float fNum)
725{
Laurence Lundblade2feb1e12020-07-15 03:50:45 -0700726 QCBOREncode_AddType7(me,
727 sizeof(uint32_t),
728 UsefulBufUtil_CopyFloatToUint32(fNum));
Laurence Lundblade9682a532020-06-06 18:33:04 -0700729}
730
731
732/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800733 * Public functions for adding a float. See qcbor/qcbor_encode.h
Laurence Lundblade9682a532020-06-06 18:33:04 -0700734 */
735void QCBOREncode_AddFloat(QCBOREncodeContext *me, float fNum)
736{
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700737#ifndef QCBOR_DISABLE_PREFERRED_FLOAT
Laurence Lundblade9682a532020-06-06 18:33:04 -0700738 const IEEE754_union uNum = IEEE754_FloatToSmallest(fNum);
Laurence Lundblade2feb1e12020-07-15 03:50:45 -0700739
Laurence Lundblade9682a532020-06-06 18:33:04 -0700740 QCBOREncode_AddType7(me, uNum.uSize, uNum.uValue);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800741#else /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700742 QCBOREncode_AddFloatNoPreferred(me, fNum);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800743#endif /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800744}
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +0200745#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800746
747
Laurence Lundbladedd6e76e2021-03-10 01:54:01 -0700748#ifndef QCBOR_DISABLE_EXP_AND_MANTISSA
Laurence Lundblade59289e52019-12-30 13:44:37 -0800749/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800750 * Semi-public function. It is exposed to the user of the interface,
751 * but one of the inline wrappers will usually be called rather than
752 * this.
753 *
754 * See qcbor/qcbor_encode.h
755 *
756 * Improvement: create another version of this that only takes a big
757 * number mantissa and converts the output to a type 0 or 1 integer
758 * when mantissa is small enough.
Laurence Lundblade59289e52019-12-30 13:44:37 -0800759 */
760void QCBOREncode_AddExponentAndMantissa(QCBOREncodeContext *pMe,
761 uint64_t uTag,
762 UsefulBufC BigNumMantissa,
763 bool bBigNumIsNegative,
764 int64_t nMantissa,
765 int64_t nExponent)
766{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800767 /* This is for encoding either a big float or a decimal fraction,
768 * both of which are an array of two items, an exponent and a
769 * mantissa. The difference between the two is that the exponent
770 * is base-2 for big floats and base-10 for decimal fractions, but
771 * that has no effect on the code here.
Laurence Lundbladeee851742020-01-08 08:37:05 -0800772 */
Laurence Lundbladeae66d3f2020-09-14 18:12:08 -0700773 if(uTag != CBOR_TAG_INVALID64) {
774 QCBOREncode_AddTag(pMe, uTag);
775 }
Laurence Lundblade59289e52019-12-30 13:44:37 -0800776 QCBOREncode_OpenArray(pMe);
777 QCBOREncode_AddInt64(pMe, nExponent);
778 if(!UsefulBuf_IsNULLC(BigNumMantissa)) {
779 if(bBigNumIsNegative) {
780 QCBOREncode_AddNegativeBignum(pMe, BigNumMantissa);
781 } else {
782 QCBOREncode_AddPositiveBignum(pMe, BigNumMantissa);
783 }
784 } else {
785 QCBOREncode_AddInt64(pMe, nMantissa);
786 }
787 QCBOREncode_CloseArray(pMe);
788}
Laurence Lundbladedd6e76e2021-03-10 01:54:01 -0700789#endif /* QCBOR_DISABLE_EXP_AND_MANTISSA */
Laurence Lundblade59289e52019-12-30 13:44:37 -0800790
791
Laurence Lundblade067035b2018-11-28 17:35:25 -0800792/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800793 * Semi-public function. It is exposed to the user of the interface,
794 * but one of the inline wrappers will usually be called rather than
795 * this.
796 *
797 * See qcbor/qcbor_encode.h
Laurence Lundblade067035b2018-11-28 17:35:25 -0800798*/
799void QCBOREncode_OpenMapOrArray(QCBOREncodeContext *me, uint8_t uMajorType)
800{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800801 /* Add one item to the nesting level we are in for the new map or array */
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800802 IncrementMapOrArrayCount(me);
Laurence Lundbladed39cd392019-01-11 18:17:38 -0800803
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800804 /* The offset where the length of an array or map will get written
805 * is stored in a uint32_t, not a size_t to keep stack usage
806 * smaller. This checks to be sure there is no wrap around when
807 * recording the offset. Note that on 64-bit machines CBOR larger
808 * than 4GB can be encoded as long as no array/map offsets occur
809 * past the 4GB mark, but the public interface says that the
810 * maximum is 4GB to keep the discussion simpler.
811 */
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800812 size_t uEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
Laurence Lundbladed39cd392019-01-11 18:17:38 -0800813
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800814 /* QCBOR_MAX_ARRAY_OFFSET is slightly less than UINT32_MAX so this
815 * code can run on a 32-bit machine and tests can pass on a 32-bit
816 * machine. If it was exactly UINT32_MAX, then this code would not
817 * compile or run on a 32-bit machine and an #ifdef or some machine
818 * size detection would be needed reducing portability.
819 */
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800820 if(uEndPosition >= QCBOR_MAX_ARRAY_OFFSET) {
821 me->uError = QCBOR_ERR_BUFFER_TOO_LARGE;
822
823 } else {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800824 /* Increase nesting level because this is a map or array. Cast
825 * from size_t to uin32_t is safe because of check above.
826 */
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800827 me->uError = Nesting_Increase(&(me->nesting), uMajorType, (uint32_t)uEndPosition);
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800828 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700829}
830
Laurence Lundblade59289e52019-12-30 13:44:37 -0800831
Jan Jongboom4a93a662019-07-25 08:44:58 +0200832/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800833 * Semi-public function. It is exposed to the user of the interface,
834 * but one of the inline wrappers will usually be called rather than
835 * this.
836 *
837 * See qcbor/qcbor_encode.h
838 */
Jan Jongboom4a93a662019-07-25 08:44:58 +0200839void QCBOREncode_OpenMapOrArrayIndefiniteLength(QCBOREncodeContext *me, uint8_t uMajorType)
840{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800841 /* Insert the indefinite length marker (0x9f for arrays, 0xbf for maps) */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000842 AppendCBORHead(me, uMajorType, 0, 0);
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800843
844 /* Call the definite-length opener just to do the bookkeeping for
845 * nesting. It will record the position of the opening item in the
846 * encoded output but this is not used when closing this open.
847 */
Jan Jongboom4a93a662019-07-25 08:44:58 +0200848 QCBOREncode_OpenMapOrArray(me, uMajorType);
849}
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700850
Laurence Lundbladeee851742020-01-08 08:37:05 -0800851
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700852/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800853 * Public functions for closing arrays and maps. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700854 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000855void QCBOREncode_CloseMapOrArray(QCBOREncodeContext *me, uint8_t uMajorType)
Laurence Lundbladea954db92018-09-28 19:27:31 -0700856{
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000857 InsertCBORHead(me, uMajorType, Nesting_GetCount(&(me->nesting)));
858}
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800859
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800860
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000861/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800862 * Public functions for closing bstr wrapping. See qcbor/qcbor_encode.h
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000863 */
864void QCBOREncode_CloseBstrWrap2(QCBOREncodeContext *me, bool bIncludeCBORHead, UsefulBufC *pWrappedCBOR)
865{
866 const size_t uInsertPosition = Nesting_GetStartPos(&(me->nesting));
867 const size_t uEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800868
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800869 /* This subtraction can't go negative because the UsefulOutBuf
870 * always only grows and never shrinks. UsefulOutBut itself also
871 * has defenses such that it won't write where it should not even
872 * if given incorrect input lengths.
873 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000874 const size_t uBstrLen = uEndPosition - uInsertPosition;
875
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800876 /* Actually insert */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000877 InsertCBORHead(me, CBOR_MAJOR_TYPE_BYTE_STRING, uBstrLen);
878
879 if(pWrappedCBOR) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800880 /* Return pointer and length to the enclosed encoded CBOR. The
881 * intended use is for it to be hashed (e.g., SHA-256) in a COSE
882 * implementation. This must be used right away, as the pointer
883 * and length go invalid on any subsequent calls to this
884 * function because there might be calls to
885 * InsertEncodedTypeAndNumber() that slides data to the right.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000886 */
887 size_t uStartOfNew = uInsertPosition;
888 if(!bIncludeCBORHead) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800889 /* Skip over the CBOR head to just get the inserted bstr */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000890 const size_t uNewEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
891 uStartOfNew += uNewEndPosition - uEndPosition;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700892 }
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000893 const UsefulBufC PartialResult = UsefulOutBuf_OutUBuf(&(me->OutBuf));
894 *pWrappedCBOR = UsefulBuf_Tail(PartialResult, uStartOfNew);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700895 }
896}
897
Laurence Lundbladeee851742020-01-08 08:37:05 -0800898
Jan Jongboom4a93a662019-07-25 08:44:58 +0200899/*
Laurence Lundblade8d3b8552021-06-10 11:11:54 -0700900 * Public function for canceling a bstr wrap. See qcbor/qcbor_encode.h
901 */
902void QCBOREncode_CancelBstrWrap(QCBOREncodeContext *pMe)
903{
904#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
905 if(pMe->uError == QCBOR_SUCCESS) {
906 if(!Nesting_IsInNest(&(pMe->nesting))) {
907 pMe->uError = QCBOR_ERR_TOO_MANY_CLOSES;
908 return;
909 } else if(Nesting_GetMajorType(&(pMe->nesting)) != CBOR_MAJOR_TYPE_BYTE_STRING) {
910 pMe->uError = QCBOR_ERR_CLOSE_MISMATCH;
911 return;
912 }
913 const size_t uCurrent = UsefulOutBuf_GetEndPosition(&(pMe->OutBuf));
914 if(pMe->nesting.pCurrentNesting->uStart != uCurrent) {
915 pMe->uError = QCBOR_ERR_CANNOT_CANCEL;
916 return;
917 }
918 }
919 /* QCBOREncode_CancelBstrWrap() can't correctly undo
920 * QCBOREncode_BstrWrapInMap() or QCBOREncode_BstrWrapInMapN(). It
921 * can't undo the labels they add. It also doesn't catch the error
922 * of using it this way. QCBOREncode_CancelBstrWrap() is used
923 * infrequently and the the result is incorrect CBOR, not a
924 * security hole, so no extra code or state is added to handle this
925 * condition.
926 */
927#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
928
929 Nesting_Decrease(&(pMe->nesting));
930 Nesting_Decrement(&(pMe->nesting));
931}
932
933
934/*
935 * Public function for closing arrays and maps. See qcbor/qcbor_encode.h
Jan Jongboom4a93a662019-07-25 08:44:58 +0200936 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000937void QCBOREncode_CloseMapOrArrayIndefiniteLength(QCBOREncodeContext *me, uint8_t uMajorType)
Jan Jongboom4a93a662019-07-25 08:44:58 +0200938{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800939#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Jan Jongboom4a93a662019-07-25 08:44:58 +0200940 if(me->uError == QCBOR_SUCCESS) {
941 if(!Nesting_IsInNest(&(me->nesting))) {
942 me->uError = QCBOR_ERR_TOO_MANY_CLOSES;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800943 return;
Jan Jongboom4a93a662019-07-25 08:44:58 +0200944 } else if(Nesting_GetMajorType(&(me->nesting)) != uMajorType) {
945 me->uError = QCBOR_ERR_CLOSE_MISMATCH;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800946 return;
Jan Jongboom4a93a662019-07-25 08:44:58 +0200947 }
948 }
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800949#else /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800950 (void) uMajorType;
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800951#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800952
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800953 /* Append the break marker (0xff for both arrays and maps) */
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800954 AppendCBORHead(me, CBOR_MAJOR_NONE_TYPE_SIMPLE_BREAK, CBOR_SIMPLE_BREAK, 0);
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800955 Nesting_Decrease(&(me->nesting));
Jan Jongboom4a93a662019-07-25 08:44:58 +0200956}
957
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700958
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700959/*
Laurence Lundblade8d3b8552021-06-10 11:11:54 -0700960 * Public function to finish and get the encoded result. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700961 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700962QCBORError QCBOREncode_Finish(QCBOREncodeContext *me, UsefulBufC *pEncodedCBOR)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700963{
Laurence Lundbladef607a2a2019-07-05 21:25:25 -0700964 QCBORError uReturn = QCBOREncode_GetErrorState(me);
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800965
Laurence Lundblade067035b2018-11-28 17:35:25 -0800966 if(uReturn != QCBOR_SUCCESS) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700967 goto Done;
Laurence Lundblade067035b2018-11-28 17:35:25 -0800968 }
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800969
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800970#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800971 if(Nesting_IsInNest(&(me->nesting))) {
Laurence Lundblade067035b2018-11-28 17:35:25 -0800972 uReturn = QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700973 goto Done;
974 }
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800975#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800976
Laurence Lundbladeda3f0822018-09-18 19:49:02 -0700977 *pEncodedCBOR = UsefulOutBuf_OutUBuf(&(me->OutBuf));
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800978
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700979Done:
Laurence Lundblade067035b2018-11-28 17:35:25 -0800980 return uReturn;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700981}
982
Laurence Lundblade0595e932018-11-02 22:22:47 +0700983
Laurence Lundblade067035b2018-11-28 17:35:25 -0800984/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800985 * Public functions to get size of the encoded result. See qcbor/qcbor_encode.h
Laurence Lundblade067035b2018-11-28 17:35:25 -0800986 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700987QCBORError QCBOREncode_FinishGetSize(QCBOREncodeContext *me, size_t *puEncodedLen)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700988{
Laurence Lundbladeda3f0822018-09-18 19:49:02 -0700989 UsefulBufC Enc;
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800990
Laurence Lundblade30816f22018-11-10 13:40:22 +0700991 QCBORError nReturn = QCBOREncode_Finish(me, &Enc);
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800992
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700993 if(nReturn == QCBOR_SUCCESS) {
Laurence Lundbladeda3f0822018-09-18 19:49:02 -0700994 *puEncodedLen = Enc.len;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700995 }
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800996
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700997 return nReturn;
998}