+ if(!s->inseqno)
+ s->received = 0;
+ else
+ s->received++;
+ }
+
+ return true;
+}
+
+// Check datagram for valid HMAC
+bool sptps_verify_datagram(sptps_t *s, const void *data, size_t len) {
+ if(!s->instate || len < 21)
+ return error(s, EIO, "Received short packet");
+
+ uint32_t seqno;
+ memcpy(&seqno, data, 4);
+ seqno = ntohl(seqno);
+ if (!sptps_check_seqno(s, seqno, false))
+ return false;
+
+ char buffer[len];
+ size_t outlen;
+ return chacha_poly1305_decrypt(s->incipher, seqno, data + 4, len - 4, buffer, &outlen);
+}
+
+// Receive incoming data, datagram version.
+static bool sptps_receive_data_datagram(sptps_t *s, const char *data, size_t len) {
+ if(len < (s->instate ? 21 : 5))
+ return error(s, EIO, "Received short packet");
+
+ uint32_t seqno;
+ memcpy(&seqno, data, 4);
+ seqno = ntohl(seqno);
+ data += 4; len -= 4;
+
+ if(!s->instate) {
+ if(seqno != s->inseqno)
+ return error(s, EIO, "Invalid packet seqno: %d != %d", seqno, s->inseqno);
+
+ s->inseqno = seqno + 1;
+
+ uint8_t type = *(data++); len--;
+
+ if(type != SPTPS_HANDSHAKE)
+ return error(s, EIO, "Application record received before handshake finished");
+
+ return receive_handshake(s, data, len);
+ }
+
+ // Decrypt
+
+ char buffer[len];
+ size_t outlen;
+ if(!chacha_poly1305_decrypt(s->incipher, seqno, data, len, buffer, &outlen))
+ return error(s, EIO, "Failed to decrypt and verify packet");
+
+ if(!sptps_check_seqno(s, seqno, true))
+ return false;
+
+ // Append a NULL byte for safety.
+ buffer[outlen] = 0;
+
+ data = buffer;
+ len = outlen;
+
+ uint8_t type = *(data++); len--;
+
+ if(type < SPTPS_HANDSHAKE) {
+ if(!s->instate)
+ return error(s, EIO, "Application record received before handshake finished");
+ if(!s->receive_record(s->handle, type, data, len))
+ return false;
+ } else if(type == SPTPS_HANDSHAKE) {
+ if(!receive_handshake(s, data, len))
+ return false;
+ } else {
+ return error(s, EIO, "Invalid record type %d", type);
+ }
+
+ return true;
+}
+
+// Receive incoming data. Check if it contains a complete record, if so, handle it.
+size_t sptps_receive_data(sptps_t *s, const void *data, size_t len) {
+ size_t total_read = 0;
+
+ if(!s->state)
+ return error(s, EIO, "Invalid session state zero");
+
+ if(s->datagram)
+ return sptps_receive_data_datagram(s, data, len) ? len : false;
+
+ // First read the 2 length bytes.
+ if(s->buflen < 2) {
+ size_t toread = 2 - s->buflen;