2 utcp.c -- Userspace TCP
3 Copyright (C) 2014-2017 Guus Sliepen <guus@tinc-vpn.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "utcp_priv.h"
38 #if defined(CLOCK_MONOTONIC_RAW) && defined(__x86_64__)
39 #define UTCP_CLOCK CLOCK_MONOTONIC_RAW
41 #define UTCP_CLOCK CLOCK_MONOTONIC
45 static void timespec_sub(const struct timespec *a, const struct timespec *b, struct timespec *r) {
46 r->tv_sec = a->tv_sec - b->tv_sec;
47 r->tv_nsec = a->tv_nsec - b->tv_nsec;
50 r->tv_sec--, r->tv_nsec += NSEC_PER_SEC;
54 static int32_t timespec_diff_usec(const struct timespec *a, const struct timespec *b) {
55 return (a->tv_sec - b->tv_sec) * 1000000 + (a->tv_nsec - b->tv_nsec) / 1000;
58 static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
59 if(a->tv_sec == b->tv_sec) {
60 return a->tv_nsec < b->tv_nsec;
62 return a->tv_sec < b->tv_sec;
66 static void timespec_clear(struct timespec *a) {
71 static bool timespec_isset(const struct timespec *a) {
75 static long CLOCK_GRANULARITY; // usec
77 static inline size_t min(size_t a, size_t b) {
81 static inline size_t max(size_t a, size_t b) {
88 #ifndef UTCP_DEBUG_DATALEN
89 #define UTCP_DEBUG_DATALEN 20
92 static void debug(struct utcp_connection *c, const char *format, ...) {
97 clock_gettime(CLOCK_REALTIME, &tv);
98 len = snprintf(buf, sizeof(buf), "%ld.%06lu %u:%u ", (long)tv.tv_sec, tv.tv_nsec / 1000, c ? c->src : 0, c ? c->dst : 0);
100 va_start(ap, format);
101 len += vsnprintf(buf + len, sizeof(buf) - len, format, ap);
104 if(len > 0 && (size_t)len < sizeof(buf)) {
105 fwrite(buf, len, 1, stderr);
109 static void print_packet(struct utcp_connection *c, const char *dir, const void *pkt, size_t len) {
112 if(len < sizeof(hdr)) {
113 debug(c, "%s: short packet (%lu bytes)\n", dir, (unsigned long)len);
117 memcpy(&hdr, pkt, sizeof(hdr));
121 if(len > sizeof(hdr)) {
122 datalen = min(len - sizeof(hdr), UTCP_DEBUG_DATALEN);
128 const uint8_t *data = (uint8_t *)pkt + sizeof(hdr);
129 char str[datalen * 2 + 1];
132 for(uint32_t i = 0; i < datalen; i++) {
133 *p++ = "0123456789ABCDEF"[data[i] >> 4];
134 *p++ = "0123456789ABCDEF"[data[i] & 15];
139 debug(c, "%s: len %lu src %u dst %u seq %u ack %u wnd %u aux %x ctl %s%s%s%s%s data %s\n",
140 dir, (unsigned long)len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd, hdr.aux,
141 hdr.ctl & SYN ? "SYN" : "",
142 hdr.ctl & RST ? "RST" : "",
143 hdr.ctl & FIN ? "FIN" : "",
144 hdr.ctl & ACK ? "ACK" : "",
145 hdr.ctl & MF ? "MF" : "",
150 static void debug_cwnd(struct utcp_connection *c) {
151 debug(c, "snd.cwnd %u snd.ssthresh %u\n", c->snd.cwnd, ~c->snd.ssthresh ? c->snd.ssthresh : 0);
154 #define debug(...) do {} while(0)
155 #define print_packet(...) do {} while(0)
156 #define debug_cwnd(...) do {} while(0)
159 static void set_state(struct utcp_connection *c, enum state state) {
162 if(state == ESTABLISHED) {
163 timespec_clear(&c->conn_timeout);
166 debug(c, "state %s\n", strstate[state]);
169 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
170 if(seq != c->snd.last) {
185 static bool is_reliable(struct utcp_connection *c) {
186 return c->flags & UTCP_RELIABLE;
189 static int32_t seqdiff(uint32_t a, uint32_t b) {
194 static bool buffer_wraps(struct buffer *buf) {
195 return buf->size - buf->offset < buf->used;
198 static bool buffer_resize(struct buffer *buf, uint32_t newsize) {
199 char *newdata = realloc(buf->data, newsize);
207 if(buffer_wraps(buf)) {
208 // Shift the right part of the buffer until it hits the end of the new buffer.
212 // [345.........|........012]
213 uint32_t tailsize = buf->size - buf->offset;
214 uint32_t newoffset = newsize - tailsize;
215 memmove(buf->data + newoffset, buf->data + buf->offset, tailsize);
216 buf->offset = newoffset;
223 // Store data into the buffer
224 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
225 debug(NULL, "buffer_put_at %lu %lu %lu\n", (unsigned long)buf->used, (unsigned long)offset, (unsigned long)len);
227 // Ensure we don't store more than maxsize bytes in total
228 size_t required = offset + len;
230 if(required > buf->maxsize) {
231 if(offset >= buf->maxsize) {
235 len = buf->maxsize - offset;
236 required = buf->maxsize;
239 // Check if we need to resize the buffer
240 if(required > buf->size) {
241 size_t newsize = buf->size;
249 } while(newsize < required);
251 if(newsize > buf->maxsize) {
252 newsize = buf->maxsize;
255 if(!buffer_resize(buf, newsize)) {
260 uint32_t realoffset = buf->offset + offset;
262 if(buf->size - buf->offset <= offset) {
263 // The offset wrapped
264 realoffset -= buf->size;
267 if(buf->size - realoffset < len) {
268 // The new chunk of data must be wrapped
269 memcpy(buf->data + realoffset, data, buf->size - realoffset);
270 memcpy(buf->data, (char *)data + buf->size - realoffset, len - (buf->size - realoffset));
272 memcpy(buf->data + realoffset, data, len);
275 if(required > buf->used) {
276 buf->used = required;
282 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
283 return buffer_put_at(buf, buf->used, data, len);
286 // Copy data from the buffer without removing it.
287 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
288 // Ensure we don't copy more than is actually stored in the buffer
289 if(offset >= buf->used) {
293 if(buf->used - offset < len) {
294 len = buf->used - offset;
297 uint32_t realoffset = buf->offset + offset;
299 if(buf->size - buf->offset <= offset) {
300 // The offset wrapped
301 realoffset -= buf->size;
304 if(buf->size - realoffset < len) {
305 // The data is wrapped
306 memcpy(data, buf->data + realoffset, buf->size - realoffset);
307 memcpy((char *)data + buf->size - realoffset, buf->data, len - (buf->size - realoffset));
309 memcpy(data, buf->data + realoffset, len);
315 // Copy data from the buffer without removing it.
316 static ssize_t buffer_call(struct utcp_connection *c, struct buffer *buf, size_t offset, size_t len) {
321 // Ensure we don't copy more than is actually stored in the buffer
322 if(offset >= buf->used) {
326 if(buf->used - offset < len) {
327 len = buf->used - offset;
330 uint32_t realoffset = buf->offset + offset;
332 if(buf->size - buf->offset <= offset) {
333 // The offset wrapped
334 realoffset -= buf->size;
337 if(buf->size - realoffset < len) {
338 // The data is wrapped
339 ssize_t rx1 = c->recv(c, buf->data + realoffset, buf->size - realoffset);
341 if(rx1 < buf->size - realoffset) {
345 // The channel might have been closed by the previous callback
350 ssize_t rx2 = c->recv(c, buf->data, len - (buf->size - realoffset));
358 return c->recv(c, buf->data + realoffset, len);
362 // Discard data from the buffer.
363 static ssize_t buffer_discard(struct buffer *buf, size_t len) {
364 if(buf->used < len) {
368 if(buf->size - buf->offset <= len) {
369 buf->offset -= buf->size;
372 if(buf->used == len) {
383 static void buffer_clear(struct buffer *buf) {
388 static bool buffer_set_size(struct buffer *buf, uint32_t minsize, uint32_t maxsize) {
389 if(maxsize < minsize) {
393 buf->maxsize = maxsize;
395 return buf->size >= minsize || buffer_resize(buf, minsize);
398 static void buffer_exit(struct buffer *buf) {
400 memset(buf, 0, sizeof(*buf));
403 static uint32_t buffer_free(const struct buffer *buf) {
404 return buf->maxsize > buf->used ? buf->maxsize - buf->used : 0;
407 // Connections are stored in a sorted list.
408 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
410 static int compare(const void *va, const void *vb) {
413 const struct utcp_connection *a = *(struct utcp_connection **)va;
414 const struct utcp_connection *b = *(struct utcp_connection **)vb;
418 int c = (int)a->src - (int)b->src;
424 c = (int)a->dst - (int)b->dst;
428 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
429 if(!utcp->nconnections) {
433 struct utcp_connection key = {
437 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
438 return match ? *match : NULL;
441 static void free_connection(struct utcp_connection *c) {
442 struct utcp *utcp = c->utcp;
443 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
447 int i = cp - utcp->connections;
448 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof(*cp));
449 utcp->nconnections--;
451 buffer_exit(&c->rcvbuf);
452 buffer_exit(&c->sndbuf);
456 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
457 // Check whether this combination of src and dst is free
460 if(find_connection(utcp, src, dst)) {
464 } else { // If src == 0, generate a random port number with the high bit set
465 if(utcp->nconnections >= 32767) {
470 src = rand() | 0x8000;
472 while(find_connection(utcp, src, dst)) {
477 // Allocate memory for the new connection
479 if(utcp->nconnections >= utcp->nallocated) {
480 if(!utcp->nallocated) {
481 utcp->nallocated = 4;
483 utcp->nallocated *= 2;
486 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof(*utcp->connections));
492 utcp->connections = new_array;
495 struct utcp_connection *c = calloc(1, sizeof(*c));
501 if(!buffer_set_size(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
506 if(!buffer_set_size(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
507 buffer_exit(&c->sndbuf);
512 // Fill in the details
521 c->snd.una = c->snd.iss;
522 c->snd.nxt = c->snd.iss + 1;
523 c->snd.last = c->snd.nxt;
524 c->snd.cwnd = (utcp->mss > 2190 ? 2 : utcp->mss > 1095 ? 3 : 4) * utcp->mss;
525 c->snd.ssthresh = ~0;
532 // Add it to the sorted list of connections
534 utcp->connections[utcp->nconnections++] = c;
535 qsort(utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
540 static inline uint32_t absdiff(uint32_t a, uint32_t b) {
548 // Update RTT variables. See RFC 6298.
549 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
551 debug(c, "invalid rtt\n");
559 c->rttvar = (c->rttvar * 3 + absdiff(c->srtt, rtt)) / 4;
560 c->srtt = (c->srtt * 7 + rtt) / 8;
563 c->rto = c->srtt + max(4 * c->rttvar, CLOCK_GRANULARITY);
565 if(c->rto > MAX_RTO) {
569 debug(c, "rtt %u srtt %u rttvar %u rto %u\n", rtt, c->srtt, c->rttvar, c->rto);
572 static void start_retransmit_timer(struct utcp_connection *c) {
573 clock_gettime(UTCP_CLOCK, &c->rtrx_timeout);
575 uint32_t rto = c->rto;
577 while(rto > USEC_PER_SEC) {
578 c->rtrx_timeout.tv_sec++;
582 c->rtrx_timeout.tv_nsec += rto * 1000;
584 if(c->rtrx_timeout.tv_nsec >= NSEC_PER_SEC) {
585 c->rtrx_timeout.tv_nsec -= NSEC_PER_SEC;
586 c->rtrx_timeout.tv_sec++;
589 debug(c, "rtrx_timeout %ld.%06lu\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_nsec);
592 static void stop_retransmit_timer(struct utcp_connection *c) {
593 timespec_clear(&c->rtrx_timeout);
594 debug(c, "rtrx_timeout cleared\n");
597 struct utcp_connection *utcp_connect_ex(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv, uint32_t flags) {
598 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
604 assert((flags & ~0x1f) == 0);
615 pkt.hdr.src = c->src;
616 pkt.hdr.dst = c->dst;
617 pkt.hdr.seq = c->snd.iss;
619 pkt.hdr.wnd = c->rcvbuf.maxsize;
621 pkt.hdr.aux = 0x0101;
625 pkt.init[3] = flags & 0x7;
627 set_state(c, SYN_SENT);
629 print_packet(c, "send", &pkt, sizeof(pkt));
630 utcp->send(utcp, &pkt, sizeof(pkt));
632 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
633 c->conn_timeout.tv_sec += utcp->timeout;
635 start_retransmit_timer(c);
640 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
641 return utcp_connect_ex(utcp, dst, recv, priv, UTCP_TCP);
644 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
645 if(c->reapable || c->state != SYN_RECEIVED) {
646 debug(c, "accept() called on invalid connection in state %s\n", c, strstate[c->state]);
650 debug(c, "accepted %p %p\n", c, recv, priv);
654 set_state(c, ESTABLISHED);
657 static void ack(struct utcp_connection *c, bool sendatleastone) {
658 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
659 int32_t cwndleft = is_reliable(c) ? min(c->snd.cwnd, c->snd.wnd) - seqdiff(c->snd.nxt, c->snd.una) : MAX_UNRELIABLE_SIZE;
665 } else if(cwndleft < left) {
668 if(!sendatleastone || cwndleft > c->utcp->mss) {
669 left -= left % c->utcp->mss;
673 debug(c, "cwndleft %d left %d\n", cwndleft, left);
675 if(!left && !sendatleastone) {
682 } *pkt = c->utcp->pkt;
684 pkt->hdr.src = c->src;
685 pkt->hdr.dst = c->dst;
686 pkt->hdr.ack = c->rcv.nxt;
687 pkt->hdr.wnd = is_reliable(c) ? c->rcvbuf.maxsize : 0;
692 uint32_t seglen = left > c->utcp->mss ? c->utcp->mss : left;
693 pkt->hdr.seq = c->snd.nxt;
695 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
697 c->snd.nxt += seglen;
700 if(!is_reliable(c)) {
708 if(seglen && fin_wanted(c, c->snd.nxt)) {
713 if(!c->rtt_start.tv_sec) {
714 // Start RTT measurement
715 clock_gettime(UTCP_CLOCK, &c->rtt_start);
716 c->rtt_seq = pkt->hdr.seq + seglen;
717 debug(c, "starting RTT measurement, expecting ack %u\n", c->rtt_seq);
720 print_packet(c, "send", pkt, sizeof(pkt->hdr) + seglen);
721 c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen);
723 if(left && !is_reliable(c)) {
724 pkt->hdr.wnd += seglen;
729 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
731 debug(c, "send() called on closed connection\n");
739 debug(c, "send() called on unconnected connection\n");
754 debug(c, "send() called on closed connection\n");
759 // Exit early if we have nothing to send.
770 // Check if we need to be able to buffer all data
772 if(c->flags & UTCP_NO_PARTIAL) {
773 if(len > buffer_free(&c->sndbuf)) {
774 if(len > c->sndbuf.maxsize) {
784 // Add data to send buffer.
787 len = buffer_put(&c->sndbuf, data, len);
788 } else if(c->state != SYN_SENT && c->state != SYN_RECEIVED) {
789 if(len > MAX_UNRELIABLE_SIZE || buffer_put(&c->sndbuf, data, len) != (ssize_t)len) {
808 // Don't send anything yet if the connection has not fully established yet
810 if(c->state == SYN_SENT || c->state == SYN_RECEIVED) {
816 if(!is_reliable(c)) {
817 c->snd.una = c->snd.nxt = c->snd.last;
818 buffer_discard(&c->sndbuf, c->sndbuf.used);
821 if(is_reliable(c) && !timespec_isset(&c->rtrx_timeout)) {
822 start_retransmit_timer(c);
825 if(is_reliable(c) && !timespec_isset(&c->conn_timeout)) {
826 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
827 c->conn_timeout.tv_sec += c->utcp->timeout;
833 static void swap_ports(struct hdr *hdr) {
834 uint16_t tmp = hdr->src;
839 static void fast_retransmit(struct utcp_connection *c) {
840 if(c->state == CLOSED || c->snd.last == c->snd.una) {
841 debug(c, "fast_retransmit() called but nothing to retransmit!\n");
845 struct utcp *utcp = c->utcp;
850 } *pkt = c->utcp->pkt;
852 pkt->hdr.src = c->src;
853 pkt->hdr.dst = c->dst;
854 pkt->hdr.wnd = c->rcvbuf.maxsize;
863 // Send unacked data again.
864 pkt->hdr.seq = c->snd.una;
865 pkt->hdr.ack = c->rcv.nxt;
867 uint32_t len = min(seqdiff(c->snd.last, c->snd.una), utcp->mss);
869 if(fin_wanted(c, c->snd.una + len)) {
874 buffer_copy(&c->sndbuf, pkt->data, 0, len);
875 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + len);
876 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
884 static void retransmit(struct utcp_connection *c) {
885 if(c->state == CLOSED || c->snd.last == c->snd.una) {
886 debug(c, "retransmit() called but nothing to retransmit!\n");
887 stop_retransmit_timer(c);
891 struct utcp *utcp = c->utcp;
893 if(utcp->retransmit) {
900 } *pkt = c->utcp->pkt;
902 pkt->hdr.src = c->src;
903 pkt->hdr.dst = c->dst;
904 pkt->hdr.wnd = c->rcvbuf.maxsize;
909 // Send our SYN again
910 pkt->hdr.seq = c->snd.iss;
913 pkt->hdr.aux = 0x0101;
917 pkt->data[3] = c->flags & 0x7;
918 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + 4);
919 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
924 pkt->hdr.seq = c->snd.nxt;
925 pkt->hdr.ack = c->rcv.nxt;
926 pkt->hdr.ctl = SYN | ACK;
927 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr));
928 utcp->send(utcp, pkt, sizeof(pkt->hdr));
936 // Send unacked data again.
937 pkt->hdr.seq = c->snd.una;
938 pkt->hdr.ack = c->rcv.nxt;
940 uint32_t len = min(seqdiff(c->snd.last, c->snd.una), utcp->mss);
942 if(fin_wanted(c, c->snd.una + len)) {
947 // RFC 5681 slow start after timeout
948 uint32_t flightsize = seqdiff(c->snd.nxt, c->snd.una);
949 c->snd.ssthresh = max(flightsize / 2, utcp->mss * 2); // eq. 4
950 c->snd.cwnd = utcp->mss;
953 buffer_copy(&c->sndbuf, pkt->data, 0, len);
954 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + len);
955 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
957 c->snd.nxt = c->snd.una + len;
964 // We shouldn't need to retransmit anything in this state.
968 stop_retransmit_timer(c);
972 start_retransmit_timer(c);
975 if(c->rto > MAX_RTO) {
979 c->rtt_start.tv_sec = 0; // invalidate RTT timer
980 c->dupack = 0; // cancel any ongoing fast recovery
986 /* Update receive buffer and SACK entries after consuming data.
990 * |.....0000..1111111111.....22222......3333|
993 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
994 * to remove data from the receive buffer. The idea is to substract "len"
995 * from the offset of all the SACK entries, and then remove/cut down entries
996 * that are shifted to before the start of the receive buffer.
998 * There are three cases:
999 * - the SACK entry is after ^, in that case just change the offset.
1000 * - the SACK entry starts before and ends after ^, so we have to
1001 * change both its offset and size.
1002 * - the SACK entry is completely before ^, in that case delete it.
1004 static void sack_consume(struct utcp_connection *c, size_t len) {
1005 debug(c, "sack_consume %lu\n", (unsigned long)len);
1007 if(len > c->rcvbuf.used) {
1008 debug(c, "all SACK entries consumed\n");
1009 c->sacks[0].len = 0;
1013 buffer_discard(&c->rcvbuf, len);
1015 for(int i = 0; i < NSACKS && c->sacks[i].len;) {
1016 if(len < c->sacks[i].offset) {
1017 c->sacks[i].offset -= len;
1019 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
1020 c->sacks[i].len -= len - c->sacks[i].offset;
1021 c->sacks[i].offset = 0;
1024 if(i < NSACKS - 1) {
1025 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
1026 c->sacks[NSACKS - 1].len = 0;
1028 c->sacks[i].len = 0;
1034 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
1035 debug(c, "SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
1039 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
1040 debug(c, "out of order packet, offset %u\n", offset);
1041 // Packet loss or reordering occured. Store the data in the buffer.
1042 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
1045 debug(c, "packet outside receive buffer, dropping\n");
1049 if((size_t)rxd < len) {
1050 debug(c, "packet partially outside receive buffer\n");
1054 // Make note of where we put it.
1055 for(int i = 0; i < NSACKS; i++) {
1056 if(!c->sacks[i].len) { // nothing to merge, add new entry
1057 debug(c, "new SACK entry %d\n", i);
1058 c->sacks[i].offset = offset;
1059 c->sacks[i].len = rxd;
1061 } else if(offset < c->sacks[i].offset) {
1062 if(offset + rxd < c->sacks[i].offset) { // insert before
1063 if(!c->sacks[NSACKS - 1].len) { // only if room left
1064 debug(c, "insert SACK entry at %d\n", i);
1065 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
1066 c->sacks[i].offset = offset;
1067 c->sacks[i].len = rxd;
1069 debug(c, "SACK entries full, dropping packet\n");
1074 debug(c, "merge with start of SACK entry at %d\n", i);
1075 c->sacks[i].offset = offset;
1078 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
1079 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
1080 debug(c, "merge with end of SACK entry at %d\n", i);
1081 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
1082 // TODO: handle potential merge with next entry
1089 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
1090 debug(c, "SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
1094 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
1096 ssize_t rxd = c->recv(c, data, len);
1098 if(rxd != (ssize_t)len) {
1099 // TODO: handle the application not accepting all data.
1104 // Check if we can process out-of-order data now.
1105 if(c->sacks[0].len && len >= c->sacks[0].offset) {
1106 debug(c, "incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
1108 if(len < c->sacks[0].offset + c->sacks[0].len) {
1109 size_t offset = len;
1110 len = c->sacks[0].offset + c->sacks[0].len;
1111 size_t remainder = len - offset;
1113 ssize_t rxd = buffer_call(c, &c->rcvbuf, offset, remainder);
1115 if(rxd != (ssize_t)remainder) {
1116 // TODO: handle the application not accepting all data.
1122 if(c->rcvbuf.used) {
1123 sack_consume(c, len);
1129 static void handle_unreliable(struct utcp_connection *c, const struct hdr *hdr, const void *data, size_t len) {
1130 // Fast path for unfragmented packets
1131 if(!hdr->wnd && !(hdr->ctl & MF)) {
1133 c->recv(c, data, len);
1136 c->rcv.nxt = hdr->seq + len;
1140 // Ensure reassembled packet are not larger than 64 kiB
1141 if(hdr->wnd >= MAX_UNRELIABLE_SIZE || hdr->wnd + len > MAX_UNRELIABLE_SIZE) {
1145 // Don't accept out of order fragments
1146 if(hdr->wnd && hdr->seq != c->rcv.nxt) {
1150 // Reset the receive buffer for the first fragment
1152 buffer_clear(&c->rcvbuf);
1155 ssize_t rxd = buffer_put_at(&c->rcvbuf, hdr->wnd, data, len);
1157 if(rxd != (ssize_t)len) {
1161 // Send the packet if it's the final fragment
1162 if(!(hdr->ctl & MF)) {
1163 buffer_call(c, &c->rcvbuf, 0, hdr->wnd + len);
1166 c->rcv.nxt = hdr->seq + len;
1169 static void handle_incoming_data(struct utcp_connection *c, const struct hdr *hdr, const void *data, size_t len) {
1170 if(!is_reliable(c)) {
1171 handle_unreliable(c, hdr, data, len);
1175 uint32_t offset = seqdiff(hdr->seq, c->rcv.nxt);
1178 handle_out_of_order(c, offset, data, len);
1180 handle_in_order(c, data, len);
1185 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
1186 const uint8_t *ptr = data;
1202 // Drop packets smaller than the header
1206 if(len < sizeof(hdr)) {
1207 print_packet(NULL, "recv", data, len);
1212 // Make a copy from the potentially unaligned data to a struct hdr
1214 memcpy(&hdr, ptr, sizeof(hdr));
1216 // Try to match the packet to an existing connection
1218 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
1219 print_packet(c, "recv", data, len);
1221 // Process the header
1226 // Drop packets with an unknown CTL flag
1228 if(hdr.ctl & ~(SYN | ACK | RST | FIN | MF)) {
1229 print_packet(NULL, "recv", data, len);
1234 // Check for auxiliary headers
1236 const uint8_t *init = NULL;
1238 uint16_t aux = hdr.aux;
1241 size_t auxlen = 4 * (aux >> 8) & 0xf;
1242 uint8_t auxtype = aux & 0xff;
1251 if(!(hdr.ctl & SYN) || auxlen != 4) {
1267 if(!(aux & 0x800)) {
1276 memcpy(&aux, ptr, 2);
1281 bool has_data = len || (hdr.ctl & (SYN | FIN));
1283 // Is it for a new connection?
1286 // Ignore RST packets
1292 // Is it a SYN packet and are we LISTENing?
1294 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1295 // If we don't want to accept it, send a RST back
1296 if((utcp->listen && !utcp->listen(utcp, hdr.dst))) {
1301 // Try to allocate memory, otherwise send a RST back
1302 c = allocate_connection(utcp, hdr.dst, hdr.src);
1309 // Parse auxilliary information
1316 c->flags = init[3] & 0x7;
1318 c->flags = UTCP_TCP;
1322 // Return SYN+ACK, go to SYN_RECEIVED state
1323 c->snd.wnd = hdr.wnd;
1324 c->rcv.irs = hdr.seq;
1325 c->rcv.nxt = c->rcv.irs + 1;
1326 set_state(c, SYN_RECEIVED);
1333 pkt.hdr.src = c->src;
1334 pkt.hdr.dst = c->dst;
1335 pkt.hdr.ack = c->rcv.irs + 1;
1336 pkt.hdr.seq = c->snd.iss;
1337 pkt.hdr.wnd = c->rcvbuf.maxsize;
1338 pkt.hdr.ctl = SYN | ACK;
1341 pkt.hdr.aux = 0x0101;
1345 pkt.data[3] = c->flags & 0x7;
1346 print_packet(c, "send", &pkt, sizeof(hdr) + 4);
1347 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1350 print_packet(c, "send", &pkt, sizeof(hdr));
1351 utcp->send(utcp, &pkt, sizeof(hdr));
1354 start_retransmit_timer(c);
1356 // No, we don't want your packets, send a RST back
1364 debug(c, "state %s\n", strstate[c->state]);
1366 // In case this is for a CLOSED connection, ignore the packet.
1367 // TODO: make it so incoming packets can never match a CLOSED connection.
1369 if(c->state == CLOSED) {
1370 debug(c, "got packet for closed connection\n");
1374 // It is for an existing connection.
1376 // 1. Drop invalid packets.
1378 // 1a. Drop packets that should not happen in our current state.
1399 // 1b. Discard data that is not in our receive window.
1401 if(is_reliable(c)) {
1404 if(c->state == SYN_SENT) {
1406 } else if(len == 0) {
1407 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1409 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1411 // cut already accepted front overlapping
1412 if(rcv_offset < 0) {
1413 acceptable = len > (size_t) - rcv_offset;
1418 hdr.seq -= rcv_offset;
1421 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1426 debug(c, "packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1428 // Ignore unacceptable RST packets.
1433 // Otherwise, continue processing.
1438 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1441 debug(c, "packet out of order, offset %u bytes", rcv_offset);
1447 c->snd.wnd = hdr.wnd; // TODO: move below
1449 // 1c. Drop packets with an invalid ACK.
1450 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1451 // (= snd.una + c->sndbuf.used).
1453 if(!is_reliable(c)) {
1454 if(hdr.ack != c->snd.last && c->state >= ESTABLISHED) {
1455 hdr.ack = c->snd.una;
1459 // 2. Handle RST packets
1464 if(!(hdr.ctl & ACK)) {
1468 // The peer has refused our connection.
1469 set_state(c, CLOSED);
1470 errno = ECONNREFUSED;
1473 c->recv(c, NULL, 0);
1476 if(c->poll && !c->reapable) {
1487 // We haven't told the application about this connection yet. Silently delete.
1499 // The peer has aborted our connection.
1500 set_state(c, CLOSED);
1504 c->recv(c, NULL, 0);
1507 if(c->poll && !c->reapable) {
1520 // As far as the application is concerned, the connection has already been closed.
1521 // If it has called utcp_close() already, we can immediately free this connection.
1527 // Otherwise, immediately move to the CLOSED state.
1528 set_state(c, CLOSED);
1541 if(!(hdr.ctl & ACK)) {
1546 // 3. Advance snd.una
1548 if(seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0) {
1549 debug(c, "packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1553 advanced = seqdiff(hdr.ack, c->snd.una);
1557 if(c->rtt_start.tv_sec) {
1558 if(c->rtt_seq == hdr.ack) {
1559 struct timespec now;
1560 clock_gettime(UTCP_CLOCK, &now);
1561 int32_t diff = timespec_diff_usec(&now, &c->rtt_start);
1562 update_rtt(c, diff);
1563 c->rtt_start.tv_sec = 0;
1564 } else if(c->rtt_seq < hdr.ack) {
1565 debug(c, "cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1566 c->rtt_start.tv_sec = 0;
1570 int32_t data_acked = advanced;
1578 // TODO: handle FIN as well.
1583 assert(data_acked >= 0);
1586 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1587 assert(data_acked <= bufused);
1591 buffer_discard(&c->sndbuf, data_acked);
1593 if(is_reliable(c)) {
1598 // Also advance snd.nxt if possible
1599 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1600 c->snd.nxt = hdr.ack;
1603 c->snd.una = hdr.ack;
1606 if(c->dupack >= 3) {
1607 debug(c, "fast recovery ended\n");
1608 c->snd.cwnd = c->snd.ssthresh;
1614 // Increase the congestion window according to RFC 5681
1615 if(c->snd.cwnd < c->snd.ssthresh) {
1616 c->snd.cwnd += min(advanced, utcp->mss); // eq. 2
1618 c->snd.cwnd += max(1, (utcp->mss * utcp->mss) / c->snd.cwnd); // eq. 3
1621 if(c->snd.cwnd > c->sndbuf.maxsize) {
1622 c->snd.cwnd = c->sndbuf.maxsize;
1627 // Check if we have sent a FIN that is now ACKed.
1630 if(c->snd.una == c->snd.last) {
1631 set_state(c, FIN_WAIT_2);
1637 if(c->snd.una == c->snd.last) {
1638 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
1639 c->conn_timeout.tv_sec += utcp->timeout;
1640 set_state(c, TIME_WAIT);
1649 if(!len && is_reliable(c) && c->snd.una != c->snd.last) {
1651 debug(c, "duplicate ACK %d\n", c->dupack);
1653 if(c->dupack == 3) {
1654 // RFC 5681 fast recovery
1655 debug(c, "fast recovery started\n", c->dupack);
1656 uint32_t flightsize = seqdiff(c->snd.nxt, c->snd.una);
1657 c->snd.ssthresh = max(flightsize / 2, utcp->mss * 2); // eq. 4
1658 c->snd.cwnd = min(c->snd.ssthresh + 3 * utcp->mss, c->sndbuf.maxsize);
1660 if(c->snd.cwnd > c->sndbuf.maxsize) {
1661 c->snd.cwnd = c->sndbuf.maxsize;
1667 } else if(c->dupack > 3) {
1668 c->snd.cwnd += utcp->mss;
1670 if(c->snd.cwnd > c->sndbuf.maxsize) {
1671 c->snd.cwnd = c->sndbuf.maxsize;
1677 // We got an ACK which indicates the other side did get one of our packets.
1678 // Reset the retransmission timer to avoid going to slow start,
1679 // but don't touch the connection timeout.
1680 start_retransmit_timer(c);
1687 if(c->snd.una == c->snd.last) {
1688 stop_retransmit_timer(c);
1689 timespec_clear(&c->conn_timeout);
1690 } else if(is_reliable(c)) {
1691 start_retransmit_timer(c);
1692 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
1693 c->conn_timeout.tv_sec += utcp->timeout;
1698 // 5. Process SYN stuff
1704 // This is a SYNACK. It should always have ACKed the SYN.
1709 c->rcv.irs = hdr.seq;
1710 c->rcv.nxt = hdr.seq + 1;
1714 set_state(c, FIN_WAIT_1);
1717 set_state(c, ESTABLISHED);
1723 // This is a retransmit of a SYN, send back the SYNACK.
1733 // This could be a retransmission. Ignore the SYN flag, but send an ACK back.
1744 // 6. Process new data
1746 if(c->state == SYN_RECEIVED) {
1747 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1752 // Are we still LISTENing?
1754 utcp->accept(c, c->src);
1757 if(c->state != ESTABLISHED) {
1758 set_state(c, CLOSED);
1768 // This should never happen.
1780 // We already closed the connection and are not interested in more data.
1790 // Ehm no, We should never receive more data after a FIN.
1800 handle_incoming_data(c, &hdr, ptr, len);
1803 // 7. Process FIN stuff
1805 if((hdr.ctl & FIN) && (!is_reliable(c) || hdr.seq + len == c->rcv.nxt)) {
1809 // This should never happen.
1816 set_state(c, CLOSE_WAIT);
1820 set_state(c, CLOSING);
1824 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
1825 c->conn_timeout.tv_sec += utcp->timeout;
1826 set_state(c, TIME_WAIT);
1833 // Ehm, no. We should never receive a second FIN.
1843 // FIN counts as one sequence number
1847 // Inform the application that the peer closed its end of the connection.
1850 c->recv(c, NULL, 0);
1854 // Now we send something back if:
1855 // - we received data, so we have to send back an ACK
1856 // -> sendatleastone = true
1857 // - or we got an ack, so we should maybe send a bit more data
1858 // -> sendatleastone = false
1860 if(is_reliable(c) || hdr.ctl & SYN || hdr.ctl & FIN) {
1875 hdr.ack = hdr.seq + len;
1877 hdr.ctl = RST | ACK;
1880 print_packet(c, "send", &hdr, sizeof(hdr));
1881 utcp->send(utcp, &hdr, sizeof(hdr));
1886 int utcp_shutdown(struct utcp_connection *c, int dir) {
1887 debug(c, "shutdown %d at %u\n", dir, c ? c->snd.last : 0);
1895 debug(c, "shutdown() called on closed connection\n");
1900 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1905 // TCP does not have a provision for stopping incoming packets.
1906 // The best we can do is to just ignore them.
1907 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1911 // The rest of the code deals with shutting down writes.
1912 if(dir == UTCP_SHUT_RD) {
1916 // Only process shutting down writes once.
1934 set_state(c, FIN_WAIT_1);
1942 set_state(c, CLOSING);
1955 if(!timespec_isset(&c->rtrx_timeout)) {
1956 start_retransmit_timer(c);
1962 static bool reset_connection(struct utcp_connection *c) {
1969 debug(c, "abort() called on closed connection\n");
1986 set_state(c, CLOSED);
1994 set_state(c, CLOSED);
2004 hdr.seq = c->snd.nxt;
2005 hdr.ack = c->rcv.nxt;
2009 print_packet(c, "send", &hdr, sizeof(hdr));
2010 c->utcp->send(c->utcp, &hdr, sizeof(hdr));
2014 // Closes all the opened connections
2015 void utcp_abort_all_connections(struct utcp *utcp) {
2021 for(int i = 0; i < utcp->nconnections; i++) {
2022 struct utcp_connection *c = utcp->connections[i];
2024 if(c->reapable || c->state == CLOSED) {
2028 utcp_recv_t old_recv = c->recv;
2029 utcp_poll_t old_poll = c->poll;
2031 reset_connection(c);
2035 old_recv(c, NULL, 0);
2038 if(old_poll && !c->reapable) {
2047 int utcp_close(struct utcp_connection *c) {
2048 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
2058 int utcp_abort(struct utcp_connection *c) {
2059 if(!reset_connection(c)) {
2068 * One call to this function will loop through all connections,
2069 * checking if something needs to be resent or not.
2070 * The return value is the time to the next timeout in milliseconds,
2071 * or maybe a negative value if the timeout is infinite.
2073 struct timespec utcp_timeout(struct utcp *utcp) {
2074 struct timespec now;
2075 clock_gettime(UTCP_CLOCK, &now);
2076 struct timespec next = {now.tv_sec + 3600, now.tv_nsec};
2078 for(int i = 0; i < utcp->nconnections; i++) {
2079 struct utcp_connection *c = utcp->connections[i];
2085 // delete connections that have been utcp_close()d.
2086 if(c->state == CLOSED) {
2088 debug(c, "reaping\n");
2096 if(timespec_isset(&c->conn_timeout) && timespec_lt(&c->conn_timeout, &now)) {
2101 c->recv(c, NULL, 0);
2104 if(c->poll && !c->reapable) {
2111 if(timespec_isset(&c->rtrx_timeout) && timespec_lt(&c->rtrx_timeout, &now)) {
2112 debug(c, "retransmitting after timeout\n");
2117 if((c->state == ESTABLISHED || c->state == CLOSE_WAIT) && c->do_poll) {
2119 uint32_t len = buffer_free(&c->sndbuf);
2124 } else if(c->state == CLOSED) {
2129 if(timespec_isset(&c->conn_timeout) && timespec_lt(&c->conn_timeout, &next)) {
2130 next = c->conn_timeout;
2133 if(timespec_isset(&c->rtrx_timeout) && timespec_lt(&c->rtrx_timeout, &next)) {
2134 next = c->rtrx_timeout;
2138 struct timespec diff;
2140 timespec_sub(&next, &now, &diff);
2145 bool utcp_is_active(struct utcp *utcp) {
2150 for(int i = 0; i < utcp->nconnections; i++)
2151 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
2158 struct utcp *utcp_init(utcp_accept_t accept, utcp_listen_t listen, utcp_send_t send, void *priv) {
2164 struct utcp *utcp = calloc(1, sizeof(*utcp));
2170 utcp_set_mtu(utcp, DEFAULT_MTU);
2177 if(!CLOCK_GRANULARITY) {
2178 struct timespec res;
2179 clock_getres(UTCP_CLOCK, &res);
2180 CLOCK_GRANULARITY = res.tv_sec * USEC_PER_SEC + res.tv_nsec / 1000;
2183 utcp->accept = accept;
2184 utcp->listen = listen;
2187 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
2192 void utcp_exit(struct utcp *utcp) {
2197 for(int i = 0; i < utcp->nconnections; i++) {
2198 struct utcp_connection *c = utcp->connections[i];
2202 c->recv(c, NULL, 0);
2205 if(c->poll && !c->reapable) {
2210 buffer_exit(&c->rcvbuf);
2211 buffer_exit(&c->sndbuf);
2215 free(utcp->connections);
2220 uint16_t utcp_get_mtu(struct utcp *utcp) {
2221 return utcp ? utcp->mtu : 0;
2224 uint16_t utcp_get_mss(struct utcp *utcp) {
2225 return utcp ? utcp->mss : 0;
2228 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
2233 if(mtu <= sizeof(struct hdr)) {
2237 if(mtu > utcp->mtu) {
2238 char *new = realloc(utcp->pkt, mtu + sizeof(struct hdr));
2248 utcp->mss = mtu - sizeof(struct hdr);
2251 void utcp_reset_timers(struct utcp *utcp) {
2256 struct timespec now, then;
2258 clock_gettime(UTCP_CLOCK, &now);
2262 then.tv_sec += utcp->timeout;
2264 for(int i = 0; i < utcp->nconnections; i++) {
2265 struct utcp_connection *c = utcp->connections[i];
2271 if(timespec_isset(&c->rtrx_timeout)) {
2272 c->rtrx_timeout = now;
2275 if(timespec_isset(&c->conn_timeout)) {
2276 c->conn_timeout = then;
2279 c->rtt_start.tv_sec = 0;
2281 if(c->rto > START_RTO) {
2287 int utcp_get_user_timeout(struct utcp *u) {
2288 return u ? u->timeout : 0;
2291 void utcp_set_user_timeout(struct utcp *u, int timeout) {
2293 u->timeout = timeout;
2297 size_t utcp_get_sndbuf(struct utcp_connection *c) {
2298 return c ? c->sndbuf.maxsize : 0;
2301 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
2311 return buffer_free(&c->sndbuf);
2318 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
2323 c->sndbuf.maxsize = size;
2325 if(c->sndbuf.maxsize != size) {
2326 c->sndbuf.maxsize = -1;
2329 c->do_poll = is_reliable(c) && buffer_free(&c->sndbuf);
2332 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
2333 return c ? c->rcvbuf.maxsize : 0;
2336 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
2337 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
2338 return buffer_free(&c->rcvbuf);
2344 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
2349 c->rcvbuf.maxsize = size;
2351 if(c->rcvbuf.maxsize != size) {
2352 c->rcvbuf.maxsize = -1;
2356 size_t utcp_get_sendq(struct utcp_connection *c) {
2357 return c->sndbuf.used;
2360 size_t utcp_get_recvq(struct utcp_connection *c) {
2361 return c->rcvbuf.used;
2364 bool utcp_get_nodelay(struct utcp_connection *c) {
2365 return c ? c->nodelay : false;
2368 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
2370 c->nodelay = nodelay;
2374 bool utcp_get_keepalive(struct utcp_connection *c) {
2375 return c ? c->keepalive : false;
2378 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
2380 c->keepalive = keepalive;
2384 size_t utcp_get_outq(struct utcp_connection *c) {
2385 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
2388 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
2394 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
2397 c->do_poll = is_reliable(c) && buffer_free(&c->sndbuf);
2401 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_listen_t listen) {
2403 utcp->accept = accept;
2404 utcp->listen = listen;
2408 void utcp_expect_data(struct utcp_connection *c, bool expect) {
2409 if(!c || c->reapable) {
2413 if(!(c->state == ESTABLISHED || c->state == FIN_WAIT_1 || c->state == FIN_WAIT_2)) {
2418 // If we expect data, start the connection timer.
2419 if(!timespec_isset(&c->conn_timeout)) {
2420 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
2421 c->conn_timeout.tv_sec += c->utcp->timeout;
2424 // If we want to cancel expecting data, only clear the timer when there is no unACKed data.
2425 if(c->snd.una == c->snd.last) {
2426 timespec_clear(&c->conn_timeout);
2431 void utcp_offline(struct utcp *utcp, bool offline) {
2432 struct timespec now;
2433 clock_gettime(UTCP_CLOCK, &now);
2435 for(int i = 0; i < utcp->nconnections; i++) {
2436 struct utcp_connection *c = utcp->connections[i];
2442 utcp_expect_data(c, offline);
2445 if(timespec_isset(&c->rtrx_timeout)) {
2446 c->rtrx_timeout = now;
2449 utcp->connections[i]->rtt_start.tv_sec = 0;
2451 if(c->rto > START_RTO) {
2458 void utcp_set_retransmit_cb(struct utcp *utcp, utcp_retransmit_t cb) {
2459 utcp->retransmit = cb;
2462 void utcp_set_clock_granularity(long granularity) {
2463 CLOCK_GRANULARITY = granularity;