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.
31 #include <sys/socket.h>
34 #include "utcp_priv.h"
49 #define timersub(a, b, r)\
51 (r)->tv_sec = (a)->tv_sec - (b)->tv_sec;\
52 (r)->tv_usec = (a)->tv_usec - (b)->tv_usec;\
54 (r)->tv_sec--, (r)->tv_usec += USEC_PER_SEC;\
58 static inline size_t min(size_t a, size_t b) {
62 static inline size_t max(size_t a, size_t b) {
69 #ifndef UTCP_DEBUG_DATALEN
70 #define UTCP_DEBUG_DATALEN 20
73 static void debug(struct utcp_connection *c, const char *format, ...) {
78 clock_gettime(CLOCK_REALTIME, &tv);
79 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);
82 len += vsnprintf(buf + len, sizeof(buf) - len, format, ap);
85 if(len > 0 && (size_t)len < sizeof(buf)) {
86 fwrite(buf, len, 1, stderr);
90 static void print_packet(struct utcp_connection *c, const char *dir, const void *pkt, size_t len) {
93 if(len < sizeof(hdr)) {
94 debug(c, "%s: short packet (%lu bytes)\n", dir, (unsigned long)len);
98 memcpy(&hdr, pkt, sizeof(hdr));
102 if(len > sizeof(hdr)) {
103 datalen = min(len - sizeof(hdr), UTCP_DEBUG_DATALEN);
109 const uint8_t *data = (uint8_t *)pkt + sizeof(hdr);
110 char str[datalen * 2 + 1];
113 for(uint32_t i = 0; i < datalen; i++) {
114 *p++ = "0123456789ABCDEF"[data[i] >> 4];
115 *p++ = "0123456789ABCDEF"[data[i] & 15];
120 debug(c, "%s: len %lu src %u dst %u seq %u ack %u wnd %u aux %x ctl %s%s%s%s data %s\n",
121 dir, (unsigned long)len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd, hdr.aux,
122 hdr.ctl & SYN ? "SYN" : "",
123 hdr.ctl & RST ? "RST" : "",
124 hdr.ctl & FIN ? "FIN" : "",
125 hdr.ctl & ACK ? "ACK" : "",
130 static void debug_cwnd(struct utcp_connection *c) {
131 debug(c, "snd.cwnd %u snd.ssthresh %u\n", c->snd.cwnd, ~c->snd.ssthresh ? c->snd.ssthresh : 0);
134 #define debug(...) do {} while(0)
135 #define print_packet(...) do {} while(0)
136 #define debug_cwnd(...) do {} while(0)
139 static void set_state(struct utcp_connection *c, enum state state) {
142 if(state == ESTABLISHED) {
143 timerclear(&c->conn_timeout);
146 debug(c, "state %s\n", strstate[state]);
149 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
150 if(seq != c->snd.last) {
165 static bool is_reliable(struct utcp_connection *c) {
166 return c->flags & UTCP_RELIABLE;
169 static int32_t seqdiff(uint32_t a, uint32_t b) {
174 static bool buffer_wraps(struct buffer *buf) {
175 return buf->size - buf->offset < buf->used;
178 static bool buffer_resize(struct buffer *buf, uint32_t newsize) {
179 char *newdata = realloc(buf->data, newsize);
187 if(buffer_wraps(buf)) {
188 // Shift the right part of the buffer until it hits the end of the new buffer.
192 // [345.........|........012]
193 uint32_t tailsize = buf->size - buf->offset;
194 uint32_t newoffset = newsize - tailsize;
195 memmove(buf + newoffset, buf + buf->offset, tailsize);
196 buf->offset = newoffset;
203 // Store data into the buffer
204 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
205 debug(NULL, "buffer_put_at %lu %lu %lu\n", (unsigned long)buf->used, (unsigned long)offset, (unsigned long)len);
207 // Ensure we don't store more than maxsize bytes in total
208 size_t required = offset + len;
210 if(required > buf->maxsize) {
211 if(offset >= buf->maxsize) {
215 len = buf->maxsize - offset;
216 required = buf->maxsize;
219 // Check if we need to resize the buffer
220 if(required > buf->size) {
221 size_t newsize = buf->size;
229 } while(newsize < required);
231 if(newsize > buf->maxsize) {
232 newsize = buf->maxsize;
235 if(!buffer_resize(buf, newsize)) {
240 uint32_t realoffset = buf->offset + offset;
242 if(buf->size - buf->offset < offset) {
243 // The offset wrapped
244 realoffset -= buf->size;
247 if(buf->size - realoffset < len) {
248 // The new chunk of data must be wrapped
249 memcpy(buf->data + realoffset, data, buf->size - realoffset);
250 memcpy(buf->data, (char *)data + buf->size - realoffset, len - (buf->size - realoffset));
252 memcpy(buf->data + realoffset, data, len);
255 if(required > buf->used) {
256 buf->used = required;
262 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
263 return buffer_put_at(buf, buf->used, data, len);
266 // Copy data from the buffer without removing it.
267 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
268 // Ensure we don't copy more than is actually stored in the buffer
269 if(offset >= buf->used) {
273 if(buf->used - offset < len) {
274 len = buf->used - offset;
277 uint32_t realoffset = buf->offset + offset;
279 if(buf->size - buf->offset < offset) {
280 // The offset wrapped
281 realoffset -= buf->size;
284 if(buf->size - realoffset < len) {
285 // The data is wrapped
286 memcpy(data, buf->data + realoffset, buf->size - realoffset);
287 memcpy((char *)data + buf->size - realoffset, buf->data, len - (buf->size - realoffset));
289 memcpy(data, buf->data + realoffset, len);
295 // Discard data from the buffer.
296 static ssize_t buffer_discard(struct buffer *buf, size_t len) {
297 if(buf->used < len) {
301 if(buf->size - buf->offset < len) {
302 buf->offset -= buf->size;
311 static bool buffer_set_size(struct buffer *buf, uint32_t minsize, uint32_t maxsize) {
312 if(maxsize < minsize) {
316 buf->maxsize = maxsize;
318 return buf->size >= minsize || buffer_resize(buf, minsize);
321 static void buffer_exit(struct buffer *buf) {
323 memset(buf, 0, sizeof(*buf));
326 static uint32_t buffer_free(const struct buffer *buf) {
327 return buf->maxsize - buf->used;
330 // Connections are stored in a sorted list.
331 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
333 static int compare(const void *va, const void *vb) {
336 const struct utcp_connection *a = *(struct utcp_connection **)va;
337 const struct utcp_connection *b = *(struct utcp_connection **)vb;
340 assert(a->src && b->src);
342 int c = (int)a->src - (int)b->src;
348 c = (int)a->dst - (int)b->dst;
352 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
353 if(!utcp->nconnections) {
357 struct utcp_connection key = {
361 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
362 return match ? *match : NULL;
365 static void free_connection(struct utcp_connection *c) {
366 struct utcp *utcp = c->utcp;
367 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
371 int i = cp - utcp->connections;
372 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof(*cp));
373 utcp->nconnections--;
375 buffer_exit(&c->rcvbuf);
376 buffer_exit(&c->sndbuf);
380 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
381 // Check whether this combination of src and dst is free
384 if(find_connection(utcp, src, dst)) {
388 } else { // If src == 0, generate a random port number with the high bit set
389 if(utcp->nconnections >= 32767) {
394 src = rand() | 0x8000;
396 while(find_connection(utcp, src, dst)) {
401 // Allocate memory for the new connection
403 if(utcp->nconnections >= utcp->nallocated) {
404 if(!utcp->nallocated) {
405 utcp->nallocated = 4;
407 utcp->nallocated *= 2;
410 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof(*utcp->connections));
416 utcp->connections = new_array;
419 struct utcp_connection *c = calloc(1, sizeof(*c));
425 if(!buffer_set_size(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
430 if(!buffer_set_size(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
431 buffer_exit(&c->sndbuf);
436 // Fill in the details
445 c->snd.una = c->snd.iss;
446 c->snd.nxt = c->snd.iss + 1;
447 c->snd.last = c->snd.nxt;
448 c->snd.cwnd = (utcp->mss > 2190 ? 2 : utcp->mss > 1095 ? 3 : 4) * utcp->mss;
449 c->snd.ssthresh = ~0;
453 // Add it to the sorted list of connections
455 utcp->connections[utcp->nconnections++] = c;
456 qsort(utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
461 static inline uint32_t absdiff(uint32_t a, uint32_t b) {
469 // Update RTT variables. See RFC 6298.
470 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
472 debug(c, "invalid rtt\n");
476 struct utcp *utcp = c->utcp;
480 utcp->rttvar = rtt / 2;
482 utcp->rttvar = (utcp->rttvar * 3 + absdiff(utcp->srtt, rtt)) / 4;
483 utcp->srtt = (utcp->srtt * 7 + rtt) / 8;
486 utcp->rto = utcp->srtt + max(4 * utcp->rttvar, CLOCK_GRANULARITY);
488 if(utcp->rto > MAX_RTO) {
492 debug(c, "rtt %u srtt %u rttvar %u rto %u\n", rtt, utcp->srtt, utcp->rttvar, utcp->rto);
495 static void start_retransmit_timer(struct utcp_connection *c) {
496 gettimeofday(&c->rtrx_timeout, NULL);
497 c->rtrx_timeout.tv_usec += c->utcp->rto;
499 while(c->rtrx_timeout.tv_usec >= 1000000) {
500 c->rtrx_timeout.tv_usec -= 1000000;
501 c->rtrx_timeout.tv_sec++;
504 debug(c, "rtrx_timeout %ld.%06lu\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_usec);
507 static void stop_retransmit_timer(struct utcp_connection *c) {
508 timerclear(&c->rtrx_timeout);
509 debug(c, "rtrx_timeout cleared\n");
512 struct utcp_connection *utcp_connect_ex(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv, uint32_t flags) {
513 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
519 assert((flags & ~0x1f) == 0);
530 pkt.hdr.src = c->src;
531 pkt.hdr.dst = c->dst;
532 pkt.hdr.seq = c->snd.iss;
534 pkt.hdr.wnd = c->rcvbuf.maxsize;
536 pkt.hdr.aux = 0x0101;
540 pkt.init[3] = flags & 0x7;
542 set_state(c, SYN_SENT);
544 print_packet(c, "send", &pkt, sizeof(pkt));
545 utcp->send(utcp, &pkt, sizeof(pkt));
547 gettimeofday(&c->conn_timeout, NULL);
548 c->conn_timeout.tv_sec += utcp->timeout;
550 start_retransmit_timer(c);
555 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
556 return utcp_connect_ex(utcp, dst, recv, priv, UTCP_TCP);
559 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
560 if(c->reapable || c->state != SYN_RECEIVED) {
561 debug(c, "accept() called on invalid connection in state %s\n", c, strstate[c->state]);
565 debug(c, "accepted %p %p\n", c, recv, priv);
568 set_state(c, ESTABLISHED);
571 static void ack(struct utcp_connection *c, bool sendatleastone) {
572 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
573 int32_t cwndleft = min(c->snd.cwnd, c->snd.wnd) - seqdiff(c->snd.nxt, c->snd.una);
579 } else if(cwndleft < left) {
582 if(!sendatleastone || cwndleft > c->utcp->mss) {
583 left -= left % c->utcp->mss;
587 debug(c, "cwndleft %d left %d\n", cwndleft, left);
589 if(!left && !sendatleastone) {
596 } *pkt = c->utcp->pkt;
598 pkt->hdr.src = c->src;
599 pkt->hdr.dst = c->dst;
600 pkt->hdr.ack = c->rcv.nxt;
601 pkt->hdr.wnd = c->rcvbuf.maxsize;
606 uint32_t seglen = left > c->utcp->mss ? c->utcp->mss : left;
607 pkt->hdr.seq = c->snd.nxt;
609 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
611 c->snd.nxt += seglen;
614 if(seglen && fin_wanted(c, c->snd.nxt)) {
619 if(!c->rtt_start.tv_sec) {
620 // Start RTT measurement
621 gettimeofday(&c->rtt_start, NULL);
622 c->rtt_seq = pkt->hdr.seq + seglen;
623 debug(c, "starting RTT measurement, expecting ack %u\n", c->rtt_seq);
626 print_packet(c, "send", pkt, sizeof(pkt->hdr) + seglen);
627 c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen);
631 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
633 debug(c, "send() called on closed connection\n");
641 debug(c, "send() called on unconnected connection\n");
656 debug(c, "send() called on closed connection\n");
661 // Exit early if we have nothing to send.
672 // Check if we need to be able to buffer all data
674 if(c->flags & UTCP_NO_PARTIAL) {
675 if(len > buffer_free(&c->sndbuf)) {
676 if(len > c->sndbuf.maxsize) {
686 // Add data to send buffer.
688 if(is_reliable(c) || (c->state != SYN_SENT && c->state != SYN_RECEIVED)) {
689 len = buffer_put(&c->sndbuf, data, len);
705 // Don't send anything yet if the connection has not fully established yet
707 if(c->state == SYN_SENT || c->state == SYN_RECEIVED) {
713 if(!is_reliable(c)) {
714 c->snd.una = c->snd.nxt = c->snd.last;
715 buffer_discard(&c->sndbuf, c->sndbuf.used);
718 if(is_reliable(c) && !timerisset(&c->rtrx_timeout)) {
719 start_retransmit_timer(c);
722 if(is_reliable(c) && !timerisset(&c->conn_timeout)) {
723 gettimeofday(&c->conn_timeout, NULL);
724 c->conn_timeout.tv_sec += c->utcp->timeout;
730 static void swap_ports(struct hdr *hdr) {
731 uint16_t tmp = hdr->src;
736 static void fast_retransmit(struct utcp_connection *c) {
737 if(c->state == CLOSED || c->snd.last == c->snd.una) {
738 debug(c, "fast_retransmit() called but nothing to retransmit!\n");
742 struct utcp *utcp = c->utcp;
749 pkt = malloc(c->utcp->mtu);
755 pkt->hdr.src = c->src;
756 pkt->hdr.dst = c->dst;
757 pkt->hdr.wnd = c->rcvbuf.maxsize;
766 // Send unacked data again.
767 pkt->hdr.seq = c->snd.una;
768 pkt->hdr.ack = c->rcv.nxt;
770 uint32_t len = min(seqdiff(c->snd.last, c->snd.una), utcp->mss);
772 if(fin_wanted(c, c->snd.una + len)) {
777 buffer_copy(&c->sndbuf, pkt->data, 0, len);
778 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + len);
779 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
789 static void retransmit(struct utcp_connection *c) {
790 if(c->state == CLOSED || c->snd.last == c->snd.una) {
791 debug(c, "retransmit() called but nothing to retransmit!\n");
792 stop_retransmit_timer(c);
796 struct utcp *utcp = c->utcp;
801 } *pkt = c->utcp->pkt;
803 pkt->hdr.src = c->src;
804 pkt->hdr.dst = c->dst;
805 pkt->hdr.wnd = c->rcvbuf.maxsize;
810 // Send our SYN again
811 pkt->hdr.seq = c->snd.iss;
814 pkt->hdr.aux = 0x0101;
818 pkt->data[3] = c->flags & 0x7;
819 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + 4);
820 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
825 pkt->hdr.seq = c->snd.nxt;
826 pkt->hdr.ack = c->rcv.nxt;
827 pkt->hdr.ctl = SYN | ACK;
828 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr));
829 utcp->send(utcp, pkt, sizeof(pkt->hdr));
837 // Send unacked data again.
838 pkt->hdr.seq = c->snd.una;
839 pkt->hdr.ack = c->rcv.nxt;
841 uint32_t len = min(seqdiff(c->snd.last, c->snd.una), utcp->mss);
843 if(fin_wanted(c, c->snd.una + len)) {
848 // RFC 5681 slow start after timeout
849 uint32_t flightsize = seqdiff(c->snd.nxt, c->snd.una);
850 c->snd.ssthresh = max(flightsize / 2, utcp->mss * 2); // eq. 4
851 c->snd.cwnd = utcp->mss;
854 buffer_copy(&c->sndbuf, pkt->data, 0, len);
855 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + len);
856 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
858 c->snd.nxt = c->snd.una + len;
865 // We shouldn't need to retransmit anything in this state.
869 stop_retransmit_timer(c);
873 start_retransmit_timer(c);
876 if(utcp->rto > MAX_RTO) {
880 c->rtt_start.tv_sec = 0; // invalidate RTT timer
881 c->dupack = 0; // cancel any ongoing fast recovery
887 /* Update receive buffer and SACK entries after consuming data.
891 * |.....0000..1111111111.....22222......3333|
894 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
895 * to remove data from the receive buffer. The idea is to substract "len"
896 * from the offset of all the SACK entries, and then remove/cut down entries
897 * that are shifted to before the start of the receive buffer.
899 * There are three cases:
900 * - the SACK entry is after ^, in that case just change the offset.
901 * - the SACK entry starts before and ends after ^, so we have to
902 * change both its offset and size.
903 * - the SACK entry is completely before ^, in that case delete it.
905 static void sack_consume(struct utcp_connection *c, size_t len) {
906 debug(c, "sack_consume %lu\n", (unsigned long)len);
908 if(len > c->rcvbuf.used) {
909 debug(c, "all SACK entries consumed\n");
914 buffer_discard(&c->rcvbuf, len);
916 for(int i = 0; i < NSACKS && c->sacks[i].len;) {
917 if(len < c->sacks[i].offset) {
918 c->sacks[i].offset -= len;
920 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
921 c->sacks[i].len -= len - c->sacks[i].offset;
922 c->sacks[i].offset = 0;
926 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
927 c->sacks[NSACKS - 1].len = 0;
935 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
936 debug(c, "SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
940 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
941 debug(c, "out of order packet, offset %u\n", offset);
942 // Packet loss or reordering occured. Store the data in the buffer.
943 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
945 if(rxd < 0 || (size_t)rxd < len) {
949 // Make note of where we put it.
950 for(int i = 0; i < NSACKS; i++) {
951 if(!c->sacks[i].len) { // nothing to merge, add new entry
952 debug(c, "new SACK entry %d\n", i);
953 c->sacks[i].offset = offset;
954 c->sacks[i].len = rxd;
956 } else if(offset < c->sacks[i].offset) {
957 if(offset + rxd < c->sacks[i].offset) { // insert before
958 if(!c->sacks[NSACKS - 1].len) { // only if room left
959 debug(c, "insert SACK entry at %d\n", i);
960 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
961 c->sacks[i].offset = offset;
962 c->sacks[i].len = rxd;
964 debug(c, "SACK entries full, dropping packet\n");
969 debug(c, "merge with start of SACK entry at %d\n", i);
970 c->sacks[i].offset = offset;
973 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
974 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
975 debug(c, "merge with end of SACK entry at %d\n", i);
976 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
977 // TODO: handle potential merge with next entry
984 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
985 debug(c, "SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
989 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
990 // Check if we can process out-of-order data now.
991 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
992 debug(c, "incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
993 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
994 len = max(len, c->sacks[0].offset + c->sacks[0].len);
995 data = c->rcvbuf.data;
999 ssize_t rxd = c->recv(c, data, len);
1001 if(rxd < 0 || (size_t)rxd != len) {
1002 // TODO: handle the application not accepting all data.
1007 if(c->rcvbuf.used) {
1008 sack_consume(c, len);
1015 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
1016 if(!is_reliable(c)) {
1017 c->recv(c, data, len);
1018 c->rcv.nxt = seq + len;
1022 uint32_t offset = seqdiff(seq, c->rcv.nxt);
1024 if(offset + len > c->rcvbuf.maxsize) {
1029 handle_out_of_order(c, offset, data, len);
1031 handle_in_order(c, data, len);
1036 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
1037 const uint8_t *ptr = data;
1053 // Drop packets smaller than the header
1057 if(len < sizeof(hdr)) {
1058 print_packet(NULL, "recv", data, len);
1063 // Make a copy from the potentially unaligned data to a struct hdr
1065 memcpy(&hdr, ptr, sizeof(hdr));
1067 // Try to match the packet to an existing connection
1069 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
1070 print_packet(c, "recv", data, len);
1072 // Process the header
1077 // Drop packets with an unknown CTL flag
1079 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
1080 print_packet(NULL, "recv", data, len);
1085 // Check for auxiliary headers
1087 const uint8_t *init = NULL;
1089 uint16_t aux = hdr.aux;
1092 size_t auxlen = 4 * (aux >> 8) & 0xf;
1093 uint8_t auxtype = aux & 0xff;
1102 if(!(hdr.ctl & SYN) || auxlen != 4) {
1118 if(!(aux & 0x800)) {
1127 memcpy(&aux, ptr, 2);
1132 bool has_data = len || (hdr.ctl & (SYN | FIN));
1134 // Is it for a new connection?
1137 // Ignore RST packets
1143 // Is it a SYN packet and are we LISTENing?
1145 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1146 // If we don't want to accept it, send a RST back
1147 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
1152 // Try to allocate memory, otherwise send a RST back
1153 c = allocate_connection(utcp, hdr.dst, hdr.src);
1160 // Parse auxilliary information
1167 c->flags = init[3] & 0x7;
1169 c->flags = UTCP_TCP;
1173 // Return SYN+ACK, go to SYN_RECEIVED state
1174 c->snd.wnd = hdr.wnd;
1175 c->rcv.irs = hdr.seq;
1176 c->rcv.nxt = c->rcv.irs + 1;
1177 set_state(c, SYN_RECEIVED);
1184 pkt.hdr.src = c->src;
1185 pkt.hdr.dst = c->dst;
1186 pkt.hdr.ack = c->rcv.irs + 1;
1187 pkt.hdr.seq = c->snd.iss;
1188 pkt.hdr.wnd = c->rcvbuf.maxsize;
1189 pkt.hdr.ctl = SYN | ACK;
1192 pkt.hdr.aux = 0x0101;
1196 pkt.data[3] = c->flags & 0x7;
1197 print_packet(c, "send", &pkt, sizeof(hdr) + 4);
1198 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1201 print_packet(c, "send", &pkt, sizeof(hdr));
1202 utcp->send(utcp, &pkt, sizeof(hdr));
1205 // No, we don't want your packets, send a RST back
1213 debug(c, "state %s\n", strstate[c->state]);
1215 // In case this is for a CLOSED connection, ignore the packet.
1216 // TODO: make it so incoming packets can never match a CLOSED connection.
1218 if(c->state == CLOSED) {
1219 debug(c, "got packet for closed connection\n");
1223 // It is for an existing connection.
1225 // 1. Drop invalid packets.
1227 // 1a. Drop packets that should not happen in our current state.
1248 // 1b. Discard data that is not in our receive window.
1250 if(is_reliable(c)) {
1253 if(c->state == SYN_SENT) {
1255 } else if(len == 0) {
1256 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1258 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1260 // cut already accepted front overlapping
1261 if(rcv_offset < 0) {
1262 acceptable = len > (size_t) - rcv_offset;
1267 hdr.seq -= rcv_offset;
1270 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1275 debug(c, "packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1277 // Ignore unacceptable RST packets.
1282 // Otherwise, continue processing.
1287 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1290 debug(c, "packet out of order, offset %u bytes", rcv_offset);
1293 if(rcv_offset >= 0) {
1294 c->rcv.nxt = hdr.seq + len;
1300 c->snd.wnd = hdr.wnd; // TODO: move below
1302 // 1c. Drop packets with an invalid ACK.
1303 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1304 // (= snd.una + c->sndbuf.used).
1306 if(!is_reliable(c)) {
1307 if(hdr.ack != c->snd.last && c->state >= ESTABLISHED) {
1308 hdr.ack = c->snd.una;
1312 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
1313 debug(c, "packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1315 // Ignore unacceptable RST packets.
1323 // 2. Handle RST packets
1328 if(!(hdr.ctl & ACK)) {
1332 // The peer has refused our connection.
1333 set_state(c, CLOSED);
1334 errno = ECONNREFUSED;
1337 c->recv(c, NULL, 0);
1340 if(c->poll && !c->reapable) {
1351 // We haven't told the application about this connection yet. Silently delete.
1363 // The peer has aborted our connection.
1364 set_state(c, CLOSED);
1368 c->recv(c, NULL, 0);
1371 if(c->poll && !c->reapable) {
1384 // As far as the application is concerned, the connection has already been closed.
1385 // If it has called utcp_close() already, we can immediately free this connection.
1391 // Otherwise, immediately move to the CLOSED state.
1392 set_state(c, CLOSED);
1405 if(!(hdr.ctl & ACK)) {
1410 // 3. Advance snd.una
1412 advanced = seqdiff(hdr.ack, c->snd.una);
1416 if(c->rtt_start.tv_sec) {
1417 if(c->rtt_seq == hdr.ack) {
1418 struct timeval now, diff;
1419 gettimeofday(&now, NULL);
1420 timersub(&now, &c->rtt_start, &diff);
1421 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
1422 c->rtt_start.tv_sec = 0;
1423 } else if(c->rtt_seq < hdr.ack) {
1424 debug(c, "cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1425 c->rtt_start.tv_sec = 0;
1429 int32_t data_acked = advanced;
1437 // TODO: handle FIN as well.
1442 assert(data_acked >= 0);
1445 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1446 assert(data_acked <= bufused);
1450 buffer_discard(&c->sndbuf, data_acked);
1453 // Also advance snd.nxt if possible
1454 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1455 c->snd.nxt = hdr.ack;
1458 c->snd.una = hdr.ack;
1461 if(c->dupack >= 3) {
1462 debug(c, "fast recovery ended\n");
1463 c->snd.cwnd = c->snd.ssthresh;
1469 // Increase the congestion window according to RFC 5681
1470 if(c->snd.cwnd < c->snd.ssthresh) {
1471 c->snd.cwnd += min(advanced, utcp->mss); // eq. 2
1473 c->snd.cwnd += max(1, (utcp->mss * utcp->mss) / c->snd.cwnd); // eq. 3
1476 if(c->snd.cwnd > c->sndbuf.maxsize) {
1477 c->snd.cwnd = c->sndbuf.maxsize;
1482 // Check if we have sent a FIN that is now ACKed.
1485 if(c->snd.una == c->snd.last) {
1486 set_state(c, FIN_WAIT_2);
1492 if(c->snd.una == c->snd.last) {
1493 gettimeofday(&c->conn_timeout, NULL);
1494 c->conn_timeout.tv_sec += utcp->timeout;
1495 set_state(c, TIME_WAIT);
1504 if(!len && is_reliable(c) && c->snd.una != c->snd.last) {
1506 debug(c, "duplicate ACK %d\n", c->dupack);
1508 if(c->dupack == 3) {
1509 // RFC 5681 fast recovery
1510 debug(c, "fast recovery started\n", c->dupack);
1511 uint32_t flightsize = seqdiff(c->snd.nxt, c->snd.una);
1512 c->snd.ssthresh = max(flightsize / 2, utcp->mss * 2); // eq. 4
1513 c->snd.cwnd = min(c->snd.ssthresh + 3 * utcp->mss, c->sndbuf.maxsize);
1515 if(c->snd.cwnd > c->sndbuf.maxsize) {
1516 c->snd.cwnd = c->sndbuf.maxsize;
1522 } else if(c->dupack > 3) {
1523 c->snd.cwnd += utcp->mss;
1525 if(c->snd.cwnd > c->sndbuf.maxsize) {
1526 c->snd.cwnd = c->sndbuf.maxsize;
1532 // We got an ACK which indicates the other side did get one of our packets.
1533 // Reset the retransmission timer to avoid going to slow start,
1534 // but don't touch the connection timeout.
1535 start_retransmit_timer(c);
1542 if(c->snd.una == c->snd.last) {
1543 stop_retransmit_timer(c);
1544 timerclear(&c->conn_timeout);
1545 } else if(is_reliable(c)) {
1546 start_retransmit_timer(c);
1547 gettimeofday(&c->conn_timeout, NULL);
1548 c->conn_timeout.tv_sec += utcp->timeout;
1553 // 5. Process SYN stuff
1559 // This is a SYNACK. It should always have ACKed the SYN.
1564 c->rcv.irs = hdr.seq;
1565 c->rcv.nxt = hdr.seq;
1569 set_state(c, FIN_WAIT_1);
1571 set_state(c, ESTABLISHED);
1574 // TODO: notify application of this somehow.
1578 // This is a retransmit of a SYN, send back the SYNACK.
1588 // Ehm, no. We should never receive a second SYN.
1598 // SYN counts as one sequence number
1602 // 6. Process new data
1604 if(c->state == SYN_RECEIVED) {
1605 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1610 // Are we still LISTENing?
1612 utcp->accept(c, c->src);
1615 if(c->state != ESTABLISHED) {
1616 set_state(c, CLOSED);
1626 // This should never happen.
1641 // Ehm no, We should never receive more data after a FIN.
1651 handle_incoming_data(c, hdr.seq, ptr, len);
1654 // 7. Process FIN stuff
1656 if((hdr.ctl & FIN) && (!is_reliable(c) || hdr.seq + len == c->rcv.nxt)) {
1660 // This should never happen.
1667 set_state(c, CLOSE_WAIT);
1671 set_state(c, CLOSING);
1675 gettimeofday(&c->conn_timeout, NULL);
1676 c->conn_timeout.tv_sec += utcp->timeout;
1677 set_state(c, TIME_WAIT);
1684 // Ehm, no. We should never receive a second FIN.
1694 // FIN counts as one sequence number
1698 // Inform the application that the peer closed its end of the connection.
1701 c->recv(c, NULL, 0);
1705 // Now we send something back if:
1706 // - we received data, so we have to send back an ACK
1707 // -> sendatleastone = true
1708 // - or we got an ack, so we should maybe send a bit more data
1709 // -> sendatleastone = false
1711 if(is_reliable(c) || hdr.ctl & SYN || hdr.ctl & FIN) {
1726 hdr.ack = hdr.seq + len;
1728 hdr.ctl = RST | ACK;
1731 print_packet(c, "send", &hdr, sizeof(hdr));
1732 utcp->send(utcp, &hdr, sizeof(hdr));
1737 int utcp_shutdown(struct utcp_connection *c, int dir) {
1738 debug(c, "shutdown %d at %u\n", dir, c ? c->snd.last : 0);
1746 debug(c, "shutdown() called on closed connection\n");
1751 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1756 // TCP does not have a provision for stopping incoming packets.
1757 // The best we can do is to just ignore them.
1758 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1762 // The rest of the code deals with shutting down writes.
1763 if(dir == UTCP_SHUT_RD) {
1767 // Only process shutting down writes once.
1785 set_state(c, FIN_WAIT_1);
1793 set_state(c, CLOSING);
1806 if(!timerisset(&c->rtrx_timeout)) {
1807 start_retransmit_timer(c);
1813 static bool reset_connection(struct utcp_connection *c) {
1820 debug(c, "abort() called on closed connection\n");
1837 set_state(c, CLOSED);
1845 set_state(c, CLOSED);
1855 hdr.seq = c->snd.nxt;
1860 print_packet(c, "send", &hdr, sizeof(hdr));
1861 c->utcp->send(c->utcp, &hdr, sizeof(hdr));
1865 // Closes all the opened connections
1866 void utcp_abort_all_connections(struct utcp *utcp) {
1872 for(int i = 0; i < utcp->nconnections; i++) {
1873 struct utcp_connection *c = utcp->connections[i];
1875 if(c->reapable || c->state == CLOSED) {
1879 utcp_recv_t old_recv = c->recv;
1880 utcp_poll_t old_poll = c->poll;
1882 reset_connection(c);
1886 old_recv(c, NULL, 0);
1889 if(old_poll && !c->reapable) {
1898 int utcp_close(struct utcp_connection *c) {
1899 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
1909 int utcp_abort(struct utcp_connection *c) {
1910 if(!reset_connection(c)) {
1919 * One call to this function will loop through all connections,
1920 * checking if something needs to be resent or not.
1921 * The return value is the time to the next timeout in milliseconds,
1922 * or maybe a negative value if the timeout is infinite.
1924 struct timeval utcp_timeout(struct utcp *utcp) {
1926 gettimeofday(&now, NULL);
1927 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1929 for(int i = 0; i < utcp->nconnections; i++) {
1930 struct utcp_connection *c = utcp->connections[i];
1936 // delete connections that have been utcp_close()d.
1937 if(c->state == CLOSED) {
1939 debug(c, "reaping\n");
1947 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1952 c->recv(c, NULL, 0);
1955 if(c->poll && !c->reapable) {
1962 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1963 debug(c, "retransmitting after timeout\n");
1968 if((c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1969 uint32_t len = buffer_free(&c->sndbuf);
1974 } else if(c->state == CLOSED) {
1979 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <)) {
1980 next = c->conn_timeout;
1983 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <)) {
1984 next = c->rtrx_timeout;
1988 struct timeval diff;
1990 timersub(&next, &now, &diff);
1995 bool utcp_is_active(struct utcp *utcp) {
2000 for(int i = 0; i < utcp->nconnections; i++)
2001 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
2008 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
2014 struct utcp *utcp = calloc(1, sizeof(*utcp));
2020 utcp->accept = accept;
2021 utcp->pre_accept = pre_accept;
2024 utcp_set_mtu(utcp, DEFAULT_MTU);
2025 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
2026 utcp->rto = START_RTO; // usec
2031 void utcp_exit(struct utcp *utcp) {
2036 for(int i = 0; i < utcp->nconnections; i++) {
2037 struct utcp_connection *c = utcp->connections[i];
2041 c->recv(c, NULL, 0);
2044 if(c->poll && !c->reapable) {
2049 buffer_exit(&c->rcvbuf);
2050 buffer_exit(&c->sndbuf);
2054 free(utcp->connections);
2058 uint16_t utcp_get_mtu(struct utcp *utcp) {
2059 return utcp ? utcp->mtu : 0;
2062 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
2067 if(mtu <= sizeof(struct hdr)) {
2071 if(mtu > utcp->mtu) {
2072 char *new = realloc(utcp->pkt, mtu + sizeof(struct hdr));
2082 utcp->mss = mtu - sizeof(struct hdr);
2085 void utcp_reset_timers(struct utcp *utcp) {
2090 struct timeval now, then;
2092 gettimeofday(&now, NULL);
2096 then.tv_sec += utcp->timeout;
2098 for(int i = 0; i < utcp->nconnections; i++) {
2099 struct utcp_connection *c = utcp->connections[i];
2105 if(timerisset(&c->rtrx_timeout)) {
2106 c->rtrx_timeout = now;
2109 if(timerisset(&c->conn_timeout)) {
2110 c->conn_timeout = then;
2113 c->rtt_start.tv_sec = 0;
2116 if(utcp->rto > START_RTO) {
2117 utcp->rto = START_RTO;
2121 int utcp_get_user_timeout(struct utcp *u) {
2122 return u ? u->timeout : 0;
2125 void utcp_set_user_timeout(struct utcp *u, int timeout) {
2127 u->timeout = timeout;
2131 size_t utcp_get_sndbuf(struct utcp_connection *c) {
2132 return c ? c->sndbuf.maxsize : 0;
2135 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
2145 return buffer_free(&c->sndbuf);
2152 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
2157 c->sndbuf.maxsize = size;
2159 if(c->sndbuf.maxsize != size) {
2160 c->sndbuf.maxsize = -1;
2164 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
2165 return c ? c->rcvbuf.maxsize : 0;
2168 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
2169 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
2170 return buffer_free(&c->rcvbuf);
2176 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
2181 c->rcvbuf.maxsize = size;
2183 if(c->rcvbuf.maxsize != size) {
2184 c->rcvbuf.maxsize = -1;
2188 size_t utcp_get_sendq(struct utcp_connection *c) {
2189 return c->sndbuf.used;
2192 size_t utcp_get_recvq(struct utcp_connection *c) {
2193 return c->rcvbuf.used;
2196 bool utcp_get_nodelay(struct utcp_connection *c) {
2197 return c ? c->nodelay : false;
2200 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
2202 c->nodelay = nodelay;
2206 bool utcp_get_keepalive(struct utcp_connection *c) {
2207 return c ? c->keepalive : false;
2210 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
2212 c->keepalive = keepalive;
2216 size_t utcp_get_outq(struct utcp_connection *c) {
2217 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
2220 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
2226 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
2232 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
2234 utcp->accept = accept;
2235 utcp->pre_accept = pre_accept;
2239 void utcp_expect_data(struct utcp_connection *c, bool expect) {
2240 if(!c || c->reapable) {
2244 if(!(c->state == ESTABLISHED || c->state == FIN_WAIT_1 || c->state == FIN_WAIT_2)) {
2249 // If we expect data, start the connection timer.
2250 if(!timerisset(&c->conn_timeout)) {
2251 gettimeofday(&c->conn_timeout, NULL);
2252 c->conn_timeout.tv_sec += c->utcp->timeout;
2255 // If we want to cancel expecting data, only clear the timer when there is no unACKed data.
2256 if(c->snd.una == c->snd.last) {
2257 timerclear(&c->conn_timeout);
2262 void utcp_offline(struct utcp *utcp, bool offline) {
2264 gettimeofday(&now, NULL);
2266 for(int i = 0; i < utcp->nconnections; i++) {
2267 struct utcp_connection *c = utcp->connections[i];
2273 utcp_expect_data(c, offline);
2276 if(timerisset(&c->rtrx_timeout)) {
2277 c->rtrx_timeout = now;
2280 utcp->connections[i]->rtt_start.tv_sec = 0;
2284 if(!offline && utcp->rto > START_RTO) {
2285 utcp->rto = START_RTO;