static int prepareheaderDataInfo()

in src/mqtt_codec.c [515:586]


static int prepareheaderDataInfo(MQTTCODEC_INSTANCE* codecData, uint8_t remainLen)
{
    int result;
    result = 0;
    codecData->storeRemainLen[codecData->remainLenIndex++] = remainLen;
    if (remainLen <= 0x7f)
    {
        int multiplier = 1;
        int totalLen = 0;
        size_t index = 0;
        uint8_t encodeByte = 0;
        do
        {
            encodeByte = codecData->storeRemainLen[index++];
            totalLen += (encodeByte & 127) * multiplier;
            multiplier *= NEXT_128_CHUNK;

            if (multiplier > MAX_3_DIGIT_PACKET_SIZE)
            {
                result = MU_FAILURE;
                break;
            }
        } while ((encodeByte & NEXT_128_CHUNK) != 0);

        if (result != 0 || totalLen > MAX_SEND_SIZE)
        {
            LogError("Receive buffer too large for MQTT packet");
            result = MU_FAILURE;
        }
        else
        {
            codecData->codecState = CODEC_STATE_VAR_HEADER;

            // Reset remainLen Index
            codecData->remainLenIndex = 0;
            memset(codecData->storeRemainLen, 0, 4 * sizeof(uint8_t));

            if (totalLen > 0)
            {
                codecData->bufferOffset = 0;
                codecData->headerData = BUFFER_new();
                if (codecData->headerData == NULL)
                {
                    /* Codes_SRS_MQTT_CODEC_07_035: [ If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value. ] */
                    LogError("Failed BUFFER_new");
                    result = MU_FAILURE;
                }
                else
                {
                    if (BUFFER_pre_build(codecData->headerData, totalLen) != 0)
                    {
                        /* Codes_SRS_MQTT_CODEC_07_035: [ If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value. ] */
                        LogError("Failed BUFFER_pre_build");
                        result = MU_FAILURE;
                    }

                }
            }
        }
    }
    else if (codecData->remainLenIndex == (sizeof(codecData->storeRemainLen) / sizeof(codecData->storeRemainLen[0])))
    {
        // The maximum number of bytes in the Remaining Length field is four
        // This allows applications to send Control Packets of size up to 268,435,455 (256 MB). 
        // The representation of this number on the wire is: 0xFF, 0xFF, 0xFF, 0x7F.

        // The last byte has exceed the max value of 0x7F
        LogError("MQTT packet len is invalid");
        result = MU_FAILURE;
    }
    return result;
}