blob: 7c248ef53e0ba48b30584a01fef2eeab80e84dce [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.
Laurence Lundbladed92a6162018-11-01 11:38:35 +07004 All rights reserved.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08005
Laurence Lundblade0dbc9172018-11-01 14:17:21 +07006Redistribution and use in source and binary forms, with or without
7modification, are permitted provided that the following conditions are
8met:
9 * Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11 * Redistributions in binary form must reproduce the above
12 copyright notice, this list of conditions and the following
13 disclaimer in the documentation and/or other materials provided
14 with the distribution.
15 * Neither the name of The Linux Foundation nor the names of its
16 contributors, nor the name "Laurence Lundblade" may be used to
17 endorse or promote products derived from this software without
18 specific prior written permission.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080019
Laurence Lundblade0dbc9172018-11-01 14:17:21 +070020THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
21WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
22MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
23ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
24BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
27BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
28WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
29OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
30IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Laurence Lundbladeee851742020-01-08 08:37:05 -080031 =============================================================================*/
Laurence Lundblade624405d2018-09-18 20:10:47 -070032
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080033
Laurence Lundblade844bb5c2020-03-01 17:27:25 -080034#include "qcbor/qcbor_encode.h"
Laurence Lundblade12d32c52018-09-19 11:25:27 -070035#include "ieee754.h"
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070036
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070037
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080038/**
39 * @file qcbor_encode.c
Laurence Lundblade3f1318a2021-01-04 18:26:44 -080040 *
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080041 * The entire implementation of the QCBOR encoder.
42 */
43
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070044
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070045/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080046 * == Nesting Tracking ==
47 *
48 * The following functions and data type QCBORTrackNesting implement
49 * the nesting management for encoding.
50 *
51 * CBOR's two nesting types, arrays and maps, are tracked here. There
52 * is a limit of QCBOR_MAX_ARRAY_NESTING to the number of arrays and
53 * maps that can be nested in one encoding so the encoding context
54 * stays small enough to fit on the stack.
55 *
56 * When an array/map is opened, pCurrentNesting points to the element
57 * in pArrays that records the type, start position and accumulates a
58 * count of the number of items added. When closed the start position
59 * is used to go back and fill in the type and number of items in the
60 * array/map.
61 *
62 * Encoded output can be a CBOR Sequence (RFC 8742) in which case
63 * there is no top-level array or map. It starts out with a string,
64 * integer or other non-aggregate type. It may have an array or map
65 * other than at the start, in which case that nesting is tracked
66 * here.
67 *
68 * QCBOR has a special feature to allow constructing byte string
69 * wrapped CBOR directly into the output buffer, so no extra buffer is
70 * needed for byte string wrapping. This is implemented as nesting
71 * with the type CBOR_MAJOR_TYPE_BYTE_STRING and is tracked here. Byte
72 * string wrapped CBOR is used by COSE for data that is to be hashed.
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070073 */
74inline static void Nesting_Init(QCBORTrackNesting *pNesting)
75{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080076 /* Assumes pNesting has been zeroed. */
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070077 pNesting->pCurrentNesting = &pNesting->pArrays[0];
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080078 /* Implied CBOR array at the top nesting level. This is never
79 * returned, but makes the item count work correctly.
80 */
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070081 pNesting->pCurrentNesting->uMajorType = CBOR_MAJOR_TYPE_ARRAY;
82}
83
Laurence Lundblade29497c02020-07-11 15:44:03 -070084inline static uint8_t Nesting_Increase(QCBORTrackNesting *pNesting,
Laurence Lundblade2c40ab82018-12-30 14:20:29 -080085 uint8_t uMajorType,
86 uint32_t uPos)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070087{
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070088 if(pNesting->pCurrentNesting == &pNesting->pArrays[QCBOR_MAX_ARRAY_NESTING]) {
Laurence Lundblade29497c02020-07-11 15:44:03 -070089 return QCBOR_ERR_ARRAY_NESTING_TOO_DEEP;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070090 } else {
91 pNesting->pCurrentNesting++;
92 pNesting->pCurrentNesting->uCount = 0;
93 pNesting->pCurrentNesting->uStart = uPos;
94 pNesting->pCurrentNesting->uMajorType = uMajorType;
Laurence Lundblade29497c02020-07-11 15:44:03 -070095 return QCBOR_SUCCESS;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070096 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070097}
98
99inline static void Nesting_Decrease(QCBORTrackNesting *pNesting)
100{
101 pNesting->pCurrentNesting--;
102}
103
Laurence Lundblade29497c02020-07-11 15:44:03 -0700104inline static uint8_t Nesting_Increment(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700105{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800106#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800107 if(1 >= QCBOR_MAX_ITEMS_IN_ARRAY - pNesting->pCurrentNesting->uCount) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700108 return QCBOR_ERR_ARRAY_TOO_LONG;
109 }
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800110#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800111
Laurence Lundbladee6bcef12020-04-01 10:56:27 -0700112 pNesting->pCurrentNesting->uCount++;
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800113
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700114 return QCBOR_SUCCESS;
115}
116
Laurence Lundblade8d3b8552021-06-10 11:11:54 -0700117inline static void Nesting_Decrement(QCBORTrackNesting *pNesting)
118{
119 /* No error check for going below 0 here needed because this
120 * is only used by QCBOREncode_CancelBstrWrap() and it checks
121 * the nesting level before calling this. */
122 pNesting->pCurrentNesting->uCount--;
123}
124
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700125inline static uint16_t Nesting_GetCount(QCBORTrackNesting *pNesting)
126{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800127 /* The nesting count recorded is always the actual number of
128 * individual data items in the array or map. For arrays CBOR uses
129 * the actual item count. For maps, CBOR uses the number of pairs.
130 * This function returns the number needed for the CBOR encoding,
131 * so it divides the number of items by two for maps to get the
132 * number of pairs.
133 */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800134 if(pNesting->pCurrentNesting->uMajorType == CBOR_MAJOR_TYPE_MAP) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800135 /* Cast back to uint16_t after integer promotion from bit shift */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800136 return (uint16_t)(pNesting->pCurrentNesting->uCount >> 1);
137 } else {
138 return pNesting->pCurrentNesting->uCount;
139 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700140}
141
142inline static uint32_t Nesting_GetStartPos(QCBORTrackNesting *pNesting)
143{
144 return pNesting->pCurrentNesting->uStart;
145}
146
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800147#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700148inline static uint8_t Nesting_GetMajorType(QCBORTrackNesting *pNesting)
149{
150 return pNesting->pCurrentNesting->uMajorType;
151}
152
Laurence Lundbladeee851742020-01-08 08:37:05 -0800153inline static bool Nesting_IsInNest(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700154{
Laurence Lundbladeee851742020-01-08 08:37:05 -0800155 return pNesting->pCurrentNesting == &pNesting->pArrays[0] ? false : true;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700156}
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800157#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700158
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700159
160
161
162/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800163 * == Major CBOR Types ==
164 *
165 * Encoding of the major CBOR types is by these functions:
166 *
Laurence Lundblade3f1318a2021-01-04 18:26:44 -0800167 * CBOR Major Type Public Function
168 * 0 QCBOREncode_AddUInt64()
169 * 0, 1 QCBOREncode_AddUInt64(), QCBOREncode_AddInt64()
170 * 2, 3 QCBOREncode_AddBuffer()
171 * 4, 5 QCBOREncode_OpenMapOrArray(), QCBOREncode_CloseMapOrArray(),
172 * QCBOREncode_OpenMapOrArrayIndefiniteLength(),
173 * QCBOREncode_CloseMapOrArrayIndefiniteLength()
174 * 6 QCBOREncode_AddTag()
175 * 7 QCBOREncode_AddDouble(), QCBOREncode_AddFloat(),
176 * QCBOREncode_AddDoubleNoPreferred(),
177 * QCBOREncode_AddFloatNoPreferred(), QCBOREncode_AddType7()
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800178 *
179 * Additionally, encoding of decimal fractions and bigfloats is by
180 * QCBOREncode_AddExponentAndMantissa() and byte strings that wrap
181 * encoded CBOR are handled by QCBOREncode_OpenMapOrArray() and
182 * QCBOREncode_CloseBstrWrap2().
183 *
184 *
185 * == Error Tracking Plan ==
186 *
187 * Errors are tracked internally and not returned until
188 * QCBOREncode_Finish() or QCBOREncode_GetErrorState() is called. The
189 * CBOR errors are in me->uError. UsefulOutBuf also tracks whether
190 * the buffer is full or not in its context. Once either of these
191 * errors is set they are never cleared. Only QCBOREncode_Init()
192 * resets them. Or said another way, they must never be cleared or
193 * we'll tell the caller all is good when it is not.
194 *
195 * Only one error code is reported by QCBOREncode_Finish() even if
196 * there are multiple errors. The last one set wins. The caller might
197 * have to fix one error to reveal the next one they have to fix.
198 * This is OK.
199 *
200 * The buffer full error tracked by UsefulBuf is only pulled out of
201 * UsefulBuf in QCBOREncode_Finish() so it is the one that usually
202 * wins. UsefulBuf will never go off the end of the buffer even if it
203 * is called again and again when full.
204 *
205 * QCBOR_DISABLE_ENCODE_USAGE_GUARDS disables about half of the error
206 * checks here to reduce code size by about 150 bytes leaving only the
207 * checks for size to avoid buffer overflow. If the calling code is
208 * completely correct, checks are completely unnecessary. For
209 * example, there is no need to check that all the opens are matched
210 * by a close.
211 *
212 * QCBOR_DISABLE_ENCODE_USAGE_GUARDS also disables the check for more
213 * than QCBOR_MAX_ITEMS_IN_ARRAY in an array. Since
214 * QCBOR_MAX_ITEMS_IN_ARRAY is very large (65,535) it is very unlikely
215 * to be reached. If it is reached, the count will wrap around to zero
216 * and CBOR that is not well formed will be produced, but there will
217 * be no buffers overrun and new security issues in the code.
218 *
219 * The 8 errors returned here fall into three categories:
220 *
221 * Sizes
222 * QCBOR_ERR_BUFFER_TOO_LARGE -- Encoded output exceeded UINT32_MAX
223 * QCBOR_ERR_BUFFER_TOO_SMALL -- Output buffer too small
224 * QCBOR_ERR_ARRAY_NESTING_TOO_DEEP -- Nesting > QCBOR_MAX_ARRAY_NESTING1
225 * QCBOR_ERR_ARRAY_TOO_LONG -- Too many items added to an array/map [1]
226 *
227 * Nesting constructed incorrectly
228 * QCBOR_ERR_TOO_MANY_CLOSES -- More close calls than opens [1]
229 * QCBOR_ERR_CLOSE_MISMATCH -- Type of close does not match open [1]
230 * QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN -- Finish called without enough closes [1]
231 *
232 * Would generate not-well-formed CBOR
233 * QCBOR_ERR_ENCODE_UNSUPPORTED -- Simple type between 24 and 31 [1]
234 *
235 * [1] indicated disabled by QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700236 */
237
238
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700239/*
Laurence Lundblade844bb5c2020-03-01 17:27:25 -0800240 Public function for initialization. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700241 */
Laurence Lundblade2296db52018-09-14 18:08:39 -0700242void QCBOREncode_Init(QCBOREncodeContext *me, UsefulBuf Storage)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700243{
244 memset(me, 0, sizeof(QCBOREncodeContext));
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800245 UsefulOutBuf_Init(&(me->OutBuf), Storage);
246 Nesting_Init(&(me->nesting));
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700247}
248
249
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000250/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800251 * Public function to encode a CBOR head. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700252 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000253UsefulBufC QCBOREncode_EncodeHead(UsefulBuf buffer,
254 uint8_t uMajorType,
255 uint8_t uMinLen,
256 uint64_t uArgument)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700257{
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800258 /*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800259 * == Description of the CBOR Head ==
260 *
261 * The head of a CBOR data item
262 * +---+-----+ +--------+ +--------+ +--------+ +--------+
263 * |M T| A R G U M E N T . . . |
264 * +---+-----+ +--------+ +--------+ +--------+ ... +--------+
265 *
266 * Every CBOR data item has a "head". It is made up of the "major
267 * type" and the "argument".
268 *
269 * The major type indicates whether the data item is an integer,
270 * string, array or such. It is encoded in 3 bits giving it a range
271 * from 0 to 7. 0 indicates the major type is a positive integer,
272 * 1 a negative integer, 2 a byte string and so on.
273 *
274 * These 3 bits are the first part of the "initial byte" in a data
275 * item. Every data item has an initial byte, and some only have
276 * the initial byte.
277 *
278 * The argument is essentially a number between 0 and UINT64_MAX
279 * (18446744073709551615). This number is interpreted to mean
280 * different things for the different major types. For major type
281 * 0, a positive integer, it is value of the data item. For major
282 * type 2, a byte string, it is the length in bytes of the byte
283 * string. For major type 4, an array, it is the number of data
284 * items in the array.
285 *
286 * Special encoding is used so that the argument values less than
287 * 24 can be encoded very compactly in the same byte as the major
288 * type is encoded. When the lower 5 bits of the initial byte have
289 * a value less than 24, then that is the value of the argument.
290 *
291 * If the lower 5 bits of the initial byte are less than 24, then
292 * they are the value of the argument. This allows integer values 0
293 * - 23 to be CBOR encoded in just one byte.
294 *
295 * When the value of lower 5 bits are 24, 25, 26, or 27 the
296 * argument is encoded in 1, 2, 4 or 8 bytes following the initial
297 * byte in network byte order (bit endian). The cases when it is
298 * 28, 29 and 30 are reserved for future use. The value 31 is a
299 * special indicator for indefinite length strings, arrays and
300 * maps.
301 *
302 * The lower 5 bits are called the "additional information."
303 *
304 * Thus the CBOR head may be 1, 2, 3, 5 or 9 bytes long.
305 *
306 * It is legal in CBOR to encode the argument using any of these
307 * lengths even if it could be encoded in a shorter length. For
308 * example it is legal to encode a data item representing the
309 * positive integer 0 in 9 bytes even though it could be encoded in
310 * only 0. This is legal to allow for for very simple code or even
311 * hardware-only implementations that just output a register
312 * directly.
313 *
314 * CBOR defines preferred encoding as the encoding of the argument
315 * in the smallest number of bytes needed to encode it.
316 *
317 * This function takes the major type and argument as inputs and
318 * outputs the encoded CBOR head for them. It does conversion to
319 * network byte order. It implements CBOR preferred encoding,
320 * outputting the shortest representation of the argument.
321 *
322 * == Endian Conversion ==
323 *
324 * This code does endian conversion without hton() or knowing the
325 * endianness of the machine by using masks and shifts. This avoids
326 * the dependency on hton() and the mess of figuring out how to
327 * find the machine's endianness.
328 *
329 * This is a good efficient implementation on little-endian
330 * machines. A faster and smaller implementation is possible on
331 * big-endian machines because CBOR/network byte order is
332 * big-endian. However big-endian machines are uncommon.
333 *
334 * On x86, this is about 150 bytes instead of 500 bytes for the
335 * original, more formal unoptimized code.
336 *
337 * This also does the CBOR preferred shortest encoding for integers
338 * and is called to do endian conversion for floats.
339 *
340 * It works backwards from the least significant byte to the most
341 * significant byte.
342 *
343 * == Floating Point ==
344 *
345 * When the major type is 7 and the 5 lower bits have the values
346 * 25, 26 or 27, the argument is a floating-point number that is
347 * half, single or double-precision. Note that it is not the
348 * conversion from a floating-point value to an integer value like
349 * converting 0x00 to 0.00, it is the interpretation of the bits in
350 * the argument as an IEEE 754 float-point number.
351 *
352 * Floating-point numbers must be converted to network byte
353 * order. That is accomplished here by exactly the same code that
354 * converts integer arguments to network byte order.
355 *
356 * There is preferred encoding for floating-point numbers in CBOR,
357 * but it is very different than for integers and it is not
358 * implemented here. Half-precision is preferred to
359 * single-precision which is preferred to double-precision only if
360 * the conversion can be performed without loss of precision. Zero
361 * and infinity can always be converted to half-precision, without
362 * loss but 3.141592653589 cannot.
363 *
364 * The way this function knows to not do preferred encoding on the
365 * argument passed here when it is a floating point number is the
366 * uMinLen parameter. It should be 2, 4 or 8 for half, single and
367 * double precision floating point values. This prevents and the
368 * incorrect removal of leading zeros when encoding arguments that
369 * are floating-point numbers.
370 *
371 * == Use of Type int and Static Analyzers ==
372 *
373 * The type int is used here for several variables because of the
374 * way integer promotion works in C for variables that are uint8_t
375 * or uint16_t. The basic rule is that they will always be promoted
376 * to int if they will fit. These integer variables here need only
377 * hold values less than 255 so they will always fit into an int.
378 *
379 * Most of values stored are never negative, so one might think
380 * that unsigned int would be more correct than int. However the C
381 * integer promotion rules only promote to unsigned int if the
382 * result won't fit into an int even if the promotion is for an
383 * unsigned variable like uint8_t.
384 *
385 * By declaring these int, there are few implicit conversions and
386 * fewer casts needed. Code size is reduced a little. It makes
387 * static analyzers happier.
388 *
389 * Note also that declaring these uint8_t won't stop integer wrap
390 * around if the code is wrong. It won't make the code more
391 * correct.
392 *
393 * https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules
394 * https://stackoverflow.com/questions/589575/what-does-the-c-standard-state-the-size-of-int-long-type-to-be
395 *
396 * Code Reviewers: THIS FUNCTION DOES POINTER MATH
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800397 */
Laurence Lundbladeee851742020-01-08 08:37:05 -0800398
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800399 /* The buffer must have room for the largest CBOR HEAD + one
400 * extra. The one extra is needed for this code to work as it does
401 * a pre-decrement.
402 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000403 if(buffer.len < QCBOR_HEAD_BUFFER_SIZE) {
404 return NULLUsefulBufC;
405 }
406
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800407 /* Pointer to last valid byte in the buffer */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000408 uint8_t * const pBufferEnd = &((uint8_t *)buffer.ptr)[QCBOR_HEAD_BUFFER_SIZE-1];
409
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800410 /* Point to the last byte and work backwards */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000411 uint8_t *pByte = pBufferEnd;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800412 /* The 5 bits in the initial byte that are not the major type */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800413 int nAdditionalInfo;
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800414
Laurence Lundblade8c858ab2020-11-02 19:53:49 -0800415 if(uMajorType > QCBOR_INDEFINITE_LEN_TYPE_MODIFIER) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800416 /* Special case for start & end of indefinite length */
Laurence Lundblade8c858ab2020-11-02 19:53:49 -0800417 uMajorType = uMajorType - QCBOR_INDEFINITE_LEN_TYPE_MODIFIER;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800418 /* This takes advantage of design of CBOR where additional info
419 * is 31 for both opening and closing indefinite length
420 * maps and arrays.
421 */
422 #if CBOR_SIMPLE_BREAK != LEN_IS_INDEFINITE
423 #error additional info for opening array not the same as for closing
424 #endif
Laurence Lundblade8c858ab2020-11-02 19:53:49 -0800425 nAdditionalInfo = CBOR_SIMPLE_BREAK;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800426
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000427 } else if (uArgument < CBOR_TWENTY_FOUR && uMinLen == 0) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800428 /* Simple case where argument is < 24 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000429 nAdditionalInfo = (int)uArgument;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800430
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800431 } else {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800432 /* This encodes the argument in 1,2,4 or 8 bytes. The outer loop
433 * runs once for 1 byte and 4 times for 8 bytes. The inner loop
434 * runs 1, 2 or 4 times depending on outer loop counter. This
435 * works backwards shifting 8 bits off the argument being
436 * encoded at a time until all bits from uArgument have been
437 * encoded and the minimum encoding size is reached. Minimum
438 * encoding size is for floating-point numbers that have some
439 * zero-value bytes that must be output.
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800440 */
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800441 static const uint8_t aIterate[] = {1,1,2,4};
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000442
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800443 /* uMinLen passed in is unsigned, but goes negative in the loop
444 * so it must be converted to a signed value.
445 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000446 int nMinLen = (int)uMinLen;
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800447 int i;
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000448 for(i = 0; uArgument || nMinLen > 0; i++) {
449 const int nIterations = (int)aIterate[i];
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800450 for(int j = 0; j < nIterations; j++) {
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000451 *--pByte = (uint8_t)(uArgument & 0xff);
452 uArgument = uArgument >> 8;
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800453 }
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800454 nMinLen -= nIterations;
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800455 }
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800456
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800457 nAdditionalInfo = LEN_IS_ONE_BYTE-1 + i;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700458 }
Laurence Lundbladef970f1d2018-12-14 01:44:23 -0800459
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800460 /* This expression integer-promotes to type int. The code above in
461 * function guarantees that nAdditionalInfo will never be larger
462 * than 0x1f. The caller may pass in a too-large uMajor type. The
463 * conversion to unint8_t will cause an integer wrap around and
464 * incorrect CBOR will be generated, but no security issue will
465 * occur.
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800466 */
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800467 const int nInitialByte = (uMajorType << 5) + nAdditionalInfo;
468 *--pByte = (uint8_t)nInitialByte;
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800469
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000470#ifdef EXTRA_ENCODE_HEAD_CHECK
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800471 /* This is a sanity check that can be turned on to verify the
472 * pointer math in this function is not going wrong. Turn it on and
473 * run the whole test suite to perform the check.
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800474 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000475 if(pBufferEnd - pByte > 9 || pBufferEnd - pByte < 1 || pByte < (uint8_t *)buffer.ptr) {
476 return NULLUsefulBufC;
477 }
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800478#endif /* EXTRA_ENCODE_HEAD_CHECK */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800479
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800480 /* Length will not go negative because the loops run for at most 8 decrements
481 * of pByte, only one other decrement is made, and the array is sized
482 * for this.
483 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000484 return (UsefulBufC){pByte, (size_t)(pBufferEnd - pByte)};
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700485}
486
487
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000488/**
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800489 * @brief Append the CBOR head, the major type and argument
490 *
491 * @param me Encoder context.
492 * @param uMajorType Major type to insert.
493 * @param uArgument The argument (an integer value or a length).
494 * @param uMinLen The minimum number of bytes for encoding the CBOR argument.
495 *
496 * This formats the CBOR "head" and appends it to the output.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000497 */
498static void AppendCBORHead(QCBOREncodeContext *me, uint8_t uMajorType, uint64_t uArgument, uint8_t uMinLen)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700499{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800500 /* A stack buffer large enough for a CBOR head */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000501 UsefulBuf_MAKE_STACK_UB (pBufferForEncodedHead, QCBOR_HEAD_BUFFER_SIZE);
502
503 UsefulBufC EncodedHead = QCBOREncode_EncodeHead(pBufferForEncodedHead,
504 uMajorType,
505 uMinLen,
506 uArgument);
507
508 /* No check for EncodedHead == NULLUsefulBufC is performed here to
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800509 * save object code. It is very clear that pBufferForEncodedHead is
510 * the correct size. If EncodedHead == NULLUsefulBufC then
511 * UsefulOutBuf_AppendUsefulBuf() will do nothing so there is no
512 * security hole introduced.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000513 */
514
515 UsefulOutBuf_AppendUsefulBuf(&(me->OutBuf), EncodedHead);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700516}
517
518
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000519/**
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800520 * @brief Insert the CBOR head for a map, array or wrapped bstr
521 *
522 * @param me QCBOR encoding context.
523 * @param uMajorType One of CBOR_MAJOR_TYPE_XXXX.
524 * @param uLen The length of the data item.
525 *
526 * When an array, map or bstr was opened, nothing was done but note
527 * the position. This function goes back to that position and inserts
528 * the CBOR Head with the major type and length.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000529 */
530static void InsertCBORHead(QCBOREncodeContext *me, uint8_t uMajorType, size_t uLen)
531{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800532#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000533 if(me->uError == QCBOR_SUCCESS) {
534 if(!Nesting_IsInNest(&(me->nesting))) {
535 me->uError = QCBOR_ERR_TOO_MANY_CLOSES;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800536 return;
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000537 } else if(Nesting_GetMajorType(&(me->nesting)) != uMajorType) {
538 me->uError = QCBOR_ERR_CLOSE_MISMATCH;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800539 return;
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000540 }
541 }
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800542#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800543
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800544 /* A stack buffer large enough for a CBOR head */
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800545 UsefulBuf_MAKE_STACK_UB(pBufferForEncodedHead, QCBOR_HEAD_BUFFER_SIZE);
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800546
547 UsefulBufC EncodedHead = QCBOREncode_EncodeHead(pBufferForEncodedHead,
548 uMajorType,
549 0,
550 uLen);
551
552 /* No check for EncodedHead == NULLUsefulBufC is performed here to
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800553 * save object code. It is very clear that pBufferForEncodedHead is
554 * the correct size. If EncodedHead == NULLUsefulBufC then
555 * UsefulOutBuf_InsertUsefulBuf() will do nothing so there is no
Laurence Lundblade9e2f7082021-05-17 02:10:48 -0700556 * security hole introduced.
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800557 */
558 UsefulOutBuf_InsertUsefulBuf(&(me->OutBuf),
559 EncodedHead,
560 Nesting_GetStartPos(&(me->nesting)));
561
562 Nesting_Decrease(&(me->nesting));
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000563}
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700564
Laurence Lundblade241705e2018-12-30 18:56:14 -0800565
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800566/**
567 * @brief Increment item counter for maps and arrays.
568 *
569 * @param pMe QCBOR encoding context.
570 *
571 * This is mostly a separate function to make code more readable and
572 * to have fewer occurrences of #ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800573 */
574static inline void IncrementMapOrArrayCount(QCBOREncodeContext *pMe)
575{
576#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
577 if(pMe->uError == QCBOR_SUCCESS) {
578 pMe->uError = Nesting_Increment(&(pMe->nesting));
579 }
580#else
581 (void)Nesting_Increment(&(pMe->nesting));
582#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
583}
584
585
586/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800587 * Public functions for adding unsigned integers. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700588 */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800589void QCBOREncode_AddUInt64(QCBOREncodeContext *me, uint64_t uValue)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700590{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800591 AppendCBORHead(me, CBOR_MAJOR_TYPE_POSITIVE_INT, uValue, 0);
592
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800593 IncrementMapOrArrayCount(me);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700594}
595
Laurence Lundblade56230d12018-11-01 11:14:51 +0700596
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700597/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800598 * Public functions for adding signed integers. See qcbor/qcbor_encode.h
Laurence Lundblade067035b2018-11-28 17:35:25 -0800599 */
600void QCBOREncode_AddInt64(QCBOREncodeContext *me, int64_t nNum)
601{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800602 uint8_t uMajorType;
603 uint64_t uValue;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800604
605 if(nNum < 0) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800606 /* In CBOR -1 encodes as 0x00 with major type negative int. */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800607 uValue = (uint64_t)(-nNum - 1);
608 uMajorType = CBOR_MAJOR_TYPE_NEGATIVE_INT;
609 } else {
610 uValue = (uint64_t)nNum;
611 uMajorType = CBOR_MAJOR_TYPE_POSITIVE_INT;
612 }
613 AppendCBORHead(me, uMajorType, uValue, 0);
614
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800615 IncrementMapOrArrayCount(me);
Laurence Lundblade067035b2018-11-28 17:35:25 -0800616}
617
618
619/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800620 * Semi-private function. It is exposed to user of the interface, but
621 * one of its inline wrappers will usually be called instead of this.
622 *
623 * See qcbor/qcbor_encode.h
624 *
625 * This does the work of adding actual strings bytes to the CBOR
626 * output (as opposed to adding numbers and opening / closing
627 * aggregate types).
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800628
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800629 * There are four use cases:
630 * CBOR_MAJOR_TYPE_BYTE_STRING -- Byte strings
631 * CBOR_MAJOR_TYPE_TEXT_STRING -- Text strings
632 * CBOR_MAJOR_NONE_TYPE_RAW -- Already-encoded CBOR
633 * CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY -- Special case
634 *
635 * The first two add the head plus the actual bytes. The third just
636 * adds the bytes as the heas is presumed to be in the bytes. The
637 * fourth just adds the head for the very special case of
638 * QCBOREncode_AddBytesLenOnly().
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700639 */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800640void QCBOREncode_AddBuffer(QCBOREncodeContext *me, uint8_t uMajorType, UsefulBufC Bytes)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700641{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800642 /* If it is not Raw CBOR, add the type and the length */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800643 if(uMajorType != CBOR_MAJOR_NONE_TYPE_RAW) {
644 uint8_t uRealMajorType = uMajorType;
645 if(uRealMajorType == CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY) {
646 uRealMajorType = CBOR_MAJOR_TYPE_BYTE_STRING;
647 }
648 AppendCBORHead(me, uRealMajorType, Bytes.len, 0);
649 }
650
651 if(uMajorType != CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800652 /* Actually add the bytes */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800653 UsefulOutBuf_AppendUsefulBuf(&(me->OutBuf), Bytes);
654 }
655
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800656 IncrementMapOrArrayCount(me);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700657}
658
Laurence Lundbladecafcfe12018-10-31 21:59:50 +0700659
Laurence Lundblade55a24832018-10-30 04:35:08 +0700660/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800661 * Public functions for adding a tag. See qcbor/qcbor_encode.h
Laurence Lundblade55a24832018-10-30 04:35:08 +0700662 */
663void QCBOREncode_AddTag(QCBOREncodeContext *me, uint64_t uTag)
664{
Laurence Lundblade3f1318a2021-01-04 18:26:44 -0800665 AppendCBORHead(me, CBOR_MAJOR_TYPE_TAG, uTag, 0);
Laurence Lundblade55a24832018-10-30 04:35:08 +0700666}
667
668
Laurence Lundblade56230d12018-11-01 11:14:51 +0700669/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800670 * Semi-private function. It is exposed to user of the interface, but
671 * one of its inline wrappers will usually be called instead of this.
672 *
673 * See header qcbor/qcbor_encode.h
Laurence Lundblade56230d12018-11-01 11:14:51 +0700674 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000675void QCBOREncode_AddType7(QCBOREncodeContext *me, uint8_t uMinLen, uint64_t uNum)
Laurence Lundblade55a24832018-10-30 04:35:08 +0700676{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800677#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade487930f2018-11-30 11:01:45 -0800678 if(me->uError == QCBOR_SUCCESS) {
Laurence Lundbladebb1062e2019-08-12 23:28:54 -0700679 if(uNum >= CBOR_SIMPLEV_RESERVED_START && uNum <= CBOR_SIMPLEV_RESERVED_END) {
Laurence Lundbladea9489f82020-09-12 13:50:56 -0700680 me->uError = QCBOR_ERR_ENCODE_UNSUPPORTED;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800681 return;
Laurence Lundbladebb1062e2019-08-12 23:28:54 -0700682 }
Laurence Lundblade487930f2018-11-30 11:01:45 -0800683 }
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800684#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
685
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800686 /* AppendCBORHead() does endian swapping for the float / double */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800687 AppendCBORHead(me, CBOR_MAJOR_TYPE_SIMPLE, uNum, uMinLen);
Laurence Lundblade3f1318a2021-01-04 18:26:44 -0800688
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800689 IncrementMapOrArrayCount(me);
Laurence Lundblade55a24832018-10-30 04:35:08 +0700690}
691
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700692
Laurence Lundblade32f3e622020-07-13 20:35:11 -0700693/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800694 * Public functions for adding a double. See qcbor/qcbor_encode.h
695 */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700696void QCBOREncode_AddDoubleNoPreferred(QCBOREncodeContext *me, double dNum)
697{
Laurence Lundblade2feb1e12020-07-15 03:50:45 -0700698 QCBOREncode_AddType7(me,
699 sizeof(uint64_t),
700 UsefulBufUtil_CopyDoubleToUint64(dNum));
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700701}
702
Laurence Lundblade32f3e622020-07-13 20:35:11 -0700703
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700704/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800705 * Public functions for adding a double. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700706 */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800707void QCBOREncode_AddDouble(QCBOREncodeContext *me, double dNum)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700708{
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700709#ifndef QCBOR_DISABLE_PREFERRED_FLOAT
Laurence Lundblade067035b2018-11-28 17:35:25 -0800710 const IEEE754_union uNum = IEEE754_DoubleToSmallest(dNum);
Laurence Lundblade2feb1e12020-07-15 03:50:45 -0700711
Laurence Lundblade487930f2018-11-30 11:01:45 -0800712 QCBOREncode_AddType7(me, uNum.uSize, uNum.uValue);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800713#else /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700714 QCBOREncode_AddDoubleNoPreferred(me, dNum);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800715#endif /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700716}
Laurence Lundblade9682a532020-06-06 18:33:04 -0700717
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700718
Laurence Lundblade32f3e622020-07-13 20:35:11 -0700719/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800720 * Public functions for adding a float. See qcbor/qcbor_encode.h
721 */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700722void QCBOREncode_AddFloatNoPreferred(QCBOREncodeContext *me, float fNum)
723{
Laurence Lundblade2feb1e12020-07-15 03:50:45 -0700724 QCBOREncode_AddType7(me,
725 sizeof(uint32_t),
726 UsefulBufUtil_CopyFloatToUint32(fNum));
Laurence Lundblade9682a532020-06-06 18:33:04 -0700727}
728
729
730/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800731 * Public functions for adding a float. See qcbor/qcbor_encode.h
Laurence Lundblade9682a532020-06-06 18:33:04 -0700732 */
733void QCBOREncode_AddFloat(QCBOREncodeContext *me, float fNum)
734{
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700735#ifndef QCBOR_DISABLE_PREFERRED_FLOAT
Laurence Lundblade9682a532020-06-06 18:33:04 -0700736 const IEEE754_union uNum = IEEE754_FloatToSmallest(fNum);
Laurence Lundblade2feb1e12020-07-15 03:50:45 -0700737
Laurence Lundblade9682a532020-06-06 18:33:04 -0700738 QCBOREncode_AddType7(me, uNum.uSize, uNum.uValue);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800739#else /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700740 QCBOREncode_AddFloatNoPreferred(me, fNum);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800741#endif /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800742}
743
744
Laurence Lundbladedd6e76e2021-03-10 01:54:01 -0700745#ifndef QCBOR_DISABLE_EXP_AND_MANTISSA
Laurence Lundblade59289e52019-12-30 13:44:37 -0800746/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800747 * Semi-public function. It is exposed to the user of the interface,
748 * but one of the inline wrappers will usually be called rather than
749 * this.
750 *
751 * See qcbor/qcbor_encode.h
752 *
753 * Improvement: create another version of this that only takes a big
754 * number mantissa and converts the output to a type 0 or 1 integer
755 * when mantissa is small enough.
Laurence Lundblade59289e52019-12-30 13:44:37 -0800756 */
757void QCBOREncode_AddExponentAndMantissa(QCBOREncodeContext *pMe,
758 uint64_t uTag,
759 UsefulBufC BigNumMantissa,
760 bool bBigNumIsNegative,
761 int64_t nMantissa,
762 int64_t nExponent)
763{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800764 /* This is for encoding either a big float or a decimal fraction,
765 * both of which are an array of two items, an exponent and a
766 * mantissa. The difference between the two is that the exponent
767 * is base-2 for big floats and base-10 for decimal fractions, but
768 * that has no effect on the code here.
Laurence Lundbladeee851742020-01-08 08:37:05 -0800769 */
Laurence Lundbladeae66d3f2020-09-14 18:12:08 -0700770 if(uTag != CBOR_TAG_INVALID64) {
771 QCBOREncode_AddTag(pMe, uTag);
772 }
Laurence Lundblade59289e52019-12-30 13:44:37 -0800773 QCBOREncode_OpenArray(pMe);
774 QCBOREncode_AddInt64(pMe, nExponent);
775 if(!UsefulBuf_IsNULLC(BigNumMantissa)) {
776 if(bBigNumIsNegative) {
777 QCBOREncode_AddNegativeBignum(pMe, BigNumMantissa);
778 } else {
779 QCBOREncode_AddPositiveBignum(pMe, BigNumMantissa);
780 }
781 } else {
782 QCBOREncode_AddInt64(pMe, nMantissa);
783 }
784 QCBOREncode_CloseArray(pMe);
785}
Laurence Lundbladedd6e76e2021-03-10 01:54:01 -0700786#endif /* QCBOR_DISABLE_EXP_AND_MANTISSA */
Laurence Lundblade59289e52019-12-30 13:44:37 -0800787
788
Laurence Lundblade067035b2018-11-28 17:35:25 -0800789/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800790 * Semi-public function. It is exposed to the user of the interface,
791 * but one of the inline wrappers will usually be called rather than
792 * this.
793 *
794 * See qcbor/qcbor_encode.h
Laurence Lundblade067035b2018-11-28 17:35:25 -0800795*/
796void QCBOREncode_OpenMapOrArray(QCBOREncodeContext *me, uint8_t uMajorType)
797{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800798 /* Add one item to the nesting level we are in for the new map or array */
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800799 IncrementMapOrArrayCount(me);
Laurence Lundbladed39cd392019-01-11 18:17:38 -0800800
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800801 /* The offset where the length of an array or map will get written
802 * is stored in a uint32_t, not a size_t to keep stack usage
803 * smaller. This checks to be sure there is no wrap around when
804 * recording the offset. Note that on 64-bit machines CBOR larger
805 * than 4GB can be encoded as long as no array/map offsets occur
806 * past the 4GB mark, but the public interface says that the
807 * maximum is 4GB to keep the discussion simpler.
808 */
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800809 size_t uEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
Laurence Lundbladed39cd392019-01-11 18:17:38 -0800810
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800811 /* QCBOR_MAX_ARRAY_OFFSET is slightly less than UINT32_MAX so this
812 * code can run on a 32-bit machine and tests can pass on a 32-bit
813 * machine. If it was exactly UINT32_MAX, then this code would not
814 * compile or run on a 32-bit machine and an #ifdef or some machine
815 * size detection would be needed reducing portability.
816 */
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800817 if(uEndPosition >= QCBOR_MAX_ARRAY_OFFSET) {
818 me->uError = QCBOR_ERR_BUFFER_TOO_LARGE;
819
820 } else {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800821 /* Increase nesting level because this is a map or array. Cast
822 * from size_t to uin32_t is safe because of check above.
823 */
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800824 me->uError = Nesting_Increase(&(me->nesting), uMajorType, (uint32_t)uEndPosition);
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800825 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700826}
827
Laurence Lundblade59289e52019-12-30 13:44:37 -0800828
Jan Jongboom4a93a662019-07-25 08:44:58 +0200829/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800830 * Semi-public function. It is exposed to the user of the interface,
831 * but one of the inline wrappers will usually be called rather than
832 * this.
833 *
834 * See qcbor/qcbor_encode.h
835 */
Jan Jongboom4a93a662019-07-25 08:44:58 +0200836void QCBOREncode_OpenMapOrArrayIndefiniteLength(QCBOREncodeContext *me, uint8_t uMajorType)
837{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800838 /* Insert the indefinite length marker (0x9f for arrays, 0xbf for maps) */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000839 AppendCBORHead(me, uMajorType, 0, 0);
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800840
841 /* Call the definite-length opener just to do the bookkeeping for
842 * nesting. It will record the position of the opening item in the
843 * encoded output but this is not used when closing this open.
844 */
Jan Jongboom4a93a662019-07-25 08:44:58 +0200845 QCBOREncode_OpenMapOrArray(me, uMajorType);
846}
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700847
Laurence Lundbladeee851742020-01-08 08:37:05 -0800848
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700849/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800850 * Public functions for closing arrays and maps. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700851 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000852void QCBOREncode_CloseMapOrArray(QCBOREncodeContext *me, uint8_t uMajorType)
Laurence Lundbladea954db92018-09-28 19:27:31 -0700853{
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000854 InsertCBORHead(me, uMajorType, Nesting_GetCount(&(me->nesting)));
855}
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800856
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800857
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000858/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800859 * Public functions for closing bstr wrapping. See qcbor/qcbor_encode.h
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000860 */
861void QCBOREncode_CloseBstrWrap2(QCBOREncodeContext *me, bool bIncludeCBORHead, UsefulBufC *pWrappedCBOR)
862{
863 const size_t uInsertPosition = Nesting_GetStartPos(&(me->nesting));
864 const size_t uEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800865
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800866 /* This subtraction can't go negative because the UsefulOutBuf
867 * always only grows and never shrinks. UsefulOutBut itself also
868 * has defenses such that it won't write where it should not even
869 * if given incorrect input lengths.
870 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000871 const size_t uBstrLen = uEndPosition - uInsertPosition;
872
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800873 /* Actually insert */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000874 InsertCBORHead(me, CBOR_MAJOR_TYPE_BYTE_STRING, uBstrLen);
875
876 if(pWrappedCBOR) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800877 /* Return pointer and length to the enclosed encoded CBOR. The
878 * intended use is for it to be hashed (e.g., SHA-256) in a COSE
879 * implementation. This must be used right away, as the pointer
880 * and length go invalid on any subsequent calls to this
881 * function because there might be calls to
882 * InsertEncodedTypeAndNumber() that slides data to the right.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000883 */
884 size_t uStartOfNew = uInsertPosition;
885 if(!bIncludeCBORHead) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800886 /* Skip over the CBOR head to just get the inserted bstr */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000887 const size_t uNewEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
888 uStartOfNew += uNewEndPosition - uEndPosition;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700889 }
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000890 const UsefulBufC PartialResult = UsefulOutBuf_OutUBuf(&(me->OutBuf));
891 *pWrappedCBOR = UsefulBuf_Tail(PartialResult, uStartOfNew);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700892 }
893}
894
Laurence Lundbladeee851742020-01-08 08:37:05 -0800895
Jan Jongboom4a93a662019-07-25 08:44:58 +0200896/*
Laurence Lundblade8d3b8552021-06-10 11:11:54 -0700897 * Public function for canceling a bstr wrap. See qcbor/qcbor_encode.h
898 */
899void QCBOREncode_CancelBstrWrap(QCBOREncodeContext *pMe)
900{
901#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
902 if(pMe->uError == QCBOR_SUCCESS) {
903 if(!Nesting_IsInNest(&(pMe->nesting))) {
904 pMe->uError = QCBOR_ERR_TOO_MANY_CLOSES;
905 return;
906 } else if(Nesting_GetMajorType(&(pMe->nesting)) != CBOR_MAJOR_TYPE_BYTE_STRING) {
907 pMe->uError = QCBOR_ERR_CLOSE_MISMATCH;
908 return;
909 }
910 const size_t uCurrent = UsefulOutBuf_GetEndPosition(&(pMe->OutBuf));
911 if(pMe->nesting.pCurrentNesting->uStart != uCurrent) {
912 pMe->uError = QCBOR_ERR_CANNOT_CANCEL;
913 return;
914 }
915 }
916 /* QCBOREncode_CancelBstrWrap() can't correctly undo
917 * QCBOREncode_BstrWrapInMap() or QCBOREncode_BstrWrapInMapN(). It
918 * can't undo the labels they add. It also doesn't catch the error
919 * of using it this way. QCBOREncode_CancelBstrWrap() is used
920 * infrequently and the the result is incorrect CBOR, not a
921 * security hole, so no extra code or state is added to handle this
922 * condition.
923 */
924#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
925
926 Nesting_Decrease(&(pMe->nesting));
927 Nesting_Decrement(&(pMe->nesting));
928}
929
930
931/*
932 * Public function for closing arrays and maps. See qcbor/qcbor_encode.h
Jan Jongboom4a93a662019-07-25 08:44:58 +0200933 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000934void QCBOREncode_CloseMapOrArrayIndefiniteLength(QCBOREncodeContext *me, uint8_t uMajorType)
Jan Jongboom4a93a662019-07-25 08:44:58 +0200935{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800936#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Jan Jongboom4a93a662019-07-25 08:44:58 +0200937 if(me->uError == QCBOR_SUCCESS) {
938 if(!Nesting_IsInNest(&(me->nesting))) {
939 me->uError = QCBOR_ERR_TOO_MANY_CLOSES;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800940 return;
Jan Jongboom4a93a662019-07-25 08:44:58 +0200941 } else if(Nesting_GetMajorType(&(me->nesting)) != uMajorType) {
942 me->uError = QCBOR_ERR_CLOSE_MISMATCH;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800943 return;
Jan Jongboom4a93a662019-07-25 08:44:58 +0200944 }
945 }
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800946#else /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800947 (void) uMajorType;
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800948#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800949
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800950 /* Append the break marker (0xff for both arrays and maps) */
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800951 AppendCBORHead(me, CBOR_MAJOR_NONE_TYPE_SIMPLE_BREAK, CBOR_SIMPLE_BREAK, 0);
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800952 Nesting_Decrease(&(me->nesting));
Jan Jongboom4a93a662019-07-25 08:44:58 +0200953}
954
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700955
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700956/*
Laurence Lundblade8d3b8552021-06-10 11:11:54 -0700957 * Public function to finish and get the encoded result. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700958 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700959QCBORError QCBOREncode_Finish(QCBOREncodeContext *me, UsefulBufC *pEncodedCBOR)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700960{
Laurence Lundbladef607a2a2019-07-05 21:25:25 -0700961 QCBORError uReturn = QCBOREncode_GetErrorState(me);
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800962
Laurence Lundblade067035b2018-11-28 17:35:25 -0800963 if(uReturn != QCBOR_SUCCESS) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700964 goto Done;
Laurence Lundblade067035b2018-11-28 17:35:25 -0800965 }
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800966
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800967#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800968 if(Nesting_IsInNest(&(me->nesting))) {
Laurence Lundblade067035b2018-11-28 17:35:25 -0800969 uReturn = QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700970 goto Done;
971 }
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800972#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800973
Laurence Lundbladeda3f0822018-09-18 19:49:02 -0700974 *pEncodedCBOR = UsefulOutBuf_OutUBuf(&(me->OutBuf));
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800975
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700976Done:
Laurence Lundblade067035b2018-11-28 17:35:25 -0800977 return uReturn;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700978}
979
Laurence Lundblade0595e932018-11-02 22:22:47 +0700980
Laurence Lundblade067035b2018-11-28 17:35:25 -0800981/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800982 * Public functions to get size of the encoded result. See qcbor/qcbor_encode.h
Laurence Lundblade067035b2018-11-28 17:35:25 -0800983 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700984QCBORError QCBOREncode_FinishGetSize(QCBOREncodeContext *me, size_t *puEncodedLen)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700985{
Laurence Lundbladeda3f0822018-09-18 19:49:02 -0700986 UsefulBufC Enc;
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800987
Laurence Lundblade30816f22018-11-10 13:40:22 +0700988 QCBORError nReturn = QCBOREncode_Finish(me, &Enc);
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800989
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700990 if(nReturn == QCBOR_SUCCESS) {
Laurence Lundbladeda3f0822018-09-18 19:49:02 -0700991 *puEncodedLen = Enc.len;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700992 }
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800993
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700994 return nReturn;
995}