bool unabto_connection_verify_and_decrypt_connect_packet(nabto_packet_header* hdr, uint8_t** decryptedDataStart, uint16_t* decryptedDataLength) {
    uint8_t* ptr = nabtoCommunicationBuffer + hdr->hlen;
    uint8_t* end = nabtoCommunicationBuffer + hdr->len;

    uint8_t* cryptoBegin;
    uint16_t cryptoLength;

    if (!find_payload(ptr,end, NP_PAYLOAD_TYPE_CRYPTO, &cryptoBegin, &cryptoLength)) {
        NABTO_LOG_TRACE(("########    U_CONNECT without Crypto payload from"));
        return false;
    }
    cryptoBegin += NP_PAYLOAD_HDR_BYTELENGTH;

    if (!unabto_crypto_verify_and_decrypt(hdr, nmc.context.cryptoConnect, cryptoBegin, cryptoLength, decryptedDataStart, decryptedDataLength)) 
    {
        NABTO_LOG_TRACE(("U_CONNECT verify or decryption failed"));
        return false;
    }

    if (decryptedDataLength == 0) {
        NABTO_LOG_TRACE(("U_CONNECT Decryption fail, no data"));
        return false;
    }
    return true;
}
bool nabto_fallback_connect_u_event(uint16_t packetLength, nabto_packet_header* hdr) {
    nabto_connect* con;
    uint8_t* startOfPayloads;
    uint8_t* endOfPayloads;
    uint8_t* noncePayloadStart;
    uint16_t noncePayloadLength;
    uint8_t type;
    uint8_t flags;
    uint8_t* ptr;
    bool isReliable;
    bool hasKeepAlive;

    con = nabto_find_connection(hdr->nsi_sp);
    if (con == 0) {
        NABTO_LOG_TRACE((PRInsi " No connection found.", MAKE_NSI_PRINTABLE(hdr->nsi_cp, hdr->nsi_sp, 0)));
        return false;
    }

    startOfPayloads = nabtoCommunicationBuffer + hdr->hlen;
    endOfPayloads = nabtoCommunicationBuffer + packetLength;

    if (!find_payload(startOfPayloads, endOfPayloads, NP_PAYLOAD_TYPE_NONCE, &noncePayloadStart, &noncePayloadLength)) {
        NABTO_LOG_ERROR((PRI_tcp_fb "No nonce payload in GW_CONN_U packet.", TCP_FB_ARGS(con)));
        return false;
    }

    if (noncePayloadLength < 2) {
        NABTO_LOG_ERROR((PRI_tcp_fb "The payload received is too small to contain both flags and type.", TCP_FB_ARGS(con)));
        return false;
    }

    ptr = noncePayloadStart + NP_PAYLOAD_HDR_BYTELENGTH;

    READ_U8(type, ptr);  ptr++;
    READ_U8(flags, ptr); ptr++;

    isReliable   = (flags & NP_GW_CONN_U_FLAG_RELIABLE) != 0;
    hasKeepAlive = (flags & NP_GW_CONN_U_FLAG_KEEP_ALIVE) != 0;

    con->tcpFallbackConnectionState = UTFS_READY_FOR_DATA;

    // If the connection is still resolving upgrade it to a fallback connection.
    if (isReliable) {
        con->fbConAttr |= CON_ATTR_NO_RETRANSMIT;
        NABTO_LOG_DEBUG((PRI_tcp_fb "connection needs no retransmition", TCP_FB_ARGS(con)));
    }

    if (!hasKeepAlive) {
        con->fbConAttr |= CON_ATTR_NO_KEEP_ALIVE;
        NABTO_LOG_DEBUG((PRI_tcp_fb "connection needs no keep alive", TCP_FB_ARGS(con)));
    } else {
        NABTO_LOG_DEBUG((PRI_tcp_fb "connection needs keep alive", TCP_FB_ARGS(con)));
    }
    
    return true;
}