+ }
+
+ if(update_state) {
+ // Mark the current packet as not being late.
+ s->late[(seqno / 8) % s->replaywin] &= ~(1 << seqno % 8);
+ s->farfuture = 0;
+ }
+ }
+
+ if(update_state) {
+ if(seqno >= s->inseqno) {
+ s->inseqno = seqno + 1;
+ }
+
+ 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 *vdata, size_t len) {
+ if(!s->instate || len < 21) {
+ return error(s, EIO, "Received short packet");
+ }
+
+ const uint8_t *data = vdata;
+ uint32_t seqno;
+ memcpy(&seqno, data, 4);
+ seqno = ntohl(seqno);
+
+ if(!sptps_check_seqno(s, seqno, false)) {
+ return false;
+ }
+
+ uint8_t 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 uint8_t *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