bool build_handshake_packet(nabto_connect* con, uint8_t* buffer, size_t bufferLength, size_t* packetLength) { uint8_t* packetPtr; /* * type, 1 bytes * flags, 1 bytes * nsi cp, 4 bytes * nsi sp, 4 bytes * nsi co, 4 bytes * id, 20 bytes */ size_t nonceLength = 38; uint8_t nonce[38]; uint8_t* noncePtr = nonce; packetPtr = insert_header(buffer, con->cpnsi, con->spnsi, NP_PACKET_HDR_TYPE_GW_CONN_U, false, 0, 0, con->consi); //NOTE: These type and flags must match the connection attributes set //in the unabto_tcp_fallback_connect_thread when a connection is //established. WRITE_U8(noncePtr, NP_GW_CONN_U_TYPE_TCP); noncePtr+=1; WRITE_U8(noncePtr, NP_GW_CONN_U_FLAG_RELIABLE); noncePtr+=1; WRITE_U32(noncePtr, con->cpnsi); noncePtr+=4; WRITE_U32(noncePtr, con->spnsi); noncePtr+=4; memcpy(noncePtr, con->consi, 8); noncePtr+=8; memcpy(noncePtr, con->gatewayId, 20); packetPtr = insert_payload(packetPtr, NP_PAYLOAD_TYPE_NONCE, nonce, nonceLength); *packetLength = packetPtr - buffer; insert_length(buffer, *packetLength); return true; }
/* Reconstruct nabto header with crypto payload header. */ uint8_t* reconstruct_header(uint8_t* buf, const nabto_packet_header * hdr) { uint8_t* ptr; // insert copy of request header (Length will be inserted later) ptr = buf; /* Write fixed part of packet header */ WRITE_U32(ptr, hdr->nsi_cp); ptr += 4; WRITE_U32(ptr, hdr->nsi_sp); ptr += 4; WRITE_U8(ptr, hdr->type); ptr += 1; WRITE_U8(ptr, hdr->version); ptr += 1; WRITE_U8(ptr, hdr->rsvd); ptr += 1; WRITE_U8(ptr, hdr->flags | NP_PACKET_HDR_FLAG_RESPONSE); ptr += 1; WRITE_U16(ptr, hdr->seq); ptr += 2; /*WRITE_U16(ptr, len);*/ ptr += 2; /* Length to be packed later */ /* Write NSI.co to packet header (optional) */ if (hdr->flags & NP_PACKET_HDR_FLAG_NSI_CO) { memcpy(ptr, (const void*) hdr->nsi_co, 8); ptr += 8; } /* Write tag to packet header (optional) */ if (hdr->flags & NP_PACKET_HDR_FLAG_TAG) { WRITE_U16(ptr, hdr->tag); ptr += 2; } { ptrdiff_t diff = ptr - buf; if (hdr->hlen != (uint16_t)(diff)) { NABTO_LOG_ERROR(("header length mismatch: %" PRIu16 " != %" PRIptrdiff " !!!!!!!!!!!!!!!!!!!", hdr->hlen, diff)); return NULL; } } // insert crypto header (len and code will be inserted later) WRITE_U8(ptr, NP_PAYLOAD_TYPE_CRYPTO); ptr += 1; WRITE_U8(ptr, NP_PAYLOAD_HDR_FLAG_NONE); /*ptr += 1; WRITE_U16(ptr, len); ptr += 2; WRITE_U16(ptr, code); ptr += 2;*/ /* len and code is patched by unabto_encrypt() */ ptr += 5; return ptr; /* return end of packet (so far) */ }