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>
33 #include "utcp_priv.h"
48 #define timersub(a, b, r)\
50 (r)->tv_sec = (a)->tv_sec - (b)->tv_sec;\
51 (r)->tv_usec = (a)->tv_usec - (b)->tv_usec;\
53 (r)->tv_sec--, (r)->tv_usec += USEC_PER_SEC;\
57 static inline size_t min(size_t a, size_t b) {
61 static inline size_t max(size_t a, size_t b) {
68 static void debug(const char *format, ...) {
71 vfprintf(stderr, format, ap);
75 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
78 if(len < sizeof(hdr)) {
79 debug("%p %s: short packet (%lu bytes)\n", utcp, dir, (unsigned long)len);
83 memcpy(&hdr, pkt, sizeof(hdr));
84 debug("%p %s: len=%lu, src=%u dst=%u seq=%u ack=%u wnd=%u aux=%x ctl=", utcp, dir, (unsigned long)len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd, hdr.aux);
102 if(len > sizeof(hdr)) {
103 uint32_t datalen = len - sizeof(hdr);
104 const uint8_t *data = (uint8_t *)pkt + sizeof(hdr);
105 char str[datalen * 2 + 1];
108 for(uint32_t i = 0; i < datalen; i++) {
109 *p++ = "0123456789ABCDEF"[data[i] >> 4];
110 *p++ = "0123456789ABCDEF"[data[i] & 15];
115 debug(" data=%s", str);
121 static void debug_cwnd(struct utcp_connection *c) {
122 debug("snd.cwnd = %u\n", c->snd.cwnd);
125 #define debug(...) do {} while(0)
126 #define print_packet(...) do {} while(0)
127 #define debug_cwnd(...) do {} while(0)
130 static void set_state(struct utcp_connection *c, enum state state) {
133 if(state == ESTABLISHED) {
134 timerclear(&c->conn_timeout);
137 debug("%p new state: %s\n", c->utcp, strstate[state]);
140 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
141 if(seq != c->snd.last) {
156 static bool is_reliable(struct utcp_connection *c) {
157 return c->flags & UTCP_RELIABLE;
160 static int32_t seqdiff(uint32_t a, uint32_t b) {
165 // TODO: convert to ringbuffers to avoid memmove() operations.
167 // Store data into the buffer
168 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
169 debug("buffer_put_at %lu %lu %lu\n", (unsigned long)buf->used, (unsigned long)offset, (unsigned long)len);
171 size_t required = offset + len;
173 if(required > buf->maxsize) {
174 if(offset >= buf->maxsize) {
178 len = buf->maxsize - offset;
179 required = buf->maxsize;
182 if(required > buf->size) {
183 size_t newsize = buf->size;
190 } while(newsize < required);
193 if(newsize > buf->maxsize) {
194 newsize = buf->maxsize;
197 char *newdata = realloc(buf->data, newsize);
207 memcpy(buf->data + offset, data, len);
209 if(required > buf->used) {
210 buf->used = required;
216 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
217 return buffer_put_at(buf, buf->used, data, len);
220 // Get data from the buffer. data can be NULL.
221 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
222 if(len > buf->used) {
227 memcpy(data, buf->data, len);
230 if(len < buf->used) {
231 memmove(buf->data, buf->data + len, buf->used - len);
238 // Copy data from the buffer without removing it.
239 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
240 if(offset >= buf->used) {
244 if(offset + len > buf->used) {
245 len = buf->used - offset;
248 memcpy(data, buf->data + offset, len);
252 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
253 memset(buf, 0, sizeof(*buf));
256 buf->data = malloc(len);
264 buf->maxsize = maxlen;
268 static void buffer_exit(struct buffer *buf) {
270 memset(buf, 0, sizeof(*buf));
273 static uint32_t buffer_free(const struct buffer *buf) {
274 return buf->maxsize - buf->used;
277 // Connections are stored in a sorted list.
278 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
280 static int compare(const void *va, const void *vb) {
283 const struct utcp_connection *a = *(struct utcp_connection **)va;
284 const struct utcp_connection *b = *(struct utcp_connection **)vb;
287 assert(a->src && b->src);
289 int c = (int)a->src - (int)b->src;
295 c = (int)a->dst - (int)b->dst;
299 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
300 if(!utcp->nconnections) {
304 struct utcp_connection key = {
308 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
309 return match ? *match : NULL;
312 static void free_connection(struct utcp_connection *c) {
313 struct utcp *utcp = c->utcp;
314 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
318 int i = cp - utcp->connections;
319 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof(*cp));
320 utcp->nconnections--;
322 buffer_exit(&c->rcvbuf);
323 buffer_exit(&c->sndbuf);
327 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
328 // Check whether this combination of src and dst is free
331 if(find_connection(utcp, src, dst)) {
335 } else { // If src == 0, generate a random port number with the high bit set
336 if(utcp->nconnections >= 32767) {
341 src = rand() | 0x8000;
343 while(find_connection(utcp, src, dst)) {
348 // Allocate memory for the new connection
350 if(utcp->nconnections >= utcp->nallocated) {
351 if(!utcp->nallocated) {
352 utcp->nallocated = 4;
354 utcp->nallocated *= 2;
357 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof(*utcp->connections));
363 utcp->connections = new_array;
366 struct utcp_connection *c = calloc(1, sizeof(*c));
372 if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
377 if(!buffer_init(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
378 buffer_exit(&c->sndbuf);
383 // Fill in the details
392 c->snd.una = c->snd.iss;
393 c->snd.nxt = c->snd.iss + 1;
394 c->snd.last = c->snd.nxt;
395 c->snd.cwnd = (utcp->mtu > 2190 ? 2 : utcp->mtu > 1095 ? 3 : 4) * utcp->mtu;
396 c->snd.ssthresh = ~0;
400 // Add it to the sorted list of connections
402 utcp->connections[utcp->nconnections++] = c;
403 qsort(utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
408 static inline uint32_t absdiff(uint32_t a, uint32_t b) {
416 // Update RTT variables. See RFC 6298.
417 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
419 debug("invalid rtt\n");
423 struct utcp *utcp = c->utcp;
427 utcp->rttvar = rtt / 2;
429 utcp->rttvar = (utcp->rttvar * 3 + absdiff(utcp->srtt, rtt)) / 4;
430 utcp->srtt = (utcp->srtt * 7 + rtt) / 8;
433 utcp->rto = utcp->srtt + max(4 * utcp->rttvar, CLOCK_GRANULARITY);
435 if(utcp->rto > MAX_RTO) {
439 debug("rtt %u srtt %u rttvar %u rto %u\n", rtt, utcp->srtt, utcp->rttvar, utcp->rto);
442 static void start_retransmit_timer(struct utcp_connection *c) {
443 gettimeofday(&c->rtrx_timeout, NULL);
444 c->rtrx_timeout.tv_usec += c->utcp->rto;
446 while(c->rtrx_timeout.tv_usec >= 1000000) {
447 c->rtrx_timeout.tv_usec -= 1000000;
448 c->rtrx_timeout.tv_sec++;
451 debug("timeout set to %lu.%06lu (%u)\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_usec, c->utcp->rto);
454 static void stop_retransmit_timer(struct utcp_connection *c) {
455 timerclear(&c->rtrx_timeout);
456 debug("timeout cleared\n");
459 struct utcp_connection *utcp_connect_ex(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv, uint32_t flags) {
460 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
466 assert((flags & ~0x1f) == 0);
477 pkt.hdr.src = c->src;
478 pkt.hdr.dst = c->dst;
479 pkt.hdr.seq = c->snd.iss;
481 pkt.hdr.wnd = c->rcvbuf.maxsize;
483 pkt.hdr.aux = 0x0101;
487 pkt.init[3] = flags & 0x7;
489 set_state(c, SYN_SENT);
491 print_packet(utcp, "send", &pkt, sizeof(pkt));
492 utcp->send(utcp, &pkt, sizeof(pkt));
494 gettimeofday(&c->conn_timeout, NULL);
495 c->conn_timeout.tv_sec += utcp->timeout;
497 start_retransmit_timer(c);
502 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
503 return utcp_connect_ex(utcp, dst, recv, priv, UTCP_TCP);
506 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
507 if(c->reapable || c->state != SYN_RECEIVED) {
508 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
512 debug("%p accepted, %p %p\n", c, recv, priv);
515 set_state(c, ESTABLISHED);
518 static void ack(struct utcp_connection *c, bool sendatleastone) {
519 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
520 int32_t cwndleft = min(c->snd.cwnd, c->snd.wnd) - seqdiff(c->snd.nxt, c->snd.una);
526 } else if(cwndleft < left) {
529 if(!sendatleastone || cwndleft > c->utcp->mtu) {
530 left -= left % c->utcp->mtu;
534 debug("cwndleft = %d, left = %d\n", cwndleft, left);
536 if(!left && !sendatleastone) {
545 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
551 pkt->hdr.src = c->src;
552 pkt->hdr.dst = c->dst;
553 pkt->hdr.ack = c->rcv.nxt;
554 pkt->hdr.wnd = c->rcvbuf.maxsize;
559 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
560 pkt->hdr.seq = c->snd.nxt;
562 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
564 c->snd.nxt += seglen;
567 if(seglen && fin_wanted(c, c->snd.nxt)) {
572 if(!c->rtt_start.tv_sec) {
573 // Start RTT measurement
574 gettimeofday(&c->rtt_start, NULL);
575 c->rtt_seq = pkt->hdr.seq + seglen;
576 debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
579 print_packet(c->utcp, "send", pkt, sizeof(pkt->hdr) + seglen);
580 c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen);
586 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
588 debug("Error: send() called on closed connection %p\n", c);
596 debug("Error: send() called on unconnected connection %p\n", c);
611 debug("Error: send() called on closing connection %p\n", c);
616 // Exit early if we have nothing to send.
627 // Check if we need to be able to buffer all data
629 if(c->flags & UTCP_NO_PARTIAL) {
630 if(len > buffer_free(&c->sndbuf)) {
631 if(len > c->sndbuf.maxsize) {
641 // Add data to send buffer.
643 if(is_reliable(c) || (c->state != SYN_SENT && c->state != SYN_RECEIVED)) {
644 len = buffer_put(&c->sndbuf, data, len);
660 // Don't send anything yet if the connection has not fully established yet
662 if(c->state == SYN_SENT || c->state == SYN_RECEIVED) {
668 if(!is_reliable(c)) {
669 c->snd.una = c->snd.nxt = c->snd.last;
670 buffer_get(&c->sndbuf, NULL, c->sndbuf.used);
673 if(is_reliable(c) && !timerisset(&c->rtrx_timeout)) {
674 start_retransmit_timer(c);
677 if(is_reliable(c) && !timerisset(&c->conn_timeout)) {
678 gettimeofday(&c->conn_timeout, NULL);
679 c->conn_timeout.tv_sec += c->utcp->timeout;
685 static void swap_ports(struct hdr *hdr) {
686 uint16_t tmp = hdr->src;
691 static void retransmit(struct utcp_connection *c) {
692 if(c->state == CLOSED || c->snd.last == c->snd.una) {
693 debug("Retransmit() called but nothing to retransmit!\n");
694 stop_retransmit_timer(c);
698 struct utcp *utcp = c->utcp;
705 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
711 pkt->hdr.src = c->src;
712 pkt->hdr.dst = c->dst;
713 pkt->hdr.wnd = c->rcvbuf.maxsize;
718 // Send our SYN again
719 pkt->hdr.seq = c->snd.iss;
722 pkt->hdr.aux = 0x0101;
726 pkt->data[3] = c->flags & 0x7;
727 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + 4);
728 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
733 pkt->hdr.seq = c->snd.nxt;
734 pkt->hdr.ack = c->rcv.nxt;
735 pkt->hdr.ctl = SYN | ACK;
736 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr));
737 utcp->send(utcp, pkt, sizeof(pkt->hdr));
745 // Send unacked data again.
746 pkt->hdr.seq = c->snd.una;
747 pkt->hdr.ack = c->rcv.nxt;
749 uint32_t len = seqdiff(c->snd.last, c->snd.una);
751 if(len > utcp->mtu) {
755 if(fin_wanted(c, c->snd.una + len)) {
760 c->snd.nxt = c->snd.una + len;
762 // RFC 5681 slow start after timeout
763 c->snd.ssthresh = max(c->snd.cwnd / 2, utcp->mtu * 2); // eq. 4
764 c->snd.cwnd = utcp->mtu;
767 buffer_copy(&c->sndbuf, pkt->data, 0, len);
768 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + len);
769 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
776 // We shouldn't need to retransmit anything in this state.
780 stop_retransmit_timer(c);
784 start_retransmit_timer(c);
787 if(utcp->rto > MAX_RTO) {
791 c->rtt_start.tv_sec = 0; // invalidate RTT timer
797 /* Update receive buffer and SACK entries after consuming data.
801 * |.....0000..1111111111.....22222......3333|
804 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
805 * to remove data from the receive buffer. The idea is to substract "len"
806 * from the offset of all the SACK entries, and then remove/cut down entries
807 * that are shifted to before the start of the receive buffer.
809 * There are three cases:
810 * - the SACK entry is after ^, in that case just change the offset.
811 * - the SACK entry starts before and ends after ^, so we have to
812 * change both its offset and size.
813 * - the SACK entry is completely before ^, in that case delete it.
815 static void sack_consume(struct utcp_connection *c, size_t len) {
816 debug("sack_consume %lu\n", (unsigned long)len);
818 if(len > c->rcvbuf.used) {
819 debug("All SACK entries consumed");
824 buffer_get(&c->rcvbuf, NULL, len);
826 for(int i = 0; i < NSACKS && c->sacks[i].len;) {
827 if(len < c->sacks[i].offset) {
828 c->sacks[i].offset -= len;
830 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
831 c->sacks[i].len -= len - c->sacks[i].offset;
832 c->sacks[i].offset = 0;
836 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
837 c->sacks[NSACKS - 1].len = 0;
845 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
846 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
850 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
851 debug("out of order packet, offset %u\n", offset);
852 // Packet loss or reordering occured. Store the data in the buffer.
853 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
855 if(rxd < 0 || (size_t)rxd < len) {
859 // Make note of where we put it.
860 for(int i = 0; i < NSACKS; i++) {
861 if(!c->sacks[i].len) { // nothing to merge, add new entry
862 debug("New SACK entry %d\n", i);
863 c->sacks[i].offset = offset;
864 c->sacks[i].len = rxd;
866 } else if(offset < c->sacks[i].offset) {
867 if(offset + rxd < c->sacks[i].offset) { // insert before
868 if(!c->sacks[NSACKS - 1].len) { // only if room left
869 debug("Insert SACK entry at %d\n", i);
870 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
871 c->sacks[i].offset = offset;
872 c->sacks[i].len = rxd;
874 debug("SACK entries full, dropping packet\n");
879 debug("Merge with start of SACK entry at %d\n", i);
880 c->sacks[i].offset = offset;
883 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
884 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
885 debug("Merge with end of SACK entry at %d\n", i);
886 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
887 // TODO: handle potential merge with next entry
894 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
895 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
899 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
900 // Check if we can process out-of-order data now.
901 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
902 debug("incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
903 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
904 len = max(len, c->sacks[0].offset + c->sacks[0].len);
905 data = c->rcvbuf.data;
909 ssize_t rxd = c->recv(c, data, len);
911 if(rxd < 0 || (size_t)rxd != len) {
912 // TODO: handle the application not accepting all data.
918 sack_consume(c, len);
925 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
926 if(!is_reliable(c)) {
927 c->recv(c, data, len);
928 c->rcv.nxt = seq + len;
932 uint32_t offset = seqdiff(seq, c->rcv.nxt);
934 if(offset + len > c->rcvbuf.maxsize) {
939 handle_out_of_order(c, offset, data, len);
941 handle_in_order(c, data, len);
946 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
947 const uint8_t *ptr = data;
963 print_packet(utcp, "recv", data, len);
965 // Drop packets smaller than the header
969 if(len < sizeof(hdr)) {
974 // Make a copy from the potentially unaligned data to a struct hdr
976 memcpy(&hdr, ptr, sizeof(hdr));
980 // Drop packets with an unknown CTL flag
982 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
987 // Check for auxiliary headers
989 const uint8_t *init = NULL;
991 uint16_t aux = hdr.aux;
994 size_t auxlen = 4 * (aux >> 8) & 0xf;
995 uint8_t auxtype = aux & 0xff;
1004 if(!(hdr.ctl & SYN) || auxlen != 4) {
1020 if(!(aux & 0x800)) {
1029 memcpy(&aux, ptr, 2);
1034 bool has_data = len || (hdr.ctl & (SYN | FIN));
1036 // Try to match the packet to an existing connection
1038 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
1040 // Is it for a new connection?
1043 // Ignore RST packets
1049 // Is it a SYN packet and are we LISTENing?
1051 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1052 // If we don't want to accept it, send a RST back
1053 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
1058 // Try to allocate memory, otherwise send a RST back
1059 c = allocate_connection(utcp, hdr.dst, hdr.src);
1066 // Parse auxilliary information
1073 c->flags = init[3] & 0x7;
1075 c->flags = UTCP_TCP;
1079 // Return SYN+ACK, go to SYN_RECEIVED state
1080 c->snd.wnd = hdr.wnd;
1081 c->rcv.irs = hdr.seq;
1082 c->rcv.nxt = c->rcv.irs + 1;
1083 set_state(c, SYN_RECEIVED);
1090 pkt.hdr.src = c->src;
1091 pkt.hdr.dst = c->dst;
1092 pkt.hdr.ack = c->rcv.irs + 1;
1093 pkt.hdr.seq = c->snd.iss;
1094 pkt.hdr.wnd = c->rcvbuf.maxsize;
1095 pkt.hdr.ctl = SYN | ACK;
1098 pkt.hdr.aux = 0x0101;
1102 pkt.data[3] = c->flags & 0x7;
1103 print_packet(c->utcp, "send", &pkt, sizeof(hdr) + 4);
1104 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1107 print_packet(c->utcp, "send", &pkt, sizeof(hdr));
1108 utcp->send(utcp, &pkt, sizeof(hdr));
1111 // No, we don't want your packets, send a RST back
1119 debug("%p state %s\n", c->utcp, strstate[c->state]);
1121 // In case this is for a CLOSED connection, ignore the packet.
1122 // TODO: make it so incoming packets can never match a CLOSED connection.
1124 if(c->state == CLOSED) {
1125 debug("Got packet for closed connection\n");
1129 // It is for an existing connection.
1131 // 1. Drop invalid packets.
1133 // 1a. Drop packets that should not happen in our current state.
1154 // 1b. Discard data that is not in our receive window.
1156 if(is_reliable(c)) {
1159 if(c->state == SYN_SENT) {
1161 } else if(len == 0) {
1162 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1164 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1166 // cut already accepted front overlapping
1167 if(rcv_offset < 0) {
1168 acceptable = len > (size_t) - rcv_offset;
1173 hdr.seq -= rcv_offset;
1176 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1181 debug("Packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1183 // Ignore unacceptable RST packets.
1188 // Otherwise, continue processing.
1193 c->snd.wnd = hdr.wnd; // TODO: move below
1195 // 1c. Drop packets with an invalid ACK.
1196 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1197 // (= snd.una + c->sndbuf.used).
1199 if(!is_reliable(c)) {
1200 if(hdr.ack != c->snd.last && c->state >= ESTABLISHED) {
1201 hdr.ack = c->snd.una;
1205 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
1206 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1208 // Ignore unacceptable RST packets.
1216 // 2. Handle RST packets
1221 if(!(hdr.ctl & ACK)) {
1225 // The peer has refused our connection.
1226 set_state(c, CLOSED);
1227 errno = ECONNREFUSED;
1230 c->recv(c, NULL, 0);
1233 if(c->poll && !c->reapable) {
1244 // We haven't told the application about this connection yet. Silently delete.
1256 // The peer has aborted our connection.
1257 set_state(c, CLOSED);
1261 c->recv(c, NULL, 0);
1264 if(c->poll && !c->reapable) {
1277 // As far as the application is concerned, the connection has already been closed.
1278 // If it has called utcp_close() already, we can immediately free this connection.
1284 // Otherwise, immediately move to the CLOSED state.
1285 set_state(c, CLOSED);
1298 if(!(hdr.ctl & ACK)) {
1303 // 3. Advance snd.una
1305 advanced = seqdiff(hdr.ack, c->snd.una);
1309 if(c->rtt_start.tv_sec) {
1310 if(c->rtt_seq == hdr.ack) {
1311 struct timeval now, diff;
1312 gettimeofday(&now, NULL);
1313 timersub(&now, &c->rtt_start, &diff);
1314 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
1315 c->rtt_start.tv_sec = 0;
1316 } else if(c->rtt_seq < hdr.ack) {
1317 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1318 c->rtt_start.tv_sec = 0;
1322 int32_t data_acked = advanced;
1330 // TODO: handle FIN as well.
1335 assert(data_acked >= 0);
1338 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1339 assert(data_acked <= bufused);
1343 buffer_get(&c->sndbuf, NULL, data_acked);
1346 // Also advance snd.nxt if possible
1347 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1348 c->snd.nxt = hdr.ack;
1351 c->snd.una = hdr.ack;
1355 // Increase the congestion window according to RFC 5681
1356 if(c->snd.cwnd < c->snd.ssthresh) {
1357 c->snd.cwnd += min(advanced, utcp->mtu); // eq. 2
1359 c->snd.cwnd += max(1, (utcp->mtu * utcp->mtu) / c->snd.cwnd); // eq. 3
1362 if(c->snd.cwnd > c->sndbuf.maxsize) {
1363 c->snd.cwnd = c->sndbuf.maxsize;
1368 // Check if we have sent a FIN that is now ACKed.
1371 if(c->snd.una == c->snd.last) {
1372 set_state(c, FIN_WAIT_2);
1378 if(c->snd.una == c->snd.last) {
1379 gettimeofday(&c->conn_timeout, NULL);
1380 c->conn_timeout.tv_sec += utcp->timeout;
1381 set_state(c, TIME_WAIT);
1390 if(!len && is_reliable(c)) {
1393 if(c->dupack == 3) {
1394 debug("Triplicate ACK\n");
1395 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1396 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1397 //Reset the congestion window so we wait for ACKs.
1398 c->snd.nxt = c->snd.una;
1399 c->snd.cwnd = utcp->mtu;
1401 start_retransmit_timer(c);
1409 if(c->snd.una == c->snd.last) {
1410 stop_retransmit_timer(c);
1411 timerclear(&c->conn_timeout);
1412 } else if(is_reliable(c)) {
1413 start_retransmit_timer(c);
1414 gettimeofday(&c->conn_timeout, NULL);
1415 c->conn_timeout.tv_sec += utcp->timeout;
1420 // 5. Process SYN stuff
1426 // This is a SYNACK. It should always have ACKed the SYN.
1431 c->rcv.irs = hdr.seq;
1432 c->rcv.nxt = hdr.seq;
1436 set_state(c, FIN_WAIT_1);
1438 set_state(c, ESTABLISHED);
1441 // TODO: notify application of this somehow.
1445 // This is a retransmit of a SYN, send back the SYNACK.
1455 // Ehm, no. We should never receive a second SYN.
1465 // SYN counts as one sequence number
1469 // 6. Process new data
1471 if(c->state == SYN_RECEIVED) {
1472 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1477 // Are we still LISTENing?
1479 utcp->accept(c, c->src);
1482 if(c->state != ESTABLISHED) {
1483 set_state(c, CLOSED);
1493 // This should never happen.
1508 // Ehm no, We should never receive more data after a FIN.
1518 handle_incoming_data(c, hdr.seq, ptr, len);
1521 // 7. Process FIN stuff
1523 if((hdr.ctl & FIN) && (!is_reliable(c) || hdr.seq + len == c->rcv.nxt)) {
1527 // This should never happen.
1534 set_state(c, CLOSE_WAIT);
1538 set_state(c, CLOSING);
1542 gettimeofday(&c->conn_timeout, NULL);
1543 c->conn_timeout.tv_sec += utcp->timeout;
1544 set_state(c, TIME_WAIT);
1551 // Ehm, no. We should never receive a second FIN.
1561 // FIN counts as one sequence number
1565 // Inform the application that the peer closed its end of the connection.
1568 c->recv(c, NULL, 0);
1572 // Now we send something back if:
1573 // - we received data, so we have to send back an ACK
1574 // -> sendatleastone = true
1575 // - or we got an ack, so we should maybe send a bit more data
1576 // -> sendatleastone = false
1578 if(is_reliable(c) || hdr.ctl & SYN || hdr.ctl & FIN) {
1593 hdr.ack = hdr.seq + len;
1595 hdr.ctl = RST | ACK;
1598 print_packet(utcp, "send", &hdr, sizeof(hdr));
1599 utcp->send(utcp, &hdr, sizeof(hdr));
1604 int utcp_shutdown(struct utcp_connection *c, int dir) {
1605 debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1613 debug("Error: shutdown() called on closed connection %p\n", c);
1618 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1623 // TCP does not have a provision for stopping incoming packets.
1624 // The best we can do is to just ignore them.
1625 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1629 // The rest of the code deals with shutting down writes.
1630 if(dir == UTCP_SHUT_RD) {
1634 // Only process shutting down writes once.
1652 set_state(c, FIN_WAIT_1);
1660 set_state(c, CLOSING);
1673 if(!timerisset(&c->rtrx_timeout)) {
1674 start_retransmit_timer(c);
1680 static bool reset_connection(struct utcp_connection *c) {
1687 debug("Error: abort() called on closed connection %p\n", c);
1704 set_state(c, CLOSED);
1712 set_state(c, CLOSED);
1722 hdr.seq = c->snd.nxt;
1727 print_packet(c->utcp, "send", &hdr, sizeof(hdr));
1728 c->utcp->send(c->utcp, &hdr, sizeof(hdr));
1732 // Closes all the opened connections
1733 void utcp_abort_all_connections(struct utcp *utcp) {
1739 for(int i = 0; i < utcp->nconnections; i++) {
1740 struct utcp_connection *c = utcp->connections[i];
1742 if(c->reapable || c->state == CLOSED) {
1746 utcp_recv_t old_recv = c->recv;
1747 utcp_poll_t old_poll = c->poll;
1749 reset_connection(c);
1753 old_recv(c, NULL, 0);
1756 if(old_poll && !c->reapable) {
1765 int utcp_close(struct utcp_connection *c) {
1766 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
1776 int utcp_abort(struct utcp_connection *c) {
1777 if(!reset_connection(c)) {
1786 * One call to this function will loop through all connections,
1787 * checking if something needs to be resent or not.
1788 * The return value is the time to the next timeout in milliseconds,
1789 * or maybe a negative value if the timeout is infinite.
1791 struct timeval utcp_timeout(struct utcp *utcp) {
1793 gettimeofday(&now, NULL);
1794 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1796 for(int i = 0; i < utcp->nconnections; i++) {
1797 struct utcp_connection *c = utcp->connections[i];
1803 // delete connections that have been utcp_close()d.
1804 if(c->state == CLOSED) {
1806 debug("Reaping %p\n", c);
1814 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1819 c->recv(c, NULL, 0);
1822 if(c->poll && !c->reapable) {
1829 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1830 debug("retransmit()\n");
1835 if((c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1836 uint32_t len = buffer_free(&c->sndbuf);
1841 } else if(c->state == CLOSED) {
1846 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <)) {
1847 next = c->conn_timeout;
1850 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <)) {
1851 next = c->rtrx_timeout;
1855 struct timeval diff;
1857 timersub(&next, &now, &diff);
1862 bool utcp_is_active(struct utcp *utcp) {
1867 for(int i = 0; i < utcp->nconnections; i++)
1868 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
1875 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1881 struct utcp *utcp = calloc(1, sizeof(*utcp));
1887 utcp->accept = accept;
1888 utcp->pre_accept = pre_accept;
1891 utcp->mtu = DEFAULT_MTU;
1892 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
1893 utcp->rto = START_RTO; // usec
1898 void utcp_exit(struct utcp *utcp) {
1903 for(int i = 0; i < utcp->nconnections; i++) {
1904 struct utcp_connection *c = utcp->connections[i];
1908 c->recv(c, NULL, 0);
1911 if(c->poll && !c->reapable) {
1916 buffer_exit(&c->rcvbuf);
1917 buffer_exit(&c->sndbuf);
1921 free(utcp->connections);
1925 uint16_t utcp_get_mtu(struct utcp *utcp) {
1926 return utcp ? utcp->mtu : 0;
1929 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1930 // TODO: handle overhead of the header
1936 void utcp_reset_timers(struct utcp *utcp) {
1941 struct timeval now, then;
1943 gettimeofday(&now, NULL);
1947 then.tv_sec += utcp->timeout;
1949 for(int i = 0; i < utcp->nconnections; i++) {
1950 struct utcp_connection *c = utcp->connections[i];
1956 if(timerisset(&c->rtrx_timeout)) {
1957 c->rtrx_timeout = now;
1960 if(timerisset(&c->conn_timeout)) {
1961 c->conn_timeout = then;
1964 c->rtt_start.tv_sec = 0;
1967 if(utcp->rto > START_RTO) {
1968 utcp->rto = START_RTO;
1972 int utcp_get_user_timeout(struct utcp *u) {
1973 return u ? u->timeout : 0;
1976 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1978 u->timeout = timeout;
1982 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1983 return c ? c->sndbuf.maxsize : 0;
1986 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1996 return buffer_free(&c->sndbuf);
2003 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
2008 c->sndbuf.maxsize = size;
2010 if(c->sndbuf.maxsize != size) {
2011 c->sndbuf.maxsize = -1;
2015 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
2016 return c ? c->rcvbuf.maxsize : 0;
2019 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
2020 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
2021 return buffer_free(&c->rcvbuf);
2027 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
2032 c->rcvbuf.maxsize = size;
2034 if(c->rcvbuf.maxsize != size) {
2035 c->rcvbuf.maxsize = -1;
2039 size_t utcp_get_sendq(struct utcp_connection *c) {
2040 return c->sndbuf.used;
2043 size_t utcp_get_recvq(struct utcp_connection *c) {
2044 return c->rcvbuf.used;
2047 bool utcp_get_nodelay(struct utcp_connection *c) {
2048 return c ? c->nodelay : false;
2051 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
2053 c->nodelay = nodelay;
2057 bool utcp_get_keepalive(struct utcp_connection *c) {
2058 return c ? c->keepalive : false;
2061 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
2063 c->keepalive = keepalive;
2067 size_t utcp_get_outq(struct utcp_connection *c) {
2068 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
2071 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
2077 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
2083 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
2085 utcp->accept = accept;
2086 utcp->pre_accept = pre_accept;
2090 void utcp_expect_data(struct utcp_connection *c, bool expect) {
2091 if(!c || c->reapable) {
2095 if(!(c->state == ESTABLISHED || c->state == FIN_WAIT_1 || c->state == FIN_WAIT_2)) {
2100 // If we expect data, start the connection timer.
2101 if(!timerisset(&c->conn_timeout)) {
2102 gettimeofday(&c->conn_timeout, NULL);
2103 c->conn_timeout.tv_sec += c->utcp->timeout;
2106 // If we want to cancel expecting data, only clear the timer when there is no unACKed data.
2107 if(c->snd.una == c->snd.last) {
2108 timerclear(&c->conn_timeout);
2113 void utcp_offline(struct utcp *utcp, bool offline) {
2115 gettimeofday(&now, NULL);
2117 for(int i = 0; i < utcp->nconnections; i++) {
2118 struct utcp_connection *c = utcp->connections[i];
2124 utcp_expect_data(c, offline);
2127 if(timerisset(&c->rtrx_timeout)) {
2128 c->rtrx_timeout = now;
2131 utcp->connections[i]->rtt_start.tv_sec = 0;
2135 if(!offline && utcp->rto > START_RTO) {
2136 utcp->rto = START_RTO;