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) {
530 debug("cwndleft = %d, left = %d\n", cwndleft, left);
532 if(!left && !sendatleastone) {
541 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
547 pkt->hdr.src = c->src;
548 pkt->hdr.dst = c->dst;
549 pkt->hdr.ack = c->rcv.nxt;
550 pkt->hdr.wnd = c->rcvbuf.maxsize;
555 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
556 pkt->hdr.seq = c->snd.nxt;
558 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
560 c->snd.nxt += seglen;
563 if(seglen && fin_wanted(c, c->snd.nxt)) {
568 if(!c->rtt_start.tv_sec) {
569 // Start RTT measurement
570 gettimeofday(&c->rtt_start, NULL);
571 c->rtt_seq = pkt->hdr.seq + seglen;
572 debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
575 print_packet(c->utcp, "send", pkt, sizeof(pkt->hdr) + seglen);
576 c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen);
582 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
584 debug("Error: send() called on closed connection %p\n", c);
592 debug("Error: send() called on unconnected connection %p\n", c);
607 debug("Error: send() called on closing connection %p\n", c);
612 // Exit early if we have nothing to send.
623 // Check if we need to be able to buffer all data
625 if(c->flags & UTCP_NO_PARTIAL) {
626 if(len > buffer_free(&c->sndbuf)) {
627 if(len > c->sndbuf.maxsize) {
637 // Add data to send buffer.
639 if(is_reliable(c) || (c->state != SYN_SENT && c->state != SYN_RECEIVED)) {
640 len = buffer_put(&c->sndbuf, data, len);
656 // Don't send anything yet if the connection has not fully established yet
658 if(c->state == SYN_SENT || c->state == SYN_RECEIVED) {
664 if(!is_reliable(c)) {
665 c->snd.una = c->snd.nxt = c->snd.last;
666 buffer_get(&c->sndbuf, NULL, c->sndbuf.used);
669 if(is_reliable(c) && !timerisset(&c->rtrx_timeout)) {
670 start_retransmit_timer(c);
673 if(is_reliable(c) && !timerisset(&c->conn_timeout)) {
674 gettimeofday(&c->conn_timeout, NULL);
675 c->conn_timeout.tv_sec += c->utcp->timeout;
681 static void swap_ports(struct hdr *hdr) {
682 uint16_t tmp = hdr->src;
687 static void retransmit(struct utcp_connection *c) {
688 if(c->state == CLOSED || c->snd.last == c->snd.una) {
689 debug("Retransmit() called but nothing to retransmit!\n");
690 stop_retransmit_timer(c);
694 struct utcp *utcp = c->utcp;
701 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
707 pkt->hdr.src = c->src;
708 pkt->hdr.dst = c->dst;
709 pkt->hdr.wnd = c->rcvbuf.maxsize;
714 // Send our SYN again
715 pkt->hdr.seq = c->snd.iss;
718 pkt->hdr.aux = 0x0101;
722 pkt->data[3] = c->flags & 0x7;
723 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + 4);
724 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
729 pkt->hdr.seq = c->snd.nxt;
730 pkt->hdr.ack = c->rcv.nxt;
731 pkt->hdr.ctl = SYN | ACK;
732 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr));
733 utcp->send(utcp, pkt, sizeof(pkt->hdr));
741 // Send unacked data again.
742 pkt->hdr.seq = c->snd.una;
743 pkt->hdr.ack = c->rcv.nxt;
745 uint32_t len = seqdiff(c->snd.last, c->snd.una);
747 if(len > utcp->mtu) {
751 if(fin_wanted(c, c->snd.una + len)) {
756 c->snd.nxt = c->snd.una + len;
758 // RFC 5681 slow start after timeout
759 c->snd.ssthresh = max(c->snd.cwnd / 2, utcp->mtu * 2); // eq. 4
760 c->snd.cwnd = utcp->mtu;
763 buffer_copy(&c->sndbuf, pkt->data, 0, len);
764 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + len);
765 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
772 // We shouldn't need to retransmit anything in this state.
776 stop_retransmit_timer(c);
780 start_retransmit_timer(c);
783 if(utcp->rto > MAX_RTO) {
787 c->rtt_start.tv_sec = 0; // invalidate RTT timer
793 /* Update receive buffer and SACK entries after consuming data.
797 * |.....0000..1111111111.....22222......3333|
800 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
801 * to remove data from the receive buffer. The idea is to substract "len"
802 * from the offset of all the SACK entries, and then remove/cut down entries
803 * that are shifted to before the start of the receive buffer.
805 * There are three cases:
806 * - the SACK entry is after ^, in that case just change the offset.
807 * - the SACK entry starts before and ends after ^, so we have to
808 * change both its offset and size.
809 * - the SACK entry is completely before ^, in that case delete it.
811 static void sack_consume(struct utcp_connection *c, size_t len) {
812 debug("sack_consume %lu\n", (unsigned long)len);
814 if(len > c->rcvbuf.used) {
815 debug("All SACK entries consumed");
820 buffer_get(&c->rcvbuf, NULL, len);
822 for(int i = 0; i < NSACKS && c->sacks[i].len;) {
823 if(len < c->sacks[i].offset) {
824 c->sacks[i].offset -= len;
826 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
827 c->sacks[i].len -= len - c->sacks[i].offset;
828 c->sacks[i].offset = 0;
832 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
833 c->sacks[NSACKS - 1].len = 0;
841 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
842 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
846 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
847 debug("out of order packet, offset %u\n", offset);
848 // Packet loss or reordering occured. Store the data in the buffer.
849 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
851 if(rxd < 0 || (size_t)rxd < len) {
855 // Make note of where we put it.
856 for(int i = 0; i < NSACKS; i++) {
857 if(!c->sacks[i].len) { // nothing to merge, add new entry
858 debug("New SACK entry %d\n", i);
859 c->sacks[i].offset = offset;
860 c->sacks[i].len = rxd;
862 } else if(offset < c->sacks[i].offset) {
863 if(offset + rxd < c->sacks[i].offset) { // insert before
864 if(!c->sacks[NSACKS - 1].len) { // only if room left
865 debug("Insert SACK entry at %d\n", i);
866 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
867 c->sacks[i].offset = offset;
868 c->sacks[i].len = rxd;
870 debug("SACK entries full, dropping packet\n");
875 debug("Merge with start of SACK entry at %d\n", i);
876 c->sacks[i].offset = offset;
879 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
880 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
881 debug("Merge with end of SACK entry at %d\n", i);
882 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
883 // TODO: handle potential merge with next entry
890 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
891 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
895 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
896 // Check if we can process out-of-order data now.
897 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
898 debug("incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
899 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
900 len = max(len, c->sacks[0].offset + c->sacks[0].len);
901 data = c->rcvbuf.data;
905 ssize_t rxd = c->recv(c, data, len);
907 if(rxd < 0 || (size_t)rxd != len) {
908 // TODO: handle the application not accepting all data.
914 sack_consume(c, len);
921 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
922 if(!is_reliable(c)) {
923 c->recv(c, data, len);
924 c->rcv.nxt = seq + len;
928 uint32_t offset = seqdiff(seq, c->rcv.nxt);
930 if(offset + len > c->rcvbuf.maxsize) {
935 handle_out_of_order(c, offset, data, len);
937 handle_in_order(c, data, len);
942 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
943 const uint8_t *ptr = data;
959 print_packet(utcp, "recv", data, len);
961 // Drop packets smaller than the header
965 if(len < sizeof(hdr)) {
970 // Make a copy from the potentially unaligned data to a struct hdr
972 memcpy(&hdr, ptr, sizeof(hdr));
976 // Drop packets with an unknown CTL flag
978 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
983 // Check for auxiliary headers
985 const uint8_t *init = NULL;
987 uint16_t aux = hdr.aux;
990 size_t auxlen = 4 * (aux >> 8) & 0xf;
991 uint8_t auxtype = aux & 0xff;
1000 if(!(hdr.ctl & SYN) || auxlen != 4) {
1016 if(!(aux & 0x800)) {
1025 memcpy(&aux, ptr, 2);
1030 bool has_data = len || (hdr.ctl & (SYN | FIN));
1032 // Try to match the packet to an existing connection
1034 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
1036 // Is it for a new connection?
1039 // Ignore RST packets
1045 // Is it a SYN packet and are we LISTENing?
1047 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1048 // If we don't want to accept it, send a RST back
1049 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
1054 // Try to allocate memory, otherwise send a RST back
1055 c = allocate_connection(utcp, hdr.dst, hdr.src);
1062 // Parse auxilliary information
1069 c->flags = init[3] & 0x7;
1071 c->flags = UTCP_TCP;
1075 // Return SYN+ACK, go to SYN_RECEIVED state
1076 c->snd.wnd = hdr.wnd;
1077 c->rcv.irs = hdr.seq;
1078 c->rcv.nxt = c->rcv.irs + 1;
1079 set_state(c, SYN_RECEIVED);
1086 pkt.hdr.src = c->src;
1087 pkt.hdr.dst = c->dst;
1088 pkt.hdr.ack = c->rcv.irs + 1;
1089 pkt.hdr.seq = c->snd.iss;
1090 pkt.hdr.wnd = c->rcvbuf.maxsize;
1091 pkt.hdr.ctl = SYN | ACK;
1094 pkt.hdr.aux = 0x0101;
1098 pkt.data[3] = c->flags & 0x7;
1099 print_packet(c->utcp, "send", &pkt, sizeof(hdr) + 4);
1100 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1103 print_packet(c->utcp, "send", &pkt, sizeof(hdr));
1104 utcp->send(utcp, &pkt, sizeof(hdr));
1107 // No, we don't want your packets, send a RST back
1115 debug("%p state %s\n", c->utcp, strstate[c->state]);
1117 // In case this is for a CLOSED connection, ignore the packet.
1118 // TODO: make it so incoming packets can never match a CLOSED connection.
1120 if(c->state == CLOSED) {
1121 debug("Got packet for closed connection\n");
1125 // It is for an existing connection.
1127 // 1. Drop invalid packets.
1129 // 1a. Drop packets that should not happen in our current state.
1150 // 1b. Discard data that is not in our receive window.
1152 if(is_reliable(c)) {
1155 if(c->state == SYN_SENT) {
1157 } else if(len == 0) {
1158 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1160 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1162 // cut already accepted front overlapping
1163 if(rcv_offset < 0) {
1164 acceptable = len > (size_t) - rcv_offset;
1169 hdr.seq -= rcv_offset;
1172 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1177 debug("Packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1179 // Ignore unacceptable RST packets.
1184 // Otherwise, continue processing.
1189 c->snd.wnd = hdr.wnd; // TODO: move below
1191 // 1c. Drop packets with an invalid ACK.
1192 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1193 // (= snd.una + c->sndbuf.used).
1195 if(!is_reliable(c)) {
1196 if(hdr.ack != c->snd.last && c->state >= ESTABLISHED) {
1197 hdr.ack = c->snd.una;
1201 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
1202 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1204 // Ignore unacceptable RST packets.
1212 // 2. Handle RST packets
1217 if(!(hdr.ctl & ACK)) {
1221 // The peer has refused our connection.
1222 set_state(c, CLOSED);
1223 errno = ECONNREFUSED;
1226 c->recv(c, NULL, 0);
1229 if(c->poll && !c->reapable) {
1240 // We haven't told the application about this connection yet. Silently delete.
1252 // The peer has aborted our connection.
1253 set_state(c, CLOSED);
1257 c->recv(c, NULL, 0);
1260 if(c->poll && !c->reapable) {
1273 // As far as the application is concerned, the connection has already been closed.
1274 // If it has called utcp_close() already, we can immediately free this connection.
1280 // Otherwise, immediately move to the CLOSED state.
1281 set_state(c, CLOSED);
1294 if(!(hdr.ctl & ACK)) {
1299 // 3. Advance snd.una
1301 advanced = seqdiff(hdr.ack, c->snd.una);
1305 if(c->rtt_start.tv_sec) {
1306 if(c->rtt_seq == hdr.ack) {
1307 struct timeval now, diff;
1308 gettimeofday(&now, NULL);
1309 timersub(&now, &c->rtt_start, &diff);
1310 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
1311 c->rtt_start.tv_sec = 0;
1312 } else if(c->rtt_seq < hdr.ack) {
1313 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1314 c->rtt_start.tv_sec = 0;
1318 int32_t data_acked = advanced;
1326 // TODO: handle FIN as well.
1331 assert(data_acked >= 0);
1334 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1335 assert(data_acked <= bufused);
1339 buffer_get(&c->sndbuf, NULL, data_acked);
1342 // Also advance snd.nxt if possible
1343 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1344 c->snd.nxt = hdr.ack;
1347 c->snd.una = hdr.ack;
1351 // Increase the congestion window according to RFC 5681
1352 if(c->snd.cwnd < c->snd.ssthresh) {
1353 c->snd.cwnd += min(advanced, utcp->mtu); // eq. 2
1355 c->snd.cwnd += max(1, (utcp->mtu * utcp->mtu) / c->snd.cwnd); // eq. 3
1358 if(c->snd.cwnd > c->sndbuf.maxsize) {
1359 c->snd.cwnd = c->sndbuf.maxsize;
1364 // Check if we have sent a FIN that is now ACKed.
1367 if(c->snd.una == c->snd.last) {
1368 set_state(c, FIN_WAIT_2);
1374 if(c->snd.una == c->snd.last) {
1375 gettimeofday(&c->conn_timeout, NULL);
1376 c->conn_timeout.tv_sec += utcp->timeout;
1377 set_state(c, TIME_WAIT);
1386 if(!len && is_reliable(c)) {
1389 if(c->dupack == 3) {
1390 debug("Triplicate ACK\n");
1391 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1392 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1393 //Reset the congestion window so we wait for ACKs.
1394 c->snd.nxt = c->snd.una;
1395 c->snd.cwnd = utcp->mtu;
1397 start_retransmit_timer(c);
1405 if(c->snd.una == c->snd.last) {
1406 stop_retransmit_timer(c);
1407 timerclear(&c->conn_timeout);
1408 } else if(is_reliable(c)) {
1409 start_retransmit_timer(c);
1410 gettimeofday(&c->conn_timeout, NULL);
1411 c->conn_timeout.tv_sec += utcp->timeout;
1416 // 5. Process SYN stuff
1422 // This is a SYNACK. It should always have ACKed the SYN.
1427 c->rcv.irs = hdr.seq;
1428 c->rcv.nxt = hdr.seq;
1432 set_state(c, FIN_WAIT_1);
1434 set_state(c, ESTABLISHED);
1437 // TODO: notify application of this somehow.
1441 // This is a retransmit of a SYN, send back the SYNACK.
1451 // Ehm, no. We should never receive a second SYN.
1461 // SYN counts as one sequence number
1465 // 6. Process new data
1467 if(c->state == SYN_RECEIVED) {
1468 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1473 // Are we still LISTENing?
1475 utcp->accept(c, c->src);
1478 if(c->state != ESTABLISHED) {
1479 set_state(c, CLOSED);
1489 // This should never happen.
1504 // Ehm no, We should never receive more data after a FIN.
1514 handle_incoming_data(c, hdr.seq, ptr, len);
1517 // 7. Process FIN stuff
1519 if((hdr.ctl & FIN) && (!is_reliable(c) || hdr.seq + len == c->rcv.nxt)) {
1523 // This should never happen.
1530 set_state(c, CLOSE_WAIT);
1534 set_state(c, CLOSING);
1538 gettimeofday(&c->conn_timeout, NULL);
1539 c->conn_timeout.tv_sec += utcp->timeout;
1540 set_state(c, TIME_WAIT);
1547 // Ehm, no. We should never receive a second FIN.
1557 // FIN counts as one sequence number
1561 // Inform the application that the peer closed its end of the connection.
1564 c->recv(c, NULL, 0);
1568 // Now we send something back if:
1569 // - we received data, so we have to send back an ACK
1570 // -> sendatleastone = true
1571 // - or we got an ack, so we should maybe send a bit more data
1572 // -> sendatleastone = false
1574 if(is_reliable(c) || hdr.ctl & SYN || hdr.ctl & FIN) {
1589 hdr.ack = hdr.seq + len;
1591 hdr.ctl = RST | ACK;
1594 print_packet(utcp, "send", &hdr, sizeof(hdr));
1595 utcp->send(utcp, &hdr, sizeof(hdr));
1600 int utcp_shutdown(struct utcp_connection *c, int dir) {
1601 debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1609 debug("Error: shutdown() called on closed connection %p\n", c);
1614 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1619 // TCP does not have a provision for stopping incoming packets.
1620 // The best we can do is to just ignore them.
1621 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1625 // The rest of the code deals with shutting down writes.
1626 if(dir == UTCP_SHUT_RD) {
1630 // Only process shutting down writes once.
1648 set_state(c, FIN_WAIT_1);
1656 set_state(c, CLOSING);
1669 if(!timerisset(&c->rtrx_timeout)) {
1670 start_retransmit_timer(c);
1676 static bool reset_connection(struct utcp_connection *c) {
1683 debug("Error: abort() called on closed connection %p\n", c);
1700 set_state(c, CLOSED);
1708 set_state(c, CLOSED);
1718 hdr.seq = c->snd.nxt;
1723 print_packet(c->utcp, "send", &hdr, sizeof(hdr));
1724 c->utcp->send(c->utcp, &hdr, sizeof(hdr));
1728 // Closes all the opened connections
1729 void utcp_abort_all_connections(struct utcp *utcp) {
1735 for(int i = 0; i < utcp->nconnections; i++) {
1736 struct utcp_connection *c = utcp->connections[i];
1738 if(c->reapable || c->state == CLOSED) {
1742 utcp_recv_t old_recv = c->recv;
1743 utcp_poll_t old_poll = c->poll;
1745 reset_connection(c);
1749 old_recv(c, NULL, 0);
1752 if(old_poll && !c->reapable) {
1761 int utcp_close(struct utcp_connection *c) {
1762 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
1772 int utcp_abort(struct utcp_connection *c) {
1773 if(!reset_connection(c)) {
1782 * One call to this function will loop through all connections,
1783 * checking if something needs to be resent or not.
1784 * The return value is the time to the next timeout in milliseconds,
1785 * or maybe a negative value if the timeout is infinite.
1787 struct timeval utcp_timeout(struct utcp *utcp) {
1789 gettimeofday(&now, NULL);
1790 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1792 for(int i = 0; i < utcp->nconnections; i++) {
1793 struct utcp_connection *c = utcp->connections[i];
1799 // delete connections that have been utcp_close()d.
1800 if(c->state == CLOSED) {
1802 debug("Reaping %p\n", c);
1810 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1815 c->recv(c, NULL, 0);
1818 if(c->poll && !c->reapable) {
1825 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1826 debug("retransmit()\n");
1831 if((c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1832 uint32_t len = buffer_free(&c->sndbuf);
1837 } else if(c->state == CLOSED) {
1842 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <)) {
1843 next = c->conn_timeout;
1846 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <)) {
1847 next = c->rtrx_timeout;
1851 struct timeval diff;
1853 timersub(&next, &now, &diff);
1858 bool utcp_is_active(struct utcp *utcp) {
1863 for(int i = 0; i < utcp->nconnections; i++)
1864 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
1871 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1877 struct utcp *utcp = calloc(1, sizeof(*utcp));
1883 utcp->accept = accept;
1884 utcp->pre_accept = pre_accept;
1887 utcp->mtu = DEFAULT_MTU;
1888 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
1889 utcp->rto = START_RTO; // usec
1894 void utcp_exit(struct utcp *utcp) {
1899 for(int i = 0; i < utcp->nconnections; i++) {
1900 struct utcp_connection *c = utcp->connections[i];
1904 c->recv(c, NULL, 0);
1907 if(c->poll && !c->reapable) {
1912 buffer_exit(&c->rcvbuf);
1913 buffer_exit(&c->sndbuf);
1917 free(utcp->connections);
1921 uint16_t utcp_get_mtu(struct utcp *utcp) {
1922 return utcp ? utcp->mtu : 0;
1925 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1926 // TODO: handle overhead of the header
1932 void utcp_reset_timers(struct utcp *utcp) {
1937 struct timeval now, then;
1939 gettimeofday(&now, NULL);
1943 then.tv_sec += utcp->timeout;
1945 for(int i = 0; i < utcp->nconnections; i++) {
1946 struct utcp_connection *c = utcp->connections[i];
1952 if(timerisset(&c->rtrx_timeout)) {
1953 c->rtrx_timeout = now;
1956 if(timerisset(&c->conn_timeout)) {
1957 c->conn_timeout = then;
1960 c->rtt_start.tv_sec = 0;
1963 if(utcp->rto > START_RTO) {
1964 utcp->rto = START_RTO;
1968 int utcp_get_user_timeout(struct utcp *u) {
1969 return u ? u->timeout : 0;
1972 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1974 u->timeout = timeout;
1978 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1979 return c ? c->sndbuf.maxsize : 0;
1982 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1992 return buffer_free(&c->sndbuf);
1999 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
2004 c->sndbuf.maxsize = size;
2006 if(c->sndbuf.maxsize != size) {
2007 c->sndbuf.maxsize = -1;
2011 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
2012 return c ? c->rcvbuf.maxsize : 0;
2015 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
2016 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
2017 return buffer_free(&c->rcvbuf);
2023 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
2028 c->rcvbuf.maxsize = size;
2030 if(c->rcvbuf.maxsize != size) {
2031 c->rcvbuf.maxsize = -1;
2035 size_t utcp_get_sendq(struct utcp_connection *c) {
2036 return c->sndbuf.used;
2039 size_t utcp_get_recvq(struct utcp_connection *c) {
2040 return c->rcvbuf.used;
2043 bool utcp_get_nodelay(struct utcp_connection *c) {
2044 return c ? c->nodelay : false;
2047 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
2049 c->nodelay = nodelay;
2053 bool utcp_get_keepalive(struct utcp_connection *c) {
2054 return c ? c->keepalive : false;
2057 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
2059 c->keepalive = keepalive;
2063 size_t utcp_get_outq(struct utcp_connection *c) {
2064 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
2067 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
2073 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
2079 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
2081 utcp->accept = accept;
2082 utcp->pre_accept = pre_accept;
2086 void utcp_expect_data(struct utcp_connection *c, bool expect) {
2087 if(!c || c->reapable) {
2091 if(!(c->state == ESTABLISHED || c->state == FIN_WAIT_1 || c->state == FIN_WAIT_2)) {
2096 // If we expect data, start the connection timer.
2097 if(!timerisset(&c->conn_timeout)) {
2098 gettimeofday(&c->conn_timeout, NULL);
2099 c->conn_timeout.tv_sec += c->utcp->timeout;
2102 // If we want to cancel expecting data, only clear the timer when there is no unACKed data.
2103 if(c->snd.una == c->snd.last) {
2104 timerclear(&c->conn_timeout);
2109 void utcp_offline(struct utcp *utcp, bool offline) {
2111 gettimeofday(&now, NULL);
2113 for(int i = 0; i < utcp->nconnections; i++) {
2114 struct utcp_connection *c = utcp->connections[i];
2120 utcp_expect_data(c, offline);
2123 if(timerisset(&c->rtrx_timeout)) {
2124 c->rtrx_timeout = now;
2127 utcp->connections[i]->rtt_start.tv_sec = 0;
2131 if(!offline && utcp->rto > START_RTO) {
2132 utcp->rto = START_RTO;