+ 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;
+
+ if(toread > len) {
+ toread = len;
+ }
+
+ memcpy(s->inbuf + s->buflen, data, toread);
+
+ total_read += toread;