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.
32 #include "utcp_priv.h"
47 #if defined(CLOCK_MONOTONIC_RAW) && defined(__x86_64__)
48 #define UTCP_CLOCK CLOCK_MONOTONIC_RAW
50 #define UTCP_CLOCK CLOCK_MONOTONIC
54 static void timespec_sub(const struct timespec *a, const struct timespec *b, struct timespec *r) {
55 r->tv_sec = a->tv_sec - b->tv_sec;
56 r->tv_nsec = a->tv_nsec - b->tv_nsec;
59 r->tv_sec--, r->tv_nsec += NSEC_PER_SEC;
63 static int32_t timespec_diff_usec(const struct timespec *a, const struct timespec *b) {
64 return (a->tv_sec - b->tv_sec) * 1000000 + (a->tv_nsec - b->tv_nsec) / 1000;
67 static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
68 if(a->tv_sec == b->tv_sec) {
69 return a->tv_nsec < b->tv_nsec;
71 return a->tv_sec < b->tv_sec;
75 static void timespec_clear(struct timespec *a) {
80 static bool timespec_isset(const struct timespec *a) {
84 static long CLOCK_GRANULARITY; // usec
86 static inline size_t min(size_t a, size_t b) {
90 static inline size_t max(size_t a, size_t b) {
97 #ifndef UTCP_DEBUG_DATALEN
98 #define UTCP_DEBUG_DATALEN 20
101 static void debug(struct utcp_connection *c, const char *format, ...) {
106 clock_gettime(CLOCK_REALTIME, &tv);
107 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);
109 va_start(ap, format);
110 len += vsnprintf(buf + len, sizeof(buf) - len, format, ap);
113 if(len > 0 && (size_t)len < sizeof(buf)) {
114 fwrite(buf, len, 1, stderr);
118 static void print_packet(struct utcp_connection *c, const char *dir, const void *pkt, size_t len) {
121 if(len < sizeof(hdr)) {
122 debug(c, "%s: short packet (%lu bytes)\n", dir, (unsigned long)len);
126 memcpy(&hdr, pkt, sizeof(hdr));
130 if(len > sizeof(hdr)) {
131 datalen = min(len - sizeof(hdr), UTCP_DEBUG_DATALEN);
137 const uint8_t *data = (uint8_t *)pkt + sizeof(hdr);
138 char str[datalen * 2 + 1];
141 for(uint32_t i = 0; i < datalen; i++) {
142 *p++ = "0123456789ABCDEF"[data[i] >> 4];
143 *p++ = "0123456789ABCDEF"[data[i] & 15];
148 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",
149 dir, (unsigned long)len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd, hdr.aux,
150 hdr.ctl & SYN ? "SYN" : "",
151 hdr.ctl & RST ? "RST" : "",
152 hdr.ctl & FIN ? "FIN" : "",
153 hdr.ctl & ACK ? "ACK" : "",
154 hdr.ctl & MF ? "MF" : "",
159 static void debug_cwnd(struct utcp_connection *c) {
160 debug(c, "snd.cwnd %u snd.ssthresh %u\n", c->snd.cwnd, ~c->snd.ssthresh ? c->snd.ssthresh : 0);
163 #define debug(...) do {} while(0)
164 #define print_packet(...) do {} while(0)
165 #define debug_cwnd(...) do {} while(0)
168 static void set_state(struct utcp_connection *c, enum state state) {
171 if(state == ESTABLISHED) {
172 timespec_clear(&c->conn_timeout);
175 debug(c, "state %s\n", strstate[state]);
178 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
179 if(seq != c->snd.last) {
194 static bool is_reliable(struct utcp_connection *c) {
195 return c->flags & UTCP_RELIABLE;
198 static int32_t seqdiff(uint32_t a, uint32_t b) {
203 static bool buffer_wraps(struct buffer *buf) {
204 return buf->size - buf->offset < buf->used;
207 static bool buffer_resize(struct buffer *buf, uint32_t newsize) {
208 char *newdata = realloc(buf->data, newsize);
216 if(buffer_wraps(buf)) {
217 // Shift the right part of the buffer until it hits the end of the new buffer.
221 // [345.........|........012]
222 uint32_t tailsize = buf->size - buf->offset;
223 uint32_t newoffset = newsize - tailsize;
224 memmove(buf->data + newoffset, buf->data + buf->offset, tailsize);
225 buf->offset = newoffset;
232 // Store data into the buffer
233 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
234 debug(NULL, "buffer_put_at %lu %lu %lu\n", (unsigned long)buf->used, (unsigned long)offset, (unsigned long)len);
236 // Ensure we don't store more than maxsize bytes in total
237 size_t required = offset + len;
239 if(required > buf->maxsize) {
240 if(offset >= buf->maxsize) {
244 len = buf->maxsize - offset;
245 required = buf->maxsize;
248 // Check if we need to resize the buffer
249 if(required > buf->size) {
250 size_t newsize = buf->size;
258 } while(newsize < required);
260 if(newsize > buf->maxsize) {
261 newsize = buf->maxsize;
264 if(!buffer_resize(buf, newsize)) {
269 uint32_t realoffset = buf->offset + offset;
271 if(buf->size - buf->offset <= offset) {
272 // The offset wrapped
273 realoffset -= buf->size;
276 if(buf->size - realoffset < len) {
277 // The new chunk of data must be wrapped
278 memcpy(buf->data + realoffset, data, buf->size - realoffset);
279 memcpy(buf->data, (char *)data + buf->size - realoffset, len - (buf->size - realoffset));
281 memcpy(buf->data + realoffset, data, len);
284 if(required > buf->used) {
285 buf->used = required;
291 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
292 return buffer_put_at(buf, buf->used, data, len);
295 // Copy data from the buffer without removing it.
296 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
297 // Ensure we don't copy more than is actually stored in the buffer
298 if(offset >= buf->used) {
302 if(buf->used - offset < len) {
303 len = buf->used - offset;
306 uint32_t realoffset = buf->offset + offset;
308 if(buf->size - buf->offset <= offset) {
309 // The offset wrapped
310 realoffset -= buf->size;
313 if(buf->size - realoffset < len) {
314 // The data is wrapped
315 memcpy(data, buf->data + realoffset, buf->size - realoffset);
316 memcpy((char *)data + buf->size - realoffset, buf->data, len - (buf->size - realoffset));
318 memcpy(data, buf->data + realoffset, len);
324 // Copy data from the buffer without removing it.
325 static ssize_t buffer_call(struct utcp_connection *c, struct buffer *buf, size_t offset, size_t len) {
330 // Ensure we don't copy more than is actually stored in the buffer
331 if(offset >= buf->used) {
335 if(buf->used - offset < len) {
336 len = buf->used - offset;
339 uint32_t realoffset = buf->offset + offset;
341 if(buf->size - buf->offset <= offset) {
342 // The offset wrapped
343 realoffset -= buf->size;
346 if(buf->size - realoffset < len) {
347 // The data is wrapped
348 ssize_t rx1 = c->recv(c, buf->data + realoffset, buf->size - realoffset);
350 if(rx1 < buf->size - realoffset) {
354 // The channel might have been closed by the previous callback
359 ssize_t rx2 = c->recv(c, buf->data, len - (buf->size - realoffset));
367 return c->recv(c, buf->data + realoffset, len);
371 // Discard data from the buffer.
372 static ssize_t buffer_discard(struct buffer *buf, size_t len) {
373 if(buf->used < len) {
377 if(buf->size - buf->offset <= len) {
378 buf->offset -= buf->size;
381 if(buf->used == len) {
392 static void buffer_clear(struct buffer *buf) {
397 static bool buffer_set_size(struct buffer *buf, uint32_t minsize, uint32_t maxsize) {
398 if(maxsize < minsize) {
402 buf->maxsize = maxsize;
404 return buf->size >= minsize || buffer_resize(buf, minsize);
407 static void buffer_exit(struct buffer *buf) {
409 memset(buf, 0, sizeof(*buf));
412 static uint32_t buffer_free(const struct buffer *buf) {
413 return buf->maxsize > buf->used ? buf->maxsize - buf->used : 0;
416 // Connections are stored in a sorted list.
417 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
419 static int compare(const void *va, const void *vb) {
422 const struct utcp_connection *a = *(struct utcp_connection **)va;
423 const struct utcp_connection *b = *(struct utcp_connection **)vb;
426 assert(a->src && b->src);
428 int c = (int)a->src - (int)b->src;
434 c = (int)a->dst - (int)b->dst;
438 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
439 if(!utcp->nconnections) {
443 struct utcp_connection key = {
447 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
448 return match ? *match : NULL;
451 static void free_connection(struct utcp_connection *c) {
452 struct utcp *utcp = c->utcp;
453 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
457 int i = cp - utcp->connections;
458 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof(*cp));
459 utcp->nconnections--;
461 buffer_exit(&c->rcvbuf);
462 buffer_exit(&c->sndbuf);
466 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
467 // Check whether this combination of src and dst is free
470 if(find_connection(utcp, src, dst)) {
474 } else { // If src == 0, generate a random port number with the high bit set
475 if(utcp->nconnections >= 32767) {
480 src = rand() | 0x8000;
482 while(find_connection(utcp, src, dst)) {
487 // Allocate memory for the new connection
489 if(utcp->nconnections >= utcp->nallocated) {
490 if(!utcp->nallocated) {
491 utcp->nallocated = 4;
493 utcp->nallocated *= 2;
496 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof(*utcp->connections));
502 utcp->connections = new_array;
505 struct utcp_connection *c = calloc(1, sizeof(*c));
511 if(!buffer_set_size(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
516 if(!buffer_set_size(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
517 buffer_exit(&c->sndbuf);
522 // Fill in the details
531 c->snd.una = c->snd.iss;
532 c->snd.nxt = c->snd.iss + 1;
533 c->snd.last = c->snd.nxt;
534 c->snd.cwnd = (utcp->mss > 2190 ? 2 : utcp->mss > 1095 ? 3 : 4) * utcp->mss;
535 c->snd.ssthresh = ~0;
542 // Add it to the sorted list of connections
544 utcp->connections[utcp->nconnections++] = c;
545 qsort(utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
550 static inline uint32_t absdiff(uint32_t a, uint32_t b) {
558 // Update RTT variables. See RFC 6298.
559 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
561 debug(c, "invalid rtt\n");
569 c->rttvar = (c->rttvar * 3 + absdiff(c->srtt, rtt)) / 4;
570 c->srtt = (c->srtt * 7 + rtt) / 8;
573 c->rto = c->srtt + max(4 * c->rttvar, CLOCK_GRANULARITY);
575 if(c->rto > MAX_RTO) {
579 debug(c, "rtt %u srtt %u rttvar %u rto %u\n", rtt, c->srtt, c->rttvar, c->rto);
582 static void start_retransmit_timer(struct utcp_connection *c) {
583 clock_gettime(UTCP_CLOCK, &c->rtrx_timeout);
585 uint32_t rto = c->rto;
587 while(rto > USEC_PER_SEC) {
588 c->rtrx_timeout.tv_sec++;
592 c->rtrx_timeout.tv_nsec += rto * 1000;
594 if(c->rtrx_timeout.tv_nsec >= NSEC_PER_SEC) {
595 c->rtrx_timeout.tv_nsec -= NSEC_PER_SEC;
596 c->rtrx_timeout.tv_sec++;
599 debug(c, "rtrx_timeout %ld.%06lu\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_nsec);
602 static void stop_retransmit_timer(struct utcp_connection *c) {
603 timespec_clear(&c->rtrx_timeout);
604 debug(c, "rtrx_timeout cleared\n");
607 struct utcp_connection *utcp_connect_ex(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv, uint32_t flags) {
608 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
614 assert((flags & ~0x1f) == 0);
625 pkt.hdr.src = c->src;
626 pkt.hdr.dst = c->dst;
627 pkt.hdr.seq = c->snd.iss;
629 pkt.hdr.wnd = c->rcvbuf.maxsize;
631 pkt.hdr.aux = 0x0101;
635 pkt.init[3] = flags & 0x7;
637 set_state(c, SYN_SENT);
639 print_packet(c, "send", &pkt, sizeof(pkt));
640 utcp->send(utcp, &pkt, sizeof(pkt));
642 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
643 c->conn_timeout.tv_sec += utcp->timeout;
645 start_retransmit_timer(c);
650 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
651 return utcp_connect_ex(utcp, dst, recv, priv, UTCP_TCP);
654 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
655 if(c->reapable || c->state != SYN_RECEIVED) {
656 debug(c, "accept() called on invalid connection in state %s\n", c, strstate[c->state]);
660 debug(c, "accepted %p %p\n", c, recv, priv);
664 set_state(c, ESTABLISHED);
667 static void ack(struct utcp_connection *c, bool sendatleastone) {
668 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
669 int32_t cwndleft = is_reliable(c) ? min(c->snd.cwnd, c->snd.wnd) - seqdiff(c->snd.nxt, c->snd.una) : MAX_UNRELIABLE_SIZE;
675 } else if(cwndleft < left) {
678 if(!sendatleastone || cwndleft > c->utcp->mss) {
679 left -= left % c->utcp->mss;
683 debug(c, "cwndleft %d left %d\n", cwndleft, left);
685 if(!left && !sendatleastone) {
692 } *pkt = c->utcp->pkt;
694 pkt->hdr.src = c->src;
695 pkt->hdr.dst = c->dst;
696 pkt->hdr.ack = c->rcv.nxt;
697 pkt->hdr.wnd = is_reliable(c) ? c->rcvbuf.maxsize : 0;
702 uint32_t seglen = left > c->utcp->mss ? c->utcp->mss : left;
703 pkt->hdr.seq = c->snd.nxt;
705 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
707 c->snd.nxt += seglen;
710 if(!is_reliable(c)) {
718 if(seglen && fin_wanted(c, c->snd.nxt)) {
723 if(!c->rtt_start.tv_sec && is_reliable(c)) {
724 // Start RTT measurement
725 clock_gettime(UTCP_CLOCK, &c->rtt_start);
726 c->rtt_seq = pkt->hdr.seq + seglen;
727 debug(c, "starting RTT measurement, expecting ack %u\n", c->rtt_seq);
730 print_packet(c, "send", pkt, sizeof(pkt->hdr) + seglen);
731 c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen);
733 if(left && !is_reliable(c)) {
734 pkt->hdr.wnd += seglen;
739 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
741 debug(c, "send() called on closed connection\n");
749 debug(c, "send() called on unconnected connection\n");
764 debug(c, "send() called on closed connection\n");
769 // Exit early if we have nothing to send.
780 // Check if we need to be able to buffer all data
782 if(c->flags & UTCP_NO_PARTIAL) {
783 if(len > buffer_free(&c->sndbuf)) {
784 if(len > c->sndbuf.maxsize) {
794 // Add data to send buffer.
797 len = buffer_put(&c->sndbuf, data, len);
798 } else if(c->state != SYN_SENT && c->state != SYN_RECEIVED) {
799 if(len > MAX_UNRELIABLE_SIZE || buffer_put(&c->sndbuf, data, len) != (ssize_t)len) {
818 // Don't send anything yet if the connection has not fully established yet
820 if(c->state == SYN_SENT || c->state == SYN_RECEIVED) {
826 if(!is_reliable(c)) {
827 c->snd.una = c->snd.nxt = c->snd.last;
828 buffer_discard(&c->sndbuf, c->sndbuf.used);
831 if(is_reliable(c) && !timespec_isset(&c->rtrx_timeout)) {
832 start_retransmit_timer(c);
835 if(is_reliable(c) && !timespec_isset(&c->conn_timeout)) {
836 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
837 c->conn_timeout.tv_sec += c->utcp->timeout;
843 static void swap_ports(struct hdr *hdr) {
844 uint16_t tmp = hdr->src;
849 static void fast_retransmit(struct utcp_connection *c) {
850 if(c->state == CLOSED || c->snd.last == c->snd.una) {
851 debug(c, "fast_retransmit() called but nothing to retransmit!\n");
855 struct utcp *utcp = c->utcp;
860 } *pkt = c->utcp->pkt;
862 pkt->hdr.src = c->src;
863 pkt->hdr.dst = c->dst;
864 pkt->hdr.wnd = c->rcvbuf.maxsize;
873 // Send unacked data again.
874 pkt->hdr.seq = c->snd.una;
875 pkt->hdr.ack = c->rcv.nxt;
877 uint32_t len = min(seqdiff(c->snd.last, c->snd.una), utcp->mss);
879 if(fin_wanted(c, c->snd.una + len)) {
884 buffer_copy(&c->sndbuf, pkt->data, 0, len);
885 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + len);
886 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
894 static void retransmit(struct utcp_connection *c) {
895 if(c->state == CLOSED || c->snd.last == c->snd.una) {
896 debug(c, "retransmit() called but nothing to retransmit!\n");
897 stop_retransmit_timer(c);
901 struct utcp *utcp = c->utcp;
903 if(utcp->retransmit) {
910 } *pkt = c->utcp->pkt;
912 pkt->hdr.src = c->src;
913 pkt->hdr.dst = c->dst;
914 pkt->hdr.wnd = c->rcvbuf.maxsize;
919 // Send our SYN again
920 pkt->hdr.seq = c->snd.iss;
923 pkt->hdr.aux = 0x0101;
927 pkt->data[3] = c->flags & 0x7;
928 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + 4);
929 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
934 pkt->hdr.seq = c->snd.nxt;
935 pkt->hdr.ack = c->rcv.nxt;
936 pkt->hdr.ctl = SYN | ACK;
937 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr));
938 utcp->send(utcp, pkt, sizeof(pkt->hdr));
946 // Send unacked data again.
947 pkt->hdr.seq = c->snd.una;
948 pkt->hdr.ack = c->rcv.nxt;
950 uint32_t len = min(seqdiff(c->snd.last, c->snd.una), utcp->mss);
952 if(fin_wanted(c, c->snd.una + len)) {
957 // RFC 5681 slow start after timeout
958 uint32_t flightsize = seqdiff(c->snd.nxt, c->snd.una);
959 c->snd.ssthresh = max(flightsize / 2, utcp->mss * 2); // eq. 4
960 c->snd.cwnd = utcp->mss;
963 buffer_copy(&c->sndbuf, pkt->data, 0, len);
964 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + len);
965 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
967 c->snd.nxt = c->snd.una + len;
974 // We shouldn't need to retransmit anything in this state.
978 stop_retransmit_timer(c);
982 start_retransmit_timer(c);
985 if(c->rto > MAX_RTO) {
989 c->rtt_start.tv_sec = 0; // invalidate RTT timer
990 c->dupack = 0; // cancel any ongoing fast recovery
996 /* Update receive buffer and SACK entries after consuming data.
1000 * |.....0000..1111111111.....22222......3333|
1003 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
1004 * to remove data from the receive buffer. The idea is to substract "len"
1005 * from the offset of all the SACK entries, and then remove/cut down entries
1006 * that are shifted to before the start of the receive buffer.
1008 * There are three cases:
1009 * - the SACK entry is after ^, in that case just change the offset.
1010 * - the SACK entry starts before and ends after ^, so we have to
1011 * change both its offset and size.
1012 * - the SACK entry is completely before ^, in that case delete it.
1014 static void sack_consume(struct utcp_connection *c, size_t len) {
1015 debug(c, "sack_consume %lu\n", (unsigned long)len);
1017 if(len > c->rcvbuf.used) {
1018 debug(c, "all SACK entries consumed\n");
1019 c->sacks[0].len = 0;
1023 buffer_discard(&c->rcvbuf, len);
1025 for(int i = 0; i < NSACKS && c->sacks[i].len;) {
1026 if(len < c->sacks[i].offset) {
1027 c->sacks[i].offset -= len;
1029 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
1030 c->sacks[i].len -= len - c->sacks[i].offset;
1031 c->sacks[i].offset = 0;
1034 if(i < NSACKS - 1) {
1035 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
1036 c->sacks[NSACKS - 1].len = 0;
1038 c->sacks[i].len = 0;
1044 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
1045 debug(c, "SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
1049 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
1050 debug(c, "out of order packet, offset %u\n", offset);
1051 // Packet loss or reordering occured. Store the data in the buffer.
1052 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
1055 debug(c, "packet outside receive buffer, dropping\n");
1059 if((size_t)rxd < len) {
1060 debug(c, "packet partially outside receive buffer\n");
1064 // Make note of where we put it.
1065 for(int i = 0; i < NSACKS; i++) {
1066 if(!c->sacks[i].len) { // nothing to merge, add new entry
1067 debug(c, "new SACK entry %d\n", i);
1068 c->sacks[i].offset = offset;
1069 c->sacks[i].len = rxd;
1071 } else if(offset < c->sacks[i].offset) {
1072 if(offset + rxd < c->sacks[i].offset) { // insert before
1073 if(!c->sacks[NSACKS - 1].len) { // only if room left
1074 debug(c, "insert SACK entry at %d\n", i);
1075 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
1076 c->sacks[i].offset = offset;
1077 c->sacks[i].len = rxd;
1079 debug(c, "SACK entries full, dropping packet\n");
1084 debug(c, "merge with start of SACK entry at %d\n", i);
1085 c->sacks[i].offset = offset;
1088 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
1089 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
1090 debug(c, "merge with end of SACK entry at %d\n", i);
1091 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
1092 // TODO: handle potential merge with next entry
1099 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
1100 debug(c, "SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
1104 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
1106 ssize_t rxd = c->recv(c, data, len);
1108 if(rxd != (ssize_t)len) {
1109 // TODO: handle the application not accepting all data.
1114 // Check if we can process out-of-order data now.
1115 if(c->sacks[0].len && len >= c->sacks[0].offset) {
1116 debug(c, "incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
1118 if(len < c->sacks[0].offset + c->sacks[0].len) {
1119 size_t offset = len;
1120 len = c->sacks[0].offset + c->sacks[0].len;
1121 size_t remainder = len - offset;
1123 ssize_t rxd = buffer_call(c, &c->rcvbuf, offset, remainder);
1125 if(rxd != (ssize_t)remainder) {
1126 // TODO: handle the application not accepting all data.
1132 if(c->rcvbuf.used) {
1133 sack_consume(c, len);
1139 static void handle_unreliable(struct utcp_connection *c, const struct hdr *hdr, const void *data, size_t len) {
1140 // Fast path for unfragmented packets
1141 if(!hdr->wnd && !(hdr->ctl & MF)) {
1143 c->recv(c, data, len);
1146 c->rcv.nxt = hdr->seq + len;
1150 // Ensure reassembled packet are not larger than 64 kiB
1151 if(hdr->wnd > MAX_UNRELIABLE_SIZE || hdr->wnd + len > MAX_UNRELIABLE_SIZE) {
1155 // Don't accept out of order fragments
1156 if(hdr->wnd && hdr->seq != c->rcv.nxt) {
1160 // Reset the receive buffer for the first fragment
1162 buffer_clear(&c->rcvbuf);
1165 ssize_t rxd = buffer_put_at(&c->rcvbuf, hdr->wnd, data, len);
1167 if(rxd != (ssize_t)len) {
1171 // Send the packet if it's the final fragment
1172 if(!(hdr->ctl & MF)) {
1173 buffer_call(c, &c->rcvbuf, 0, hdr->wnd + len);
1176 c->rcv.nxt = hdr->seq + len;
1179 static void handle_incoming_data(struct utcp_connection *c, const struct hdr *hdr, const void *data, size_t len) {
1180 if(!is_reliable(c)) {
1181 handle_unreliable(c, hdr, data, len);
1185 uint32_t offset = seqdiff(hdr->seq, c->rcv.nxt);
1188 handle_out_of_order(c, offset, data, len);
1190 handle_in_order(c, data, len);
1195 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
1196 const uint8_t *ptr = data;
1212 // Drop packets smaller than the header
1216 if(len < sizeof(hdr)) {
1217 print_packet(NULL, "recv", data, len);
1222 // Make a copy from the potentially unaligned data to a struct hdr
1224 memcpy(&hdr, ptr, sizeof(hdr));
1226 // Try to match the packet to an existing connection
1228 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
1229 print_packet(c, "recv", data, len);
1231 // Process the header
1236 // Drop packets with an unknown CTL flag
1238 if(hdr.ctl & ~(SYN | ACK | RST | FIN | MF)) {
1239 print_packet(NULL, "recv", data, len);
1244 // Check for auxiliary headers
1246 const uint8_t *init = NULL;
1248 uint16_t aux = hdr.aux;
1251 size_t auxlen = 4 * (aux >> 8) & 0xf;
1252 uint8_t auxtype = aux & 0xff;
1261 if(!(hdr.ctl & SYN) || auxlen != 4) {
1277 if(!(aux & 0x800)) {
1286 memcpy(&aux, ptr, 2);
1291 bool has_data = len || (hdr.ctl & (SYN | FIN));
1293 // Is it for a new connection?
1296 // Ignore RST packets
1302 // Is it a SYN packet and are we LISTENing?
1304 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1305 // If we don't want to accept it, send a RST back
1306 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
1311 // Try to allocate memory, otherwise send a RST back
1312 c = allocate_connection(utcp, hdr.dst, hdr.src);
1319 // Parse auxilliary information
1326 c->flags = init[3] & 0x7;
1328 c->flags = UTCP_TCP;
1332 // Return SYN+ACK, go to SYN_RECEIVED state
1333 c->snd.wnd = hdr.wnd;
1334 c->rcv.irs = hdr.seq;
1335 c->rcv.nxt = c->rcv.irs + 1;
1336 set_state(c, SYN_RECEIVED);
1343 pkt.hdr.src = c->src;
1344 pkt.hdr.dst = c->dst;
1345 pkt.hdr.ack = c->rcv.irs + 1;
1346 pkt.hdr.seq = c->snd.iss;
1347 pkt.hdr.wnd = c->rcvbuf.maxsize;
1348 pkt.hdr.ctl = SYN | ACK;
1351 pkt.hdr.aux = 0x0101;
1355 pkt.data[3] = c->flags & 0x7;
1356 print_packet(c, "send", &pkt, sizeof(hdr) + 4);
1357 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1360 print_packet(c, "send", &pkt, sizeof(hdr));
1361 utcp->send(utcp, &pkt, sizeof(hdr));
1364 start_retransmit_timer(c);
1366 // No, we don't want your packets, send a RST back
1374 debug(c, "state %s\n", strstate[c->state]);
1376 // In case this is for a CLOSED connection, ignore the packet.
1377 // TODO: make it so incoming packets can never match a CLOSED connection.
1379 if(c->state == CLOSED) {
1380 debug(c, "got packet for closed connection\n");
1384 // It is for an existing connection.
1386 // 1. Drop invalid packets.
1388 // 1a. Drop packets that should not happen in our current state.
1409 // 1b. Discard data that is not in our receive window.
1411 if(is_reliable(c)) {
1414 if(c->state == SYN_SENT) {
1416 } else if(len == 0) {
1417 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1419 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1421 // cut already accepted front overlapping
1422 if(rcv_offset < 0) {
1423 acceptable = len > (size_t) - rcv_offset;
1428 hdr.seq -= rcv_offset;
1431 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1436 debug(c, "packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1438 // Ignore unacceptable RST packets.
1443 // Otherwise, continue processing.
1448 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1451 debug(c, "packet out of order, offset %u bytes", rcv_offset);
1457 c->snd.wnd = hdr.wnd; // TODO: move below
1459 // 1c. Drop packets with an invalid ACK.
1460 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1461 // (= snd.una + c->sndbuf.used).
1463 if(!is_reliable(c)) {
1464 if(hdr.ack != c->snd.last && c->state >= ESTABLISHED) {
1465 hdr.ack = c->snd.una;
1469 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
1470 debug(c, "packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1472 // Ignore unacceptable RST packets.
1480 // 2. Handle RST packets
1485 if(!(hdr.ctl & ACK)) {
1489 // The peer has refused our connection.
1490 set_state(c, CLOSED);
1491 errno = ECONNREFUSED;
1494 c->recv(c, NULL, 0);
1497 if(c->poll && !c->reapable) {
1508 // We haven't told the application about this connection yet. Silently delete.
1520 // The peer has aborted our connection.
1521 set_state(c, CLOSED);
1525 c->recv(c, NULL, 0);
1528 if(c->poll && !c->reapable) {
1541 // As far as the application is concerned, the connection has already been closed.
1542 // If it has called utcp_close() already, we can immediately free this connection.
1548 // Otherwise, immediately move to the CLOSED state.
1549 set_state(c, CLOSED);
1562 if(!(hdr.ctl & ACK)) {
1567 // 3. Advance snd.una
1569 advanced = seqdiff(hdr.ack, c->snd.una);
1573 if(c->rtt_start.tv_sec) {
1574 if(c->rtt_seq == hdr.ack) {
1575 struct timespec now;
1576 clock_gettime(UTCP_CLOCK, &now);
1577 int32_t diff = timespec_diff_usec(&now, &c->rtt_start);
1578 update_rtt(c, diff);
1579 c->rtt_start.tv_sec = 0;
1580 } else if(c->rtt_seq < hdr.ack) {
1581 debug(c, "cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1582 c->rtt_start.tv_sec = 0;
1586 int32_t data_acked = advanced;
1594 // TODO: handle FIN as well.
1599 assert(data_acked >= 0);
1602 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1603 assert(data_acked <= bufused);
1607 buffer_discard(&c->sndbuf, data_acked);
1609 if(is_reliable(c)) {
1614 // Also advance snd.nxt if possible
1615 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1616 c->snd.nxt = hdr.ack;
1619 c->snd.una = hdr.ack;
1622 if(c->dupack >= 3) {
1623 debug(c, "fast recovery ended\n");
1624 c->snd.cwnd = c->snd.ssthresh;
1630 // Increase the congestion window according to RFC 5681
1631 if(c->snd.cwnd < c->snd.ssthresh) {
1632 c->snd.cwnd += min(advanced, utcp->mss); // eq. 2
1634 c->snd.cwnd += max(1, (utcp->mss * utcp->mss) / c->snd.cwnd); // eq. 3
1637 if(c->snd.cwnd > c->sndbuf.maxsize) {
1638 c->snd.cwnd = c->sndbuf.maxsize;
1643 // Check if we have sent a FIN that is now ACKed.
1646 if(c->snd.una == c->snd.last) {
1647 set_state(c, FIN_WAIT_2);
1653 if(c->snd.una == c->snd.last) {
1654 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
1655 c->conn_timeout.tv_sec += utcp->timeout;
1656 set_state(c, TIME_WAIT);
1665 if(!len && is_reliable(c) && c->snd.una != c->snd.last) {
1667 debug(c, "duplicate ACK %d\n", c->dupack);
1669 if(c->dupack == 3) {
1670 // RFC 5681 fast recovery
1671 debug(c, "fast recovery started\n", c->dupack);
1672 uint32_t flightsize = seqdiff(c->snd.nxt, c->snd.una);
1673 c->snd.ssthresh = max(flightsize / 2, utcp->mss * 2); // eq. 4
1674 c->snd.cwnd = min(c->snd.ssthresh + 3 * utcp->mss, c->sndbuf.maxsize);
1676 if(c->snd.cwnd > c->sndbuf.maxsize) {
1677 c->snd.cwnd = c->sndbuf.maxsize;
1683 } else if(c->dupack > 3) {
1684 c->snd.cwnd += utcp->mss;
1686 if(c->snd.cwnd > c->sndbuf.maxsize) {
1687 c->snd.cwnd = c->sndbuf.maxsize;
1693 // We got an ACK which indicates the other side did get one of our packets.
1694 // Reset the retransmission timer to avoid going to slow start,
1695 // but don't touch the connection timeout.
1696 start_retransmit_timer(c);
1703 if(c->snd.una == c->snd.last) {
1704 stop_retransmit_timer(c);
1705 timespec_clear(&c->conn_timeout);
1706 } else if(is_reliable(c)) {
1707 start_retransmit_timer(c);
1708 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
1709 c->conn_timeout.tv_sec += utcp->timeout;
1714 // 5. Process SYN stuff
1720 // This is a SYNACK. It should always have ACKed the SYN.
1725 c->rcv.irs = hdr.seq;
1726 c->rcv.nxt = hdr.seq + 1;
1730 set_state(c, FIN_WAIT_1);
1733 set_state(c, ESTABLISHED);
1739 // This is a retransmit of a SYN, send back the SYNACK.
1749 // This could be a retransmission. Ignore the SYN flag, but send an ACK back.
1760 // 6. Process new data
1762 if(c->state == SYN_RECEIVED) {
1763 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1768 // Are we still LISTENing?
1770 utcp->accept(c, c->src);
1773 if(c->state != ESTABLISHED) {
1774 set_state(c, CLOSED);
1784 // This should never happen.
1799 // Ehm no, We should never receive more data after a FIN.
1809 handle_incoming_data(c, &hdr, ptr, len);
1812 // 7. Process FIN stuff
1814 if((hdr.ctl & FIN) && (!is_reliable(c) || hdr.seq + len == c->rcv.nxt)) {
1818 // This should never happen.
1825 set_state(c, CLOSE_WAIT);
1829 set_state(c, CLOSING);
1833 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
1834 c->conn_timeout.tv_sec += utcp->timeout;
1835 set_state(c, TIME_WAIT);
1842 // Ehm, no. We should never receive a second FIN.
1852 // FIN counts as one sequence number
1856 // Inform the application that the peer closed its end of the connection.
1859 c->recv(c, NULL, 0);
1863 // Now we send something back if:
1864 // - we received data, so we have to send back an ACK
1865 // -> sendatleastone = true
1866 // - or we got an ack, so we should maybe send a bit more data
1867 // -> sendatleastone = false
1869 if(is_reliable(c) || hdr.ctl & SYN || hdr.ctl & FIN) {
1884 hdr.ack = hdr.seq + len;
1886 hdr.ctl = RST | ACK;
1889 print_packet(c, "send", &hdr, sizeof(hdr));
1890 utcp->send(utcp, &hdr, sizeof(hdr));
1895 int utcp_shutdown(struct utcp_connection *c, int dir) {
1896 debug(c, "shutdown %d at %u\n", dir, c ? c->snd.last : 0);
1904 debug(c, "shutdown() called on closed connection\n");
1909 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1914 // TCP does not have a provision for stopping incoming packets.
1915 // The best we can do is to just ignore them.
1916 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1920 // The rest of the code deals with shutting down writes.
1921 if(dir == UTCP_SHUT_RD) {
1925 // Only process shutting down writes once.
1943 set_state(c, FIN_WAIT_1);
1951 set_state(c, CLOSING);
1964 if(!timespec_isset(&c->rtrx_timeout)) {
1965 start_retransmit_timer(c);
1971 static bool reset_connection(struct utcp_connection *c) {
1978 debug(c, "abort() called on closed connection\n");
1995 set_state(c, CLOSED);
2003 set_state(c, CLOSED);
2013 hdr.seq = c->snd.nxt;
2018 print_packet(c, "send", &hdr, sizeof(hdr));
2019 c->utcp->send(c->utcp, &hdr, sizeof(hdr));
2023 // Closes all the opened connections
2024 void utcp_abort_all_connections(struct utcp *utcp) {
2030 for(int i = 0; i < utcp->nconnections; i++) {
2031 struct utcp_connection *c = utcp->connections[i];
2033 if(c->reapable || c->state == CLOSED) {
2037 utcp_recv_t old_recv = c->recv;
2038 utcp_poll_t old_poll = c->poll;
2040 reset_connection(c);
2044 old_recv(c, NULL, 0);
2047 if(old_poll && !c->reapable) {
2056 int utcp_close(struct utcp_connection *c) {
2057 if(c->rcvbuf.used) {
2058 fprintf(stderr, "UTCP channel closed with stuff in receive buffer\n");
2059 return reset_connection(c) ? 0 : -1;
2062 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
2072 int utcp_abort(struct utcp_connection *c) {
2073 if(!reset_connection(c)) {
2082 * One call to this function will loop through all connections,
2083 * checking if something needs to be resent or not.
2084 * The return value is the time to the next timeout in milliseconds,
2085 * or maybe a negative value if the timeout is infinite.
2087 struct timespec utcp_timeout(struct utcp *utcp) {
2088 struct timespec now;
2089 clock_gettime(UTCP_CLOCK, &now);
2090 struct timespec next = {now.tv_sec + 3600, now.tv_nsec};
2092 for(int i = 0; i < utcp->nconnections; i++) {
2093 struct utcp_connection *c = utcp->connections[i];
2099 // delete connections that have been utcp_close()d.
2100 if(c->state == CLOSED) {
2102 debug(c, "reaping\n");
2110 if(timespec_isset(&c->conn_timeout) && timespec_lt(&c->conn_timeout, &now)) {
2115 c->recv(c, NULL, 0);
2118 if(c->poll && !c->reapable) {
2125 if(timespec_isset(&c->rtrx_timeout) && timespec_lt(&c->rtrx_timeout, &now)) {
2126 debug(c, "retransmitting after timeout\n");
2131 if((c->state == ESTABLISHED || c->state == CLOSE_WAIT) && c->do_poll) {
2133 uint32_t len = buffer_free(&c->sndbuf);
2138 } else if(c->state == CLOSED) {
2143 if(timespec_isset(&c->conn_timeout) && timespec_lt(&c->conn_timeout, &next)) {
2144 next = c->conn_timeout;
2147 if(timespec_isset(&c->rtrx_timeout) && timespec_lt(&c->rtrx_timeout, &next)) {
2148 next = c->rtrx_timeout;
2152 struct timespec diff;
2154 timespec_sub(&next, &now, &diff);
2159 bool utcp_is_active(struct utcp *utcp) {
2164 for(int i = 0; i < utcp->nconnections; i++)
2165 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
2172 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
2178 struct utcp *utcp = calloc(1, sizeof(*utcp));
2184 utcp_set_mtu(utcp, DEFAULT_MTU);
2191 if(!CLOCK_GRANULARITY) {
2192 struct timespec res;
2193 clock_getres(UTCP_CLOCK, &res);
2194 CLOCK_GRANULARITY = res.tv_sec * USEC_PER_SEC + res.tv_nsec / 1000;
2197 utcp->accept = accept;
2198 utcp->pre_accept = pre_accept;
2201 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
2206 void utcp_exit(struct utcp *utcp) {
2211 for(int i = 0; i < utcp->nconnections; i++) {
2212 struct utcp_connection *c = utcp->connections[i];
2216 c->recv(c, NULL, 0);
2219 if(c->poll && !c->reapable) {
2224 buffer_exit(&c->rcvbuf);
2225 buffer_exit(&c->sndbuf);
2229 free(utcp->connections);
2234 uint16_t utcp_get_mtu(struct utcp *utcp) {
2235 return utcp ? utcp->mtu : 0;
2238 uint16_t utcp_get_mss(struct utcp *utcp) {
2239 return utcp ? utcp->mss : 0;
2242 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
2247 if(mtu <= sizeof(struct hdr)) {
2251 if(mtu > utcp->mtu) {
2252 char *new = realloc(utcp->pkt, mtu + sizeof(struct hdr));
2262 utcp->mss = mtu - sizeof(struct hdr);
2265 void utcp_reset_timers(struct utcp *utcp) {
2270 struct timespec now, then;
2272 clock_gettime(UTCP_CLOCK, &now);
2276 then.tv_sec += utcp->timeout;
2278 for(int i = 0; i < utcp->nconnections; i++) {
2279 struct utcp_connection *c = utcp->connections[i];
2285 if(timespec_isset(&c->rtrx_timeout)) {
2286 c->rtrx_timeout = now;
2289 if(timespec_isset(&c->conn_timeout)) {
2290 c->conn_timeout = then;
2293 c->rtt_start.tv_sec = 0;
2295 if(c->rto > START_RTO) {
2301 int utcp_get_user_timeout(struct utcp *u) {
2302 return u ? u->timeout : 0;
2305 void utcp_set_user_timeout(struct utcp *u, int timeout) {
2307 u->timeout = timeout;
2311 size_t utcp_get_sndbuf(struct utcp_connection *c) {
2312 return c ? c->sndbuf.maxsize : 0;
2315 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
2325 return buffer_free(&c->sndbuf);
2332 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
2337 c->sndbuf.maxsize = size;
2339 if(c->sndbuf.maxsize != size) {
2340 c->sndbuf.maxsize = -1;
2343 c->do_poll = is_reliable(c) && buffer_free(&c->sndbuf);
2346 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
2347 return c ? c->rcvbuf.maxsize : 0;
2350 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
2351 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
2352 return buffer_free(&c->rcvbuf);
2358 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
2363 c->rcvbuf.maxsize = size;
2365 if(c->rcvbuf.maxsize != size) {
2366 c->rcvbuf.maxsize = -1;
2370 size_t utcp_get_sendq(struct utcp_connection *c) {
2371 return c->sndbuf.used;
2374 size_t utcp_get_recvq(struct utcp_connection *c) {
2375 return c->rcvbuf.used;
2378 bool utcp_get_nodelay(struct utcp_connection *c) {
2379 return c ? c->nodelay : false;
2382 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
2384 c->nodelay = nodelay;
2388 bool utcp_get_keepalive(struct utcp_connection *c) {
2389 return c ? c->keepalive : false;
2392 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
2394 c->keepalive = keepalive;
2398 size_t utcp_get_outq(struct utcp_connection *c) {
2399 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
2402 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
2408 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
2411 c->do_poll = is_reliable(c) && buffer_free(&c->sndbuf);
2415 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
2417 utcp->accept = accept;
2418 utcp->pre_accept = pre_accept;
2422 void utcp_expect_data(struct utcp_connection *c, bool expect) {
2423 if(!c || c->reapable) {
2427 if(!(c->state == ESTABLISHED || c->state == FIN_WAIT_1 || c->state == FIN_WAIT_2)) {
2432 // If we expect data, start the connection timer.
2433 if(!timespec_isset(&c->conn_timeout)) {
2434 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
2435 c->conn_timeout.tv_sec += c->utcp->timeout;
2438 // If we want to cancel expecting data, only clear the timer when there is no unACKed data.
2439 if(c->snd.una == c->snd.last) {
2440 timespec_clear(&c->conn_timeout);
2445 void utcp_offline(struct utcp *utcp, bool offline) {
2446 struct timespec now;
2447 clock_gettime(UTCP_CLOCK, &now);
2449 for(int i = 0; i < utcp->nconnections; i++) {
2450 struct utcp_connection *c = utcp->connections[i];
2456 utcp_expect_data(c, offline);
2459 if(timespec_isset(&c->rtrx_timeout)) {
2460 c->rtrx_timeout = now;
2463 utcp->connections[i]->rtt_start.tv_sec = 0;
2465 if(c->rto > START_RTO) {
2472 void utcp_set_retransmit_cb(struct utcp *utcp, utcp_retransmit_t cb) {
2473 utcp->retransmit = cb;
2476 void utcp_set_clock_granularity(long granularity) {
2477 CLOCK_GRANULARITY = granularity;