Initial drop from Qualcomm / CAF
diff --git a/src/UsefulBuf.c b/src/UsefulBuf.c
new file mode 100644
index 0000000..7fc5e12
--- /dev/null
+++ b/src/UsefulBuf.c
@@ -0,0 +1,345 @@
+/*==============================================================================
+Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of The Linux Foundation nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+==============================================================================*/
+
+/*===================================================================================
+ FILE: UsefulBuf.c
+
+ DESCRIPTION: General purpose input and output buffers
+
+ EDIT HISTORY FOR FILE:
+
+ This section contains comments describing changes made to the module.
+ Notice that changes are listed in reverse chronological order.
+
+ when who what, where, why
+ -------- ---- ---------------------------------------------------
+ 09/07/17 llundbla Fix critical bug in UsefulBuf_Find() -- a read off
+ the end of memory when the bytes to find is longer
+ than the bytes to search.
+ 06/27/17 llundbla Fix UsefulBuf_Compare() bug. Only affected comparison
+ for < or > for unequal length buffers. Added
+ UsefulBuf_Set() function.
+ 05/30/17 llundbla Functions for NULL UsefulBufs and const / unconst
+ 11/13/16 llundbla Initial Version.
+
+ =====================================================================================*/
+
+#include <string.h>
+#include "UsefulBuf.h"
+#include <stringl.h>
+
+#define USEFUL_OUT_BUF_MAGIC (0x0B0F) // used to catch use of uninitialized or corrupted UOBs
+
+/*
+ Public function -- see UsefulBuf.h
+ */
+int UsefulBuf_Copy(UsefulBuf *pDest, const UsefulBufC Src)
+{
+ if(Src.len > pDest->len)
+ return 1;
+
+ memscpy(pDest->ptr, pDest->len, Src.ptr, Src.len);
+
+ pDest->len = Src.len;
+
+ return 0;
+}
+
+/*
+ Public function -- see UsefulBuf.h
+ */
+int UsefulBuf_Compare(const UsefulBufC UB1, const UsefulBufC UB2)
+{
+ // use the comparisons rather than subtracting lengths to
+ // return an int instead of a size_t
+ if(UB1.len < UB2.len) {
+ return -1;
+ } else if (UB1.len > UB2.len) {
+ return 1;
+ } // else UB1.len == UB2.len
+
+ return memcmp(UB1.ptr, UB2.ptr, UB1.len);
+}
+
+
+/*
+ Public function -- see UsefulBuf.h
+ */
+void UsefulBuf_Set(UsefulBuf *pDest, uint8_t value)
+{
+ memset(pDest->ptr, value, pDest->len);
+}
+
+
+/*
+ returns SIZE_MAX when there is no match
+ */
+size_t UsefulBuf_FindBytes(UsefulBufC BytesToSearch, UsefulBufC BytesToFind)
+{
+ if(BytesToSearch.len < BytesToFind.len) {
+ return SIZE_MAX;
+ }
+
+ for(size_t uPos = 0; uPos <= BytesToSearch.len - BytesToFind.len; uPos++) {
+ if(!UsefulBuf_Compare((UsefulBufC){((uint8_t *)BytesToSearch.ptr) + uPos, BytesToFind.len}, BytesToFind)) {
+ return uPos;
+ }
+ }
+
+ return SIZE_MAX;
+}
+
+
+/*
+ Public function -- see UsefulBuf.h
+
+ The core of UsefulOutBuf -- put some bytes in the buffer without writing off the end of it.
+
+ THIS FUNCTION DOES POINTER MATH
+ */
+void UsefulOutBuf_Init(UsefulOutBuf *me, void *pStorage, size_t uStorageSize)
+{
+ me->magic = USEFUL_OUT_BUF_MAGIC;
+ UsefulOutBuf_Reset(me);
+
+ me->UB.ptr = pStorage;
+ me->size = uStorageSize;
+
+ // The following check fails on ThreadX
+#if 0
+ // Sanity check on the pointer and size to be sure we are not
+ // passed a buffer that goes off the end of the address space.
+ // Given this test, we know that all unsigned lengths less than
+ // me->size are valid and won't wrap in any pointer additions
+ // based off of pStorage in the rest of this code.
+ const uintptr_t ptrM = UINTPTR_MAX - uStorageSize;
+ if(pStorage && (uintptr_t)pStorage > ptrM) // Check #0
+ me->err = 1;
+#endif
+}
+
+
+/*
+ Public function -- see UsefulBuf.h
+
+ The core of UsefulOutBuf -- put some bytes in the buffer without writing off the end of it.
+
+ Code Reviewers: THIS FUNCTION DOES POINTER MATH
+
+ This function inserts the source buffer, NewData, into the destination buffer, me->UB.ptr.
+
+ Destination is represented as:
+ me->UB.ptr -- start of the buffer
+ me->UB.len -- length of valid data in the buffer
+ me->size -- size of the buffer UB.ptr
+
+ Source is data:
+ NewData.ptr -- start of source buffer
+ NewData.len -- length of source buffer
+
+ Insertion point:
+ uInsertionPos.
+
+ Steps:
+
+ 0. Corruption checks on UsefulOutBuf
+
+ 1. Figure out if the new data will fit or not
+
+ 2. Is insertion position in the range of valid data?
+
+ 3. If insertion point is not at the end, slide data to the right of the insertion point to the right
+
+ 4. Put the new data in at the insertion position.
+
+ */
+void UsefulOutBuf_InsertUsefulBuf(UsefulOutBuf *me, UsefulBufC NewData, size_t uInsertionPos)
+{
+ if(me->err) {
+ // Already in error state.
+ return;
+ }
+
+ /* 0. Sanity check the UsefulOutBuf structure */
+ // A "counter measure". If magic number is not the right number it
+ // probably means me was not initialized or it was corrupted. Attackers
+ // can defeat this, but it is a hurdle and does good with very
+ // little code.
+ if(me->magic != USEFUL_OUT_BUF_MAGIC) {
+ me->err = 1;
+ return; // Magic number is wrong due to uninitalization or corrption
+ }
+
+ // Make sure valid data is less than buffer size. This would only occur
+ // if there was corruption of me, but it is also part of the checks to
+ // be sure there is no pointer arithmatic under/overflow.
+ if(me->UB.len > me->size) { // Check #1
+ me->err = 1;
+ return; // Offset of valid data is off the end of the UsefulOutBuf due to uninitialization or corruption
+ }
+
+ /* 1. Will it fit? */
+ // WillItFit() is the same as: NewData.len <= (me->size - me->UB.len)
+ // Check #1 makes sure subtraction in RoomLeft will not wrap around
+ if(! UsefulOutBuf_WillItFit(me, NewData.len)) { // Check #2
+ // The new data will not fit into the the buffer.
+ me->err = 1;
+ return;
+ }
+
+ /* 2. Check the Insertion Position */
+ // This, with Check #1, also confirms that uInsertionPos <= me->size
+ if(uInsertionPos > me->UB.len) { // Check #3
+ // Off the end of the valid data in the buffer.
+ me->err = 1;
+ return;
+ }
+
+ /* 3. Slide existing data to the right */
+ uint8_t *pSourceOfMove = ((uint8_t *)me->UB.ptr) + uInsertionPos; // PtrMath #1
+ size_t uNumBytesToMove = me->UB.len - uInsertionPos; // PtrMath #2
+ uint8_t *pDestinationOfMove = pSourceOfMove + NewData.len; // PtrMath #3
+ size_t uRoomInDestination = me->size - (uInsertionPos + NewData.len); // PtrMath #4
+
+ if(uNumBytesToMove && me->UB.ptr) {
+ memsmove(pDestinationOfMove, uRoomInDestination, pSourceOfMove, uNumBytesToMove);
+ }
+
+ /* 4. Put the new data in */
+ uint8_t *pInsertionPoint = ((uint8_t *)me->UB.ptr) + uInsertionPos; // PtrMath #5
+ uRoomInDestination = me->size - uInsertionPos; // PtrMath #6
+ if(me->UB.ptr) {
+ memsmove(pInsertionPoint, uRoomInDestination, NewData.ptr, NewData.len);
+ }
+ me->UB.len += NewData.len ;
+}
+
+
+/*
+ Rationale that describes why the above pointer math is safe
+
+ PtrMath #1 will never wrap around over because
+ Check #0 in UsefulOutBuf_Init makes sure me-UB.ptr + me->size doesn't wrap
+ Check #1 makes sure me->UB.len is less than me->size
+ Check #3 makes sure uInsertionPos is less than me->UB.len
+
+ PtrMath #2 will never wrap around under because
+ Check #3 makes sure uInsertionPos is less than me->UB.len
+
+ PtrMath #3 will never wrap around over because todo
+ PtrMath #1 is checked resulting in pStartOfDataToMove being between me->UB.ptr and a maximum valid ptr
+
+ PtrMath #4 will never wrap under because
+ Check #3 makes sure uInsertionPos is less than me->UB.len
+ Check #3 allows Check #2 to be refactored as NewData.Len > (me->size - uInsertionPos)
+ This algebraically rearranges to me->size > uInsertionPos + NewData.len
+
+ PtrMath #5 is exactly the same as PtrMath #1
+
+ PtrMath #6 will never wrap under because
+ Check #1 makes sure me->UB.len is less than me->size
+ Check #3 makes sure uInsertionPos is less than me->UB.len
+ */
+
+
+/*
+ Public function -- see UsefulBuf.h
+
+ Returns the resulting valid data in a UsefulBuf
+
+ */
+int UsefulOutBuf_OutUBuf(UsefulOutBuf *me, UsefulBuf *O)
+{
+ if(me->err) {
+ return me->err;
+ }
+
+ if(me->magic != USEFUL_OUT_BUF_MAGIC) {
+ me->err = 1;
+ return 1;
+ }
+
+ *O = me->UB;
+ return 0;
+}
+
+
+/*
+ Public function -- see UsefulBuf.h
+
+ Copy out the data accumulated in the output buffer.
+
+ */
+int UsefulOutBuf_CopyOut(UsefulOutBuf *me, void *pBuf, size_t uBufSize, size_t *puCopied)
+{
+ UsefulBuf B;
+ if(UsefulOutBuf_OutUBuf(me, &B)) {
+ return 1; // was in error state or was corrupted
+ }
+
+ if(B.len > uBufSize) {
+ return 1; // buffer was too small
+ }
+
+ memsmove(pBuf, uBufSize, B.ptr, B.len);
+
+ *puCopied = me->UB.len;
+
+ return 0;
+}
+
+
+
+
+/*
+ Public function -- see UsefulBuf.h
+
+ The core of UsefulInputBuf -- consume some bytes without going off the end of the buffer.
+
+ Code Reviewers: THIS FUNCTION DOES POINTER MATH
+ */
+const void * UsefulInputBuf_GetBytes(UsefulInputBuf *me, size_t uAmount)
+{
+ // Already in error state. Do nothing.
+ if(me->err) {
+ return NULL;
+ }
+
+ if(!UsefulInputBuf_BytesAvailable(me, uAmount)) {
+ // The number of bytes asked for at current position are more than available
+ me->err = 1;
+ return NULL;
+ }
+
+ // This is going to succeed
+ const void * const result = ((uint8_t *)me->UB.ptr) + me->cursor;
+ me->cursor += uAmount; // this will not overflow because of check using UsefulInputBuf_BytesAvailable()
+ return result;
+}
+
diff --git a/src/qcbor_decode.c b/src/qcbor_decode.c
new file mode 100644
index 0000000..b412205
--- /dev/null
+++ b/src/qcbor_decode.c
@@ -0,0 +1,708 @@
+/*==============================================================================
+Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of The Linux Foundation nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+==============================================================================*/
+
+/*===================================================================================
+ FILE: qcbor_decode.c
+
+ DESCRIPTION: This file contains the implementation of QCBOR.
+
+ EDIT HISTORY FOR FILE:
+
+ This section contains comments describing changes made to the module.
+ Notice that changes are listed in reverse chronological order.
+
+ when who what, where, why
+ -------- ---- ---------------------------------------------------
+ 02/04/17 llundbla Work on CPUs that don's require pointer alignment
+ by making use of changes in UsefulBuf
+ 03/01/17 llundbla More data types; decoding improvements and fixes
+ 11/13/16 llundbla Integrate most TZ changes back into github version.
+ 09/30/16 gkanike Porting to TZ.
+ 03/15/16 llundbla Initial Version.
+
+ =====================================================================================*/
+
+#include "qcbor.h"
+
+#include <stdint.h>
+
+#ifdef QSEE
+#include "stringl.h"
+#endif
+
+
+/*
+ Collection of functions to track the map and array nesting for decoding
+ */
+
+inline static int IsMapOrArray(uint8_t uDataType)
+{
+ return uDataType == QCBOR_TYPE_MAP || uDataType == QCBOR_TYPE_ARRAY;
+}
+
+inline static int DecodeNesting_IsNested(const QCBORDecodeNesting *pNesting)
+{
+ return pNesting->pCurrent != &(pNesting->pMapsAndArrays[0]);
+}
+
+inline static int DecodeNesting_TypeIsMap(const QCBORDecodeNesting *pNesting)
+{
+ if(!DecodeNesting_IsNested(pNesting))
+ return 0;
+
+ return CBOR_MAJOR_TYPE_MAP == pNesting->pCurrent->uMajorType;
+}
+
+inline static void DecodeNesting_Decrement(QCBORDecodeNesting *pNesting, uint8_t uDataType)
+{
+ if(!DecodeNesting_IsNested(pNesting)) {
+ return; // at top level where there is no tracking
+ }
+
+ // Decrement
+ pNesting->pCurrent->uCount--;
+
+ // Pop up nesting levels if the counts at the levels is zero
+ while(0 == pNesting->pCurrent->uCount && DecodeNesting_IsNested(pNesting)) {
+ pNesting->pCurrent--;
+ }
+}
+
+inline static int DecodeNesting_Descend(QCBORDecodeNesting *pNesting, uint8_t uMajorType, int uCount)
+{
+ int nReturn = QCBOR_SUCCESS;
+
+ if(uCount > QCBOR_MAX_ITEMS_IN_ARRAY) {
+ nReturn = QCBOR_ERR_ARRAY_TOO_LONG;
+ goto Done;
+ }
+
+ if(pNesting->pCurrent >= &(pNesting->pMapsAndArrays[QCBOR_MAX_ARRAY_NESTING])) {
+ nReturn = QCBOR_ERR_ARRAY_NESTING_TOO_DEEP;
+ goto Done;
+ }
+
+ pNesting->pCurrent++;
+
+ pNesting->pCurrent->uMajorType = uMajorType;
+ pNesting->pCurrent->uCount = uCount;
+
+Done:
+ return nReturn;;
+}
+
+inline static uint8_t DecodeNesting_GetLevel(QCBORDecodeNesting *pNesting)
+{
+ return pNesting->pCurrent - &(pNesting->pMapsAndArrays[0]);
+}
+
+inline static void DecodeNesting_Init(QCBORDecodeNesting *pNesting)
+{
+ pNesting->pCurrent = &(pNesting->pMapsAndArrays[0]);
+}
+
+
+
+
+/*
+ Public function, see header file
+ */
+void QCBORDecode_Init(QCBORDecodeContext *me, UsefulBufC EncodedCBOR, int8_t nDecodeMode)
+{
+ memset(me, 0, sizeof(QCBORDecodeContext));
+ UsefulInputBuf_Init(&(me->InBuf), EncodedCBOR);
+ // Don't bother with error check on decode mode. If a bad value is passed it will just act as
+ // if the default normal mode of 0 was set.
+ me->uDecodeMode = nDecodeMode;
+ DecodeNesting_Init(&(me->nesting));
+}
+
+
+/*
+ This decodes the fundamental part of a CBOR data item, the type and number
+
+ This is the Counterpart to InsertEncodedTypeAndNumber().
+
+ This does the network->host byte order conversion. The conversion here
+ also results in the conversion for floats in addition to that for
+ lengths, tags and integer values.
+
+ */
+inline static int DecodeTypeAndNumber(UsefulInputBuf *pUInBuf, int *pnMajorType, uint64_t *puNumber, uint8_t *puAdditionalInfo)
+{
+ int nReturn;
+
+ // Get the initial byte that every CBOR data item has
+ const uint8_t InitialByte = UsefulInputBuf_GetByte(pUInBuf);
+
+ // Break down the initial byte
+ const uint8_t uTmpMajorType = InitialByte >> 5;
+ const uint8_t uAdditionalInfo = InitialByte & 0x1f;
+
+ // Get the integer that follows the major type. Do not know if this is a length, value, float or tag at this point
+ // Also convert from network byte order. Call ntohxx on simple variables in case they are macros that
+ // reference their argument multiple times.
+ uint64_t uTmpValue;
+ switch(uAdditionalInfo) {
+
+ case LEN_IS_ONE_BYTE:
+ uTmpValue = UsefulInputBuf_GetByte(pUInBuf);
+ break;
+
+ case LEN_IS_TWO_BYTES:
+ uTmpValue = UsefulInputBuf_GetUint16(pUInBuf);
+ break;
+
+ case LEN_IS_FOUR_BYTES:
+ uTmpValue = UsefulInputBuf_GetUint32(pUInBuf);
+ break;
+
+ case LEN_IS_EIGHT_BYTES:
+ uTmpValue = UsefulInputBuf_GetUint64(pUInBuf);
+ break;
+
+ case ADDINFO_RESERVED1: // reserved by CBOR spec
+ case ADDINFO_RESERVED2: // reserved by CBOR spec
+ case ADDINFO_RESERVED3: // reserved by CBOR spec
+ case LEN_IS_INDEFINITE: // indefinite types not supported (yet)
+ nReturn = QCBOR_ERR_UNSUPPORTED;
+ goto Done;
+
+ default:
+ uTmpValue = uAdditionalInfo;
+ break;
+ }
+
+ // If any of the UsefulInputBuf_Get calls fail we will get here with uTmpValue as 0.
+ // There is no harm in this. This following check takes care of catching all of
+ // these errors.
+
+ if(UsefulInputBuf_GetError(pUInBuf)) {
+ nReturn = QCBOR_ERR_HIT_END;
+ goto Done;
+ }
+
+ // All successful if we got here.
+ nReturn = QCBOR_SUCCESS;
+ *pnMajorType = uTmpMajorType;
+ *puNumber = uTmpValue;
+ *puAdditionalInfo = uAdditionalInfo;
+
+Done:
+ return nReturn;
+}
+
+
+/*
+ CBOR doesn't explicitly specify two's compliment for integers but all CPUs
+ use it these days and the test vectors in the RFC are so. All integers in the CBOR
+ structure are positive and the major type indicates positive or negative.
+ CBOR can express positive integers up to 2^x - 1 where x is the number of bits
+ and negative integers down to 2^x. Note that negative numbers can be one
+ more away from zero than positive.
+ Stdint, as far as I can tell, uses two's compliment to represent
+ negative integers.
+
+ See http://www.unix.org/whitepapers/64bit.html for reasons int isn't
+ used here in any way including in the interface
+ */
+inline static int DecodeInteger(int nMajorType, uint64_t uNumber, QCBORItem *pDecodedItem)
+{
+ int nReturn = QCBOR_SUCCESS;
+
+ if(nMajorType == CBOR_MAJOR_TYPE_POSITIVE_INT) {
+ if (uNumber <= INT64_MAX) {
+ pDecodedItem->val.int64 = (int64_t)uNumber;
+ pDecodedItem->uDataType = QCBOR_TYPE_INT64;
+
+ } else {
+ pDecodedItem->val.uint64 = uNumber;
+ pDecodedItem->uDataType = QCBOR_TYPE_UINT64;
+
+ }
+ } else {
+ if(uNumber <= INT64_MAX) {
+ pDecodedItem->val.int64 = -uNumber-1;
+ pDecodedItem->uDataType = QCBOR_TYPE_INT64;
+
+ } else {
+ // C can't represent a negative integer in this range
+ // so it is an error. todo -- test this condition
+ nReturn = QCBOR_ERR_INT_OVERFLOW;
+ }
+ }
+
+ return nReturn;
+}
+
+// Make sure #define value line up as DecodeSimple counts on this.
+#if QCBOR_TYPE_FALSE != CBOR_SIMPLEV_FALSE
+#error QCBOR_TYPE_FALSE macro value wrong
+#endif
+
+#if QCBOR_TYPE_TRUE != CBOR_SIMPLEV_TRUE
+#error QCBOR_TYPE_TRUE macro value wrong
+#endif
+
+#if QCBOR_TYPE_NULL != CBOR_SIMPLEV_NULL
+#error QCBOR_TYPE_NULL macro value wrong
+#endif
+
+#if QCBOR_TYPE_UNDEF != CBOR_SIMPLEV_UNDEF
+#error QCBOR_TYPE_UNDEF macro value wrong
+#endif
+
+#if QCBOR_TYPE_DOUBLE != DOUBLE_PREC_FLOAT
+#error QCBOR_TYPE_DOUBLE macro value wrong
+#endif
+
+#if QCBOR_TYPE_FLOAT != SINGLE_PREC_FLOAT
+#error QCBOR_TYPE_FLOAT macro value wrong
+#endif
+
+/*
+ Decode true, false, floats, break...
+ */
+
+inline static int DecodeSimple(uint8_t uAdditionalInfo, uint64_t uNumber, QCBORItem *pDecodedItem)
+{
+ int nReturn = QCBOR_SUCCESS;
+
+ // uAdditionalInfo is 5 bits from the initial byte
+ // compile time checks above make sure uAdditionalInfo values line up with uDataType values
+ pDecodedItem->uDataType = uAdditionalInfo;
+
+ switch(uAdditionalInfo) {
+ case ADDINFO_RESERVED1: // 28
+ case ADDINFO_RESERVED2: // 29
+ case ADDINFO_RESERVED3: // 30
+ case CBOR_SIMPLE_BREAK: // 31
+ nReturn = QCBOR_ERR_UNSUPPORTED;
+ break;
+
+ case CBOR_SIMPLEV_FALSE: // 20
+ case CBOR_SIMPLEV_TRUE: // 21
+ case CBOR_SIMPLEV_NULL: // 22
+ case CBOR_SIMPLEV_UNDEF: // 23
+ break; // nothing to do
+
+ case CBOR_SIMPLEV_ONEBYTE: // 24
+ if(uNumber <= CBOR_SIMPLE_BREAK) {
+ // This takes out f8 00 ... f8 1f which should be encoded as e0 … f7
+ nReturn = QCBOR_ERR_INVALID_CBOR;
+ goto Done;
+ }
+ // fall through intentionally
+
+ default: // 0-19
+ pDecodedItem->uDataType = QCBOR_TYPE_UKNOWN_SIMPLE;
+ // DecodeTypeAndNumber will make uNumber equal to uAdditionalInfo when uAdditionalInfo is < 24
+ // This cast is safe because the 2, 4 and 8 byte lengths of uNumber are in the double/float cases above
+ pDecodedItem->val.uSimple = (uint8_t)uNumber;
+ break;
+ }
+
+Done:
+ return nReturn;
+}
+
+
+
+/*
+ Decode text and byte strings
+ */
+inline static int DecodeBytes(int nMajorType, uint64_t uNumber, UsefulInputBuf *pUInBuf, QCBORItem *pDecodedItem)
+{
+ const void *pBytes = UsefulInputBuf_GetBytes(pUInBuf, uNumber);
+
+ int nReturn = QCBOR_ERR_HIT_END;
+
+ if(pBytes != NULL) {
+ pDecodedItem->val.string.ptr = pBytes;
+ pDecodedItem->val.string.len = uNumber;
+ pDecodedItem->uDataType = (nMajorType == CBOR_MAJOR_TYPE_BYTE_STRING) ? QCBOR_TYPE_BYTE_STRING : QCBOR_TYPE_TEXT_STRING;
+ nReturn = QCBOR_SUCCESS;
+ }
+
+ return nReturn;
+}
+
+
+/*
+ Mostly just assign the right data type for the date string.
+ */
+inline static int DecodeDateString(QCBORItem Item, QCBORItem *pDecodedItem)
+{
+ if(Item.uDataType != QCBOR_TYPE_TEXT_STRING) {
+ return QCBOR_ERR_BAD_OPT_TAG;
+ }
+ pDecodedItem->val.dateString = Item.val.string;
+ pDecodedItem->uDataType = QCBOR_TYPE_DATE_STRING;
+ pDecodedItem->uTagBits = Item.uTagBits;
+ pDecodedItem->uTag = Item.uTag;
+ return QCBOR_SUCCESS;
+}
+
+
+/*
+ Mostly just assign the right data type for the bignum.
+ */
+inline static int DecodeBigNum(QCBORItem Item, QCBORItem *pDecodedItem, uint64_t uTagFlags)
+{
+ if(Item.uDataType != QCBOR_TYPE_BYTE_STRING) {
+ return QCBOR_ERR_BAD_OPT_TAG;
+ }
+ pDecodedItem->val.bigNum = Item.val.string;
+ pDecodedItem->uDataType = uTagFlags & QCBOR_TAGFLAG_POS_BIGNUM ? QCBOR_TYPE_POSBIGNUM : QCBOR_TYPE_NEGBIGNUM;
+ pDecodedItem->uTagBits = Item.uTagBits;
+ pDecodedItem->uTag = Item.uTag;
+ return QCBOR_SUCCESS;
+}
+
+
+/*
+ The epoch formatted date. Turns lots of different forms of encoding date into uniform one
+ */
+static int DecodeDateEpoch(QCBORItem Item, QCBORItem *pDecodedItem)
+{
+ int nReturn = QCBOR_SUCCESS;
+
+ pDecodedItem->uTagBits = Item.uTagBits;
+ pDecodedItem->uTag = Item.uTag;
+ pDecodedItem->uDataType = QCBOR_TYPE_DATE_EPOCH;
+ pDecodedItem->val.epochDate.fSecondsFraction = 0;
+
+ switch (Item.uDataType) {
+
+ case QCBOR_TYPE_INT64:
+ pDecodedItem->val.epochDate.nSeconds = Item.val.int64;
+ break;
+
+ case QCBOR_TYPE_UINT64:
+ if(Item.val.uint64 > INT64_MAX) {
+ nReturn = QCBOR_ERR_DATE_OVERFLOW;
+ goto Done;
+ }
+ pDecodedItem->val.epochDate.nSeconds = Item.val.uint64;
+ break;
+
+ default:
+ nReturn = QCBOR_ERR_BAD_OPT_TAG;
+ }
+
+Done:
+ return nReturn;
+}
+
+
+/*
+ Decode the optional tagging that preceeds the real data value. There could be lots of them.
+ */
+static int GetAnItem(UsefulInputBuf *pUInBuf, QCBORItem *pDecodedItem, int bCalledFromDecodeOptional);
+
+/*
+ Returns an error if there was something wrong with the optional item or it couldn't
+ be handled.
+ */
+static int DecodeOptional(UsefulInputBuf *pUInBuf, uint64_t uInputTag, QCBORItem *pDecodedItem)
+{
+ int nReturn = QCBOR_SUCCESS;
+
+ uint64_t uTagFlags = 0; // accumulate the tags in the form of flags
+ uint64_t uTagToProcess = uInputTag; // First process tag passed in
+
+ QCBORItem Item;
+
+ do {
+ if(uTagToProcess < 63) { // 63 is the number of bits in a uint64 - 1
+ uTagFlags |= 0x01LL << uTagToProcess;
+ } else if(uTagToProcess == CBOR_TAG_CBOR_MAGIC) {
+ uTagFlags |= QCBOR_TAGFLAG_CBOR_MAGIC;
+ }
+ /* This code ignores the all but the first tag of value
+ greater than 63. Ignoring tags that are not understoof
+ is allowed by the standard. Multiple tags are
+ presumably rare. */
+
+ nReturn = GetAnItem(pUInBuf, &Item, 1);
+ if(nReturn) {
+ // Bail out of the whole item fetch on any sort of error here
+ goto Done;
+ }
+
+ if(Item.uDataType != QCBOR_TYPE_OPTTAG) {
+ break;
+ }
+
+ uTagToProcess = Item.uTag;
+ } while (1);
+
+
+ /*
+ CBOR allows multiple tags on a data item. It also defines
+ a number of standard tag values, most of which are
+ less than 64. This code can deal with multiple tag
+ values that are less than 64 and the last tag of multiple
+ if the value is more than 64. Or said another way
+ if there is one tag with a value >64 this code works.
+
+ The assumption is that multiple tag values > 64 are rare.
+
+ At this point in this code. uTagFlags has all the flags
+ < 64 and uTagToProcess has the last tag.
+
+ Does this deal with multiple tags on an item we process?
+ */
+
+ Item.uTagBits = uTagFlags;
+ Item.uTag = uTagToProcess;
+
+ switch(uTagFlags & (QCBOR_TAGFLAG_DATE_STRING | QCBOR_TAGFLAG_DATE_EPOCH | QCBOR_TAGFLAG_POS_BIGNUM |QCBOR_TAGFLAG_NEG_BIGNUM)) {
+ case 0:
+ // No tags we know about. Pass them up
+ *pDecodedItem = Item;
+ break;
+
+ case QCBOR_TAGFLAG_DATE_STRING:
+ nReturn = DecodeDateString(Item, pDecodedItem);
+ break;
+
+ case QCBOR_TAGFLAG_DATE_EPOCH:
+ nReturn = DecodeDateEpoch(Item, pDecodedItem);
+ break;
+
+ case QCBOR_TAGFLAG_POS_BIGNUM:
+ case QCBOR_TAGFLAG_NEG_BIGNUM:
+ nReturn = DecodeBigNum(Item, pDecodedItem, uTagFlags);
+ break;
+
+ default:
+ // Encountering some mixed up CBOR like something that
+ // is tagged as both a string and integer date.
+ nReturn = QCBOR_ERR_BAD_OPT_TAG ;
+ }
+
+Done:
+ return nReturn;
+}
+
+
+
+// Make sure the constants align as this is assumed by the GetAnItem() implementation
+#if QCBOR_TYPE_ARRAY != CBOR_MAJOR_TYPE_ARRAY
+#error QCBOR_TYPE_ARRAY value not lined up with major type
+#endif
+#if QCBOR_TYPE_MAP != CBOR_MAJOR_TYPE_MAP
+#error QCBOR_TYPE_MAP value not lined up with major type
+#endif
+
+/*
+ This gets a single data item and decodes it including preceding optional tagging. This does not
+ deal with arrays and maps and nesting except to decode the data item introducing them. Arrays and
+ maps are handled at the next level up in GetNext().
+
+ Errors detected here include: an array that is too long to decode, hit end of buffer unexpectedly,
+ a few forms of invalid encoded CBOR
+ */
+
+static int GetAnItem(UsefulInputBuf *pUInBuf, QCBORItem *pDecodedItem, int bCalledFromDecodeOptional)
+{
+ int nReturn;
+
+ // Get the major type and the number. Number could be length of more bytes or the value depending on the major type
+ // nAdditionalInfo is an encoding of the length of the uNumber and is needed to decode floats and doubles
+ int uMajorType;
+ uint64_t uNumber;
+ uint8_t uAdditionalInfo;
+
+ nReturn = DecodeTypeAndNumber(pUInBuf, &uMajorType, &uNumber, &uAdditionalInfo);
+
+ // Error out here if we got into trouble on the type and number.
+ // The code after this will not work if the type and number is not good.
+ if(nReturn)
+ goto Done;
+
+ pDecodedItem->uTagBits = 0;
+ pDecodedItem->uTag = 0;
+
+ // At this point the major type and the value are valid. We've got the type and the number that
+ // starts every CBOR data item.
+ switch (uMajorType) {
+ case CBOR_MAJOR_TYPE_POSITIVE_INT: // Major type 0
+ case CBOR_MAJOR_TYPE_NEGATIVE_INT: // Major type 1
+ nReturn = DecodeInteger(uMajorType, uNumber, pDecodedItem);
+ break;
+
+ case CBOR_MAJOR_TYPE_BYTE_STRING: // Major type 2
+ case CBOR_MAJOR_TYPE_TEXT_STRING: // Major type 3
+ nReturn = DecodeBytes(uMajorType, uNumber, pUInBuf, pDecodedItem);
+ break;
+
+ case CBOR_MAJOR_TYPE_ARRAY: // Major type 4
+ case CBOR_MAJOR_TYPE_MAP: // Major type 5
+ // Record the number of items in the array or map
+ if(uNumber > QCBOR_MAX_ITEMS_IN_ARRAY) {
+ nReturn = QCBOR_ERR_ARRAY_TOO_LONG;
+ goto Done;
+ }
+ pDecodedItem->val.uCount = uNumber; // type conversion OK because of check above
+ pDecodedItem->uDataType = uMajorType; // C preproc #if above makes sure constants align
+ break;
+
+ case CBOR_MAJOR_TYPE_OPTIONAL: // Major type 6, optional prepended tags
+ pDecodedItem->uTag = uNumber;
+ pDecodedItem->uDataType = QCBOR_TYPE_OPTTAG;
+ if(!bCalledFromDecodeOptional) {
+ // There can be a more than one optional tag in front of an actual data item
+ // they are all handled by looping in DecodeOptional which calls back here
+ // this test avoids infinite recursion.
+ nReturn = DecodeOptional(pUInBuf, uNumber, pDecodedItem);
+ }
+ break;
+
+ case CBOR_MAJOR_TYPE_SIMPLE: // Major type 7, float, double, true, false, null...
+ nReturn = DecodeSimple(uAdditionalInfo, uNumber, pDecodedItem);
+ break;
+
+ default: // Should never happen because DecodeTypeAndNumber() should never return > 7
+ nReturn = QCBOR_ERR_UNSUPPORTED;
+ break;
+ }
+
+Done:
+ return nReturn;
+}
+
+
+/*
+ Public function, see header qcbor.h file
+ */
+int QCBORDecode_GetNext(QCBORDecodeContext *me, QCBORItem *pDecodedItem)
+{
+ int nReturn;
+
+ if(!UsefulInputBuf_BytesUnconsumed(&(me->InBuf))) {
+ nReturn = QCBOR_ERR_HIT_END;
+ goto Done;
+ }
+
+ nReturn = GetAnItem(&(me->InBuf), pDecodedItem, 0);
+ if(nReturn)
+ goto Done;
+
+ // If in a map and the right decoding mode, get the label
+ if(DecodeNesting_TypeIsMap(&(me->nesting)) && me->uDecodeMode != QCBOR_DECODE_MODE_MAP_AS_ARRAY) {
+ // In a map and caller wants maps decoded, not treated as arrays
+
+ // Get the next item which will be the real data; Item will be the label
+ QCBORItem LabelItem = *pDecodedItem;
+ nReturn = GetAnItem(&(me->InBuf), pDecodedItem, 0);
+ if(nReturn)
+ goto Done;
+
+ if(LabelItem.uDataType == QCBOR_TYPE_TEXT_STRING) {
+ // strings are always good labels
+ pDecodedItem->label.string = LabelItem.val.string;
+ pDecodedItem->uLabelType = QCBOR_TYPE_TEXT_STRING;
+ } else if (QCBOR_DECODE_MODE_MAP_STRINGS_ONLY == me->uDecodeMode) {
+ // It's not a string and we only want strings, probably for easy translation to JSON
+ nReturn = QCBOR_ERR_MAP_LABEL_TYPE;
+ goto Done;
+ } else if(LabelItem.uDataType == QCBOR_TYPE_INT64) {
+ pDecodedItem->label.int64 = LabelItem.val.int64;
+ pDecodedItem->uLabelType = QCBOR_TYPE_INT64;
+ } else if(LabelItem.uDataType == QCBOR_TYPE_UINT64) {
+ pDecodedItem->label.uint64 = LabelItem.val.uint64;
+ pDecodedItem->uLabelType = QCBOR_TYPE_UINT64;
+ } else if(LabelItem.uDataType == QCBOR_TYPE_BYTE_STRING) {
+ pDecodedItem->label.string = LabelItem.val.string;
+ pDecodedItem->uLabelType = QCBOR_TYPE_BYTE_STRING;
+ } else {
+ // label is not an int or a string. It is an arrray
+ // or a float or such and this implementation doesn't handle that.
+ nReturn = QCBOR_ERR_MAP_LABEL_TYPE ;
+ goto Done;
+ }
+ }
+
+ // Record the nesting level for this data item
+ pDecodedItem->uNestingLevel = DecodeNesting_GetLevel(&(me->nesting));
+
+ // If the new item is a non-empty array or map, the nesting level descends
+ if(IsMapOrArray(pDecodedItem->uDataType) && pDecodedItem->val.uCount) {
+ nReturn = DecodeNesting_Descend(&(me->nesting), pDecodedItem->uDataType, pDecodedItem->val.uCount);
+ } else {
+ // Track number of items in maps and arrays and ascend nesting if all are consumed
+ // Note that an empty array or map is like a integer or string in effect here
+ DecodeNesting_Decrement(&(me->nesting), pDecodedItem->uDataType);
+ }
+
+Done:
+ return nReturn;
+}
+
+
+/*
+ Public function, see header qcbor.h file
+ */
+int QCBORDecode_Finish(QCBORDecodeContext *me)
+{
+ return UsefulInputBuf_BytesUnconsumed(&(me->InBuf)) ? QCBOR_ERR_EXTRA_BYTES : QCBOR_SUCCESS;
+}
+
+
+
+/*
+
+Decoder errors handled in this file
+
+ - Hit end of input before it was expected while decoding type and number QCBOR_ERR_HIT_END
+
+ - indefinite length, currently not supported QCBOR_ERR_UNSUPPORTED
+
+ - negative integer that is too large for C QCBOR_ERR_INT_OVERFLOW
+
+ - Hit end of input while decoding a text or byte string QCBOR_ERR_HIT_END
+
+ - Encountered conflicting tags -- e.g., an item is tagged both a date string and an epoch date QCBOR_ERR_UNSUPPORTED
+
+ - Encountered a break, not supported because indefinite lengths are not supported QCBOR_ERR_UNSUPPORTED
+
+ - Encontered an array or mapp that has too many items QCBOR_ERR_ARRAY_TOO_LONG
+
+ - Encountered array/map nesting that is too deep QCBOR_ERR_ARRAY_NESTING_TOO_DEEP
+
+ - An epoch date > INT64_MAX or < INT64_MIN was encountered QCBOR_ERR_DATE_OVERFLOW
+
+ - The type of a map label is not a string or int QCBOR_ERR_MAP_LABEL_TYPE
+
+ - Hit end with arrays or maps still open -- QCBOR_ERR_EXTRA_BYTES
+
+ */
+
diff --git a/src/qcbor_encode.c b/src/qcbor_encode.c
new file mode 100644
index 0000000..7b53ac1
--- /dev/null
+++ b/src/qcbor_encode.c
@@ -0,0 +1,632 @@
+/*==============================================================================
+Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of The Linux Foundation nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+==============================================================================*/
+
+/*===================================================================================
+ FILE: qcbor_encode.c
+
+ DESCRIPTION: This file contains the implementation of QCBOR.
+
+ EDIT HISTORY FOR FILE:
+
+ This section contains comments describing changes made to the module.
+ Notice that changes are listed in reverse chronological order.
+
+ when who what, where, why
+ -------- ---- ---------------------------------------------------
+ 02/05/18 llundbla Works on CPUs which require integer alignment.
+ Requires new version of UsefulBuf.
+ 07/05/17 llundbla Add bstr wrapping of maps/arrays for COSE
+ 03/01/17 llundbla More data types
+ 11/13/16 llundbla Integrate most TZ changes back into github version.
+ 09/30/16 gkanike Porting to TZ.
+ 03/15/16 llundbla Initial Version.
+
+ =====================================================================================*/
+
+#include "qcbor.h"
+#include <stdint.h>
+
+#ifdef QSEE
+#include "stringl.h"
+#endif
+
+/*...... This is a ruler that is 80 characters long...........................*/
+
+
+// Used internally in the impementation here
+// Must not conflict with any of the official CBOR types
+#define CBOR_MAJOR_NONE_TYPE_RAW 9
+
+
+
+
+
+/*
+ CBOR's two nesting types, arrays and maps, are tracked here. There is a
+ limit of QCBOR_MAX_ARRAY_NESTING to the number of arrays and maps
+ that can be nested in one encoding so the encoding context stays
+ small enough to fit on the stack.
+
+ When an array / map is opened, pCurrentNesting points to the element
+ in pArrays that records the type, start position and accumluates a
+ count of the number of items added. When closed the start position is
+ used to go back and fill in the type and number of items in the array
+ / map.
+
+ Encoded output be just items like ints and strings that are
+ not part of any array / map. That is, the first thing encoded
+ does not have to be an array or a map.
+ */
+inline static void Nesting_Init(QCBORTrackNesting *pNesting)
+{
+ // assumes pNesting has been zeroed
+ pNesting->pCurrentNesting = &pNesting->pArrays[0];
+ // Implied CBOR array at the top nesting level. This is never returned,
+ // but makes the item count work correctly.
+ pNesting->pCurrentNesting->uMajorType = CBOR_MAJOR_TYPE_ARRAY;
+}
+
+inline static int Nesting_Increase(QCBORTrackNesting *pNesting, uint8_t uMajorType, uint32_t uPos, bool bBstWrap)
+{
+ int nReturn = QCBOR_SUCCESS;
+
+ if(pNesting->pCurrentNesting == &pNesting->pArrays[QCBOR_MAX_ARRAY_NESTING]) {
+ // trying to open one too many
+ nReturn = QCBOR_ERR_ARRAY_NESTING_TOO_DEEP;
+ } else {
+ pNesting->pCurrentNesting++;
+ pNesting->pCurrentNesting->uCount = 0;
+ pNesting->pCurrentNesting->uStart = uPos;
+ pNesting->pCurrentNesting->uMajorType = uMajorType;
+ pNesting->pCurrentNesting->bBstrWrap = bBstWrap;
+ }
+ return nReturn;
+}
+
+inline static void Nesting_Decrease(QCBORTrackNesting *pNesting)
+{
+ pNesting->pCurrentNesting--;
+}
+
+inline static int Nesting_Increment(QCBORTrackNesting *pNesting, uint16_t uAmount)
+{
+ if(uAmount >= QCBOR_MAX_ITEMS_IN_ARRAY - pNesting->pCurrentNesting->uCount) {
+ return QCBOR_ERR_ARRAY_TOO_LONG;
+ }
+
+ pNesting->pCurrentNesting->uCount += uAmount;
+ return QCBOR_SUCCESS;
+}
+
+inline static uint16_t Nesting_GetCount(QCBORTrackNesting *pNesting)
+{
+ // The nesting count recorded is always the actual number of individiual
+ // data items in the array or map. For arrays CBOR uses the actual item
+ // count. For maps, CBOR uses the number of pairs. This function returns
+ // the number needed for the CBOR encoding, so it divides the number of
+ // items by two for maps to get the number of pairs. This implementation
+ // takes advantage of the map major type being one larger the array major
+ // type, hence the subtraction returns either 1 or 2.
+ return pNesting->pCurrentNesting->uCount / (pNesting->pCurrentNesting->uMajorType - CBOR_MAJOR_TYPE_ARRAY+1);
+}
+
+inline static uint32_t Nesting_GetStartPos(QCBORTrackNesting *pNesting)
+{
+ return pNesting->pCurrentNesting->uStart;
+}
+
+inline static uint8_t Nesting_GetMajorType(QCBORTrackNesting *pNesting)
+{
+ return pNesting->pCurrentNesting->uMajorType;
+}
+
+inline static int Nesting_IsInNest(QCBORTrackNesting *pNesting)
+{
+ return pNesting->pCurrentNesting == &pNesting->pArrays[0] ? 0 : 1;
+}
+
+inline static bool Nesting_IsBstrWrapped(QCBORTrackNesting *pNesting)
+{
+ return pNesting->pCurrentNesting->bBstrWrap;
+}
+
+
+
+/*
+ Error tracking plan -- Errors are tracked internally and not returned
+ until Finish is called. The CBOR errors are in me->uError.
+ UsefulOutBuf also tracks whether the the buffer is full or not in its
+ context. Once either of these errors is set they are never
+ cleared. Only Init() resets them. Or said another way, they must
+ never be cleared or we'll tell the caller all is good when it is not.
+
+ Only one error code is reported by Finish() even if there are
+ multiple errors. The last one set wins. The caller might have to fix
+ one error to reveal the next one they have to fix. This is OK.
+
+ The buffer full error tracked by UsefulBuf is only pulled out of
+ UsefulBuf in Finish() so it is the one that usually wins. UsefulBuf
+ will never go off the end of the buffer even if it is called again
+ and again when full.
+
+ It is really tempting to not check for overflow on the count in the
+ number of items in an array. It would save a lot of code, it is
+ extremely unlikely that any one will every put 65,000 items in an
+ array, and the only bad thing that would happen is the CBOR would be
+ bogus. Once we prove that is the only consequence, then we can make
+ the change.
+
+ Since this does not parse any input, you could in theory remove all
+ error checks in this code if you knew the caller called it
+ correctly. Maybe someday CDDL or some such language will be able to
+ generate the code to call this and the calling code would always be
+ correct. This could also make automatically size some of the data
+ structures like array/map nesting resulting in some good memory
+ savings.
+ */
+
+
+
+
+/*
+ Public function for initialization. See header qcbor.h
+ */
+void QCBOREncode_Init(QCBOREncodeContext *me, void *pBuf, size_t uBufLen)
+{
+ memset(me, 0, sizeof(QCBOREncodeContext));
+ if(uBufLen > UINT32_MAX) {
+ me->uError = QCBOR_ERR_BUFFER_TOO_LARGE;
+ } else {
+ UsefulOutBuf_Init(&(me->OutBuf), pBuf, uBufLen);
+ Nesting_Init(&(me->nesting));
+ }
+}
+
+
+
+
+/*
+ All CBOR data items have a type and a number. The number is either
+ the value of the item for integer types, the length of the content
+ for string, byte, array and map types, a tag for major type 6, and
+ has serveral uses for major type 7.
+
+ This function encodes the type and the number. There are several
+ encodings for the number depending on how large it is and how it is
+ used.
+
+ Every encoding of the type and number has at least one byte, the
+ "initial byte".
+
+ The top three bits of the initial byte are the major type for the
+ CBOR data item. The eight major types defined by the standard are
+ defined as CBOR_MAJOR_TYPE_xxxx in qcbor.h.
+
+ The remaining five bits, known as "additional information", and
+ possibly more bytes encode the number. If the number is less than 24,
+ then it is encoded entirely in the five bits. This is neat because it
+ allows you to encode an entire CBOR data item in 1 byte for many
+ values and types (integers 0-23, true, false, and tags).
+
+ If the number is larger than 24, then it is encoded in 1,2,4 or 8
+ additional bytes, with the number of these bytes indicated by the
+ values of the 5 bits 24, 25, 25 and 27.
+
+ It is possible to encode a particular number in many ways with this
+ representation. This implementation always uses the smallest
+ possible representation. This is also the suggestion made in the RFC
+ for cannonical CBOR.
+
+ This function inserts them into the output buffer at the specified
+ position. AppendEncodedTypeAndNumber() appends to the end.
+
+ This function takes care of converting to network byte order.
+
+ This function is also used to insert floats and doubles. Before this
+ function is called the float or double must be copied into a
+ uint64_t. That is how they are passed in. They are then converted to
+ network byte order correctly. The uMinLen param makes sure that even
+ if all the digits of a float or double are 0 it is still correctly
+ encoded in 4 or 8 bytes.
+
+ */
+static void InsertEncodedTypeAndNumber(QCBOREncodeContext *me, uint8_t uMajorType, size_t uMinLen, uint64_t uNumber, size_t uPos)
+{
+ // No need to worry about integer overflow here because a) uMajorType is
+ // always generated internally, not by the caller, b) this is for CBOR
+ // _generation_, not parsing c) a mistake will result in bad CBOR generation,
+ // not a security vulnerability.
+ uMajorType <<= 5;
+
+ if(uNumber > 0xffffffff || uMinLen >= 8) {
+ UsefulOutBuf_InsertByte(&(me->OutBuf), uMajorType + LEN_IS_EIGHT_BYTES, uPos);
+ UsefulOutBuf_InsertUint64(&(me->OutBuf), (uint64_t)uNumber, uPos+1);
+
+ } else if(uNumber > 0xffff || uMinLen >= 4) {
+ UsefulOutBuf_InsertByte(&(me->OutBuf), uMajorType + LEN_IS_FOUR_BYTES, uPos);
+ UsefulOutBuf_InsertUint32(&(me->OutBuf), (uint32_t)uNumber, uPos+1);
+
+ } else if (uNumber > 0xff) {
+ // Between 0 and 65535
+ UsefulOutBuf_InsertByte(&(me->OutBuf), uMajorType + LEN_IS_TWO_BYTES, uPos);
+ UsefulOutBuf_InsertUint16(&(me->OutBuf), (uint16_t)uNumber, uPos+1);
+
+ } else if(uNumber >= 24) {
+ // Between 0 and 255, but only between 24 and 255 is ever encoded here
+ UsefulOutBuf_InsertByte(&(me->OutBuf), uMajorType + LEN_IS_ONE_BYTE, uPos);
+ UsefulOutBuf_InsertByte(&(me->OutBuf), (uint8_t)uNumber, uPos+1);
+
+ } else {
+ // Between 0 and 23
+ UsefulOutBuf_InsertByte(&(me->OutBuf), uMajorType + (uint8_t)uNumber, uPos);
+ }
+}
+
+
+/*
+ Append the type and number info to the end of the buffer.
+
+ See InsertEncodedTypeAndNumber() function above for details
+*/
+inline static void AppendEncodedTypeAndNumber(QCBOREncodeContext *me, uint8_t uMajorType, uint64_t uNumber)
+{
+ // An append is an insert at the end.
+ InsertEncodedTypeAndNumber(me, uMajorType, 0, uNumber, UsefulOutBuf_GetEndPosition(&(me->OutBuf)));
+}
+
+
+static void AddBytesInternal(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, UsefulBufC Bytes, uint8_t uMajorType, uint16_t uItems);
+
+
+/*
+ Add an optional label and optional tag. It will go in front of a real data item.
+ */
+static void AddLabelAndOptionalTag(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag)
+{
+ if(szLabel) {
+ UsefulBufC SZText = {szLabel, strlen(szLabel)};
+ AddBytesInternal(me, NULL, nLabel, CBOR_TAG_NONE, SZText, CBOR_MAJOR_TYPE_TEXT_STRING, 0);
+ } else if (QCBOR_NO_INT_LABEL != nLabel) {
+ // Add an integer label. This is just adding an integer at this point
+ // This will result in a call right back to here, but the call won't do anything
+ // because of the params NULL, QCBOR_NO_INT_LABEL and CBOR_TAG_NONE
+ QCBOREncode_AddInt64_3(me, NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, nLabel);
+ }
+ if(uTag != CBOR_TAG_NONE) {
+ AppendEncodedTypeAndNumber(me, CBOR_MAJOR_TYPE_OPTIONAL, uTag);
+ }
+}
+
+
+/*
+ Does the work of adding some bytes to the CBOR output. Works for a
+ byte and text strings, which are the same in in CBOR though they have
+ different major types. This is also used to insert raw or
+ pre-formatted CBOR.
+ */
+static void AddBytesInternal(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, UsefulBufC Bytes, uint8_t uMajorType, uint16_t uItems)
+{
+ if(Bytes.len >= UINT32_MAX) {
+ // This implementation doesn't allow buffers larger than UINT32_MAX. This is
+ // primarily because QCBORTrackNesting.pArrays[].uStart is an uint32 rather
+ // than size_t to keep the stack usage down. Also it is entirely impractical
+ // to create tokens bigger than 4GB in contiguous RAM
+ me->uError = QCBOR_ERR_BUFFER_TOO_LARGE;
+
+ } else {
+
+ AddLabelAndOptionalTag(me, szLabel, nLabel, uTag);
+
+ if(!me->uError) {
+
+ // If it is not Raw CBOR, add the type and the length
+ if(uMajorType != CBOR_MAJOR_NONE_TYPE_RAW) {
+ AppendEncodedTypeAndNumber(me, uMajorType, Bytes.len);
+ }
+
+ // Actually add the bytes
+ UsefulOutBuf_AppendUsefulBuf(&(me->OutBuf), Bytes);
+
+ // Update the array counting if there is any nesting at all
+ me->uError = Nesting_Increment(&(me->nesting), uMajorType == CBOR_MAJOR_NONE_TYPE_RAW ? uItems : 1);
+ }
+ }
+}
+
+
+
+
+/*
+ Public functions for adding strings and raw encoded CBOR. See header qcbor.h
+ */
+void QCBOREncode_AddBytes_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, UsefulBufC Bytes)
+{
+ AddBytesInternal(me, szLabel, nLabel, uTag, Bytes, CBOR_MAJOR_TYPE_BYTE_STRING, 0);
+}
+
+void QCBOREncode_AddText_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, UsefulBufC Bytes)
+{
+ AddBytesInternal(me, szLabel, nLabel, uTag, Bytes, CBOR_MAJOR_TYPE_TEXT_STRING, 0);
+}
+
+void QCBOREncode_AddRaw(QCBOREncodeContext *me, EncodedCBORC Raw)
+{
+ AddBytesInternal(me, NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, Raw.Bytes, CBOR_MAJOR_NONE_TYPE_RAW, Raw.uItems);
+}
+
+
+
+
+/*
+ Internal function common to opening an array or a map
+
+ QCBOR_MAX_ARRAY_NESTING is the number of times Open can be called
+ successfully. Call it one more time gives an error.
+
+ */
+static void OpenMapOrArrayInternal(QCBOREncodeContext *me, uint8_t uMajorType, const char *szLabel, uint64_t nLabel, uint64_t uTag, bool bBstrWrap)
+{
+ AddLabelAndOptionalTag(me, szLabel, nLabel, uTag);
+
+ if(!me->uError) {
+ // Add one item to the nesting level we are in for the new map or array
+ me->uError = Nesting_Increment(&(me->nesting), 1);
+ if(!me->uError) {
+ // Increase nesting level because this is a map or array
+ // Cast from size_t to uin32_t is safe because the UsefulOutBuf
+ // size is limited to UINT32_MAX in QCBOR_Init().
+ me->uError = Nesting_Increase(&(me->nesting),
+ uMajorType, (uint32_t)UsefulOutBuf_GetEndPosition(&(me->OutBuf)),
+ bBstrWrap);
+ }
+ }
+}
+
+
+/*
+ Public functions for opening / closing arrays and maps. See header qcbor.h
+ */
+void QCBOREncode_OpenArray_3(QCBOREncodeContext *me, const char *szLabel, uint64_t nLabel, uint64_t uTag, bool bBstrWrap)
+{
+ OpenMapOrArrayInternal(me, CBOR_MAJOR_TYPE_ARRAY, szLabel, nLabel, uTag, bBstrWrap);
+}
+
+void QCBOREncode_OpenMap_3(QCBOREncodeContext *me, const char *szLabel, uint64_t nLabel, uint64_t uTag, uint8_t bBstrWrap)
+{
+ OpenMapOrArrayInternal(me, CBOR_MAJOR_TYPE_MAP, szLabel, nLabel, uTag, bBstrWrap);
+}
+
+void QCBOREncode_CloseArray(QCBOREncodeContext *me)
+{
+ if(!Nesting_IsInNest(&(me->nesting))) {
+ me->uError = QCBOR_ERR_TOO_MANY_CLOSES;
+
+ } else {
+ // When the array was opened, nothing was done except note the position
+ // of the start of the array. This code goes back and inserts the type
+ // (array or map) and length. That means all the data in the array or map
+ // and any nested arrays or maps have to be slid right. This is done
+ // by UsefulOutBuf's insert function that is called from inside
+ // InsertEncodedTypeAndNumber()
+
+ const uint32_t uInsertPosition = Nesting_GetStartPos(&(me->nesting));
+
+ InsertEncodedTypeAndNumber(me,
+ Nesting_GetMajorType(&(me->nesting)), // the major type (array or map)
+ 0, // no minimum length for encoding
+ Nesting_GetCount(&(me->nesting)), // number of items in array or map
+ uInsertPosition); // position in output buffer
+
+ if(Nesting_IsBstrWrapped(&(me->nesting))) {
+ // This map or array is to be wrapped in a byte string. This is typically because
+ // the data is to be hashed or cryprographically signed. This is what COSE
+ // signing does.
+
+ // Cast from size_t to uin32_t is safe because the UsefulOutBuf
+ // size is limited to UINT32_MAX in QCBOR_Init().
+ uint32_t uLenOfEncodedMapOrArray = (uint32_t)UsefulOutBuf_GetEndPosition(&(me->OutBuf)) - uInsertPosition;
+
+ // Insert the bstring wrapping
+ InsertEncodedTypeAndNumber(me,
+ CBOR_MAJOR_TYPE_BYTE_STRING, // major type bstring
+ 0, // no minimum length for encoding
+ uLenOfEncodedMapOrArray, // length of the map
+ uInsertPosition); // position in out buffer
+ }
+
+ Nesting_Decrease(&(me->nesting));
+ }
+}
+
+
+
+
+/*
+ Internal function for adding positive and negative integers of all different sizes
+ */
+static void AddUInt64Internal(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, uint8_t uMajorType, uint64_t n)
+{
+ AddLabelAndOptionalTag(me, szLabel, nLabel, uTag);
+ if(!me->uError) {
+ AppendEncodedTypeAndNumber(me, uMajorType, n);
+ me->uError = Nesting_Increment(&(me->nesting), 1);
+ }
+}
+
+
+/*
+ Public functions for adding integers. See header qcbor.h
+ */
+void QCBOREncode_AddUInt64_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, uint64_t uNum)
+{
+ AddUInt64Internal(me, szLabel, nLabel, uTag, CBOR_MAJOR_TYPE_POSITIVE_INT, uNum);
+}
+
+void QCBOREncode_AddInt64_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, int64_t nNum)
+{
+ uint8_t uMajorType;
+ uint64_t uValue;
+
+ // Handle CBOR's particular format for positive and negative integers
+ if(nNum < 0) {
+ uValue = (uint64_t)(-nNum - 1); // This is the way negative ints work in CBOR. -1 encodes as 0x00 with major type negative int.
+ uMajorType = CBOR_MAJOR_TYPE_NEGATIVE_INT;
+ } else {
+ uValue = (uint64_t)nNum;
+ uMajorType = CBOR_MAJOR_TYPE_POSITIVE_INT;
+ }
+ AddUInt64Internal(me, szLabel, nLabel, uTag, uMajorType, uValue);
+}
+
+
+
+
+/*
+ Common code for adding floats and doubles and simple types like true and false
+
+ One way to look at simple values is that they are:
+ - type 7
+ - an additional integer from 0 to 255
+ - additional integer 0-19 are unassigned and could be used in an update to CBOR
+ - additional integers 20, 21, 22 and 23 are false, true, null and undef
+ - additional integer 24 is not available
+ - when the additional value is 25, 26, or 27 there is additionally a half, float or double in following bytes
+ - additional integers 28, 29 and 30 are unassigned / reserved
+ - additional integer 31 is a "break"
+ - additional integers 32-255 are unassigned and could be used in an update to CBOR
+ */
+static void AddSimpleInternal(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, size_t uSize, uint64_t uNum)
+{
+ AddLabelAndOptionalTag(me, szLabel, nLabel, uTag);
+ if(!me->uError) {
+ // This function call takes care of endian swapping for the float / double
+ InsertEncodedTypeAndNumber(me,
+ CBOR_MAJOR_TYPE_SIMPLE, // The major type for floats and doubles
+ uSize, // min size / tells encoder to do it right
+ uNum, // Bytes of the floating point number as a uint
+ UsefulOutBuf_GetEndPosition(&(me->OutBuf))); // end position for append
+
+ me->uError = Nesting_Increment(&(me->nesting), 1);
+ }
+}
+
+
+/*
+ Public function for adding simple values. See header qcbor.h
+ */
+void QCBOREncode_AddRawSimple_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, uint8_t uSimple)
+{
+ AddSimpleInternal(me, szLabel, nLabel, uTag, 0, uSimple);
+}
+
+
+/*
+ Public function for adding simple values. See header qcbor.h
+ */
+void QCBOREncode_AddSimple_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, uint8_t uSimple)
+{
+ if(uSimple < CBOR_SIMPLEV_FALSE || uSimple > CBOR_SIMPLEV_UNDEF) {
+ me->uError = QCBOR_ERR_BAD_SIMPLE;
+ } else {
+ QCBOREncode_AddRawSimple_3(me, szLabel, nLabel, uTag, uSimple);
+ }
+}
+
+
+/*
+ Public functions for floating point numbers. See header qcbor.h
+ */
+void QCBOREncode_AddFloat_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, float fNum)
+{
+ // Convert the *type* of the data from a float to a uint so the
+ // standard integer encoding can work. This takes advantage
+ // of CBOR's indicator for a float being the same as for a 4
+ // byte integer too.
+ const float *pfNum = &fNum;
+ const uint32_t uNum = *(uint32_t *)pfNum;
+
+ AddSimpleInternal(me, szLabel, nLabel, uTag, sizeof(float), uNum);
+}
+
+void QCBOREncode_AddDouble_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, double dNum)
+{
+ // see how it is done for floats above
+ const double *pdNum = &dNum;
+ const uint64_t uNum = *(uint64_t *)pdNum;
+
+ AddSimpleInternal(me, szLabel, nLabel, uTag, sizeof(double), uNum);
+}
+
+
+
+
+/*
+ Public functions to finish and get the encoded result. See header qcbor.h
+ */
+int QCBOREncode_Finish2(QCBOREncodeContext *me, EncodedCBOR *pEncodedCBOR)
+{
+ if(me->uError)
+ goto Done;
+
+ if (Nesting_IsInNest(&(me->nesting))) {
+ me->uError = QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN;
+ goto Done;
+ }
+
+ if(UsefulOutBuf_GetError(&(me->OutBuf))) {
+ // Stuff didn't fit in the buffer.
+ // This check catches this condition for all the appends and inserts so checks aren't needed
+ // when the appends and inserts are performed. And of course UsefulBuf will never
+ // overrun the input buffer given to it. No complex analysis of the error handling
+ // in this file is needed to know that is true. Just read the UsefulBuf code.
+ me->uError = QCBOR_ERR_BUFFER_TOO_SMALL;
+ goto Done;
+ }
+
+ UsefulOutBuf_OutUBuf(&(me->OutBuf), &(pEncodedCBOR->Bytes));
+ pEncodedCBOR->uItems = Nesting_GetCount(&(me->nesting));
+
+Done:
+ return me->uError;
+}
+
+int QCBOREncode_Finish(QCBOREncodeContext *me, size_t *puEncodedLen)
+{
+ EncodedCBOR Enc;
+
+ int nReturn = QCBOREncode_Finish2(me, &Enc);
+
+ if(nReturn == QCBOR_SUCCESS) {
+ *puEncodedLen = Enc.Bytes.len;
+ }
+
+ return nReturn;
+}
+
+