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 max(size_t a, size_t b) {
64 static void debug(const char *format, ...) {
67 vfprintf(stderr, format, ap);
71 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
74 if(len < sizeof(hdr)) {
75 debug("%p %s: short packet (%lu bytes)\n", utcp, dir, (unsigned long)len);
79 memcpy(&hdr, pkt, sizeof(hdr));
80 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);
98 if(len > sizeof(hdr)) {
99 uint32_t datalen = len - sizeof(hdr);
100 const uint8_t *data = (uint8_t *)pkt + sizeof(hdr);
101 char str[datalen * 2 + 1];
104 for(uint32_t i = 0; i < datalen; i++) {
105 *p++ = "0123456789ABCDEF"[data[i] >> 4];
106 *p++ = "0123456789ABCDEF"[data[i] & 15];
111 debug(" data=%s", str);
117 #define debug(...) do {} while(0)
118 #define print_packet(...) do {} while(0)
121 static void set_state(struct utcp_connection *c, enum state state) {
124 if(state == ESTABLISHED) {
125 timerclear(&c->conn_timeout);
128 debug("%p new state: %s\n", c->utcp, strstate[state]);
131 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
132 if(seq != c->snd.last) {
147 static bool is_reliable(struct utcp_connection *c) {
148 return c->flags & UTCP_RELIABLE;
151 static int32_t seqdiff(uint32_t a, uint32_t b) {
156 // TODO: convert to ringbuffers to avoid memmove() operations.
158 // Store data into the buffer
159 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
160 debug("buffer_put_at %lu %lu %lu\n", (unsigned long)buf->used, (unsigned long)offset, (unsigned long)len);
162 size_t required = offset + len;
164 if(required > buf->maxsize) {
165 if(offset >= buf->maxsize) {
169 len = buf->maxsize - offset;
170 required = buf->maxsize;
173 if(required > buf->size) {
174 size_t newsize = buf->size;
181 } while(newsize < required);
184 if(newsize > buf->maxsize) {
185 newsize = buf->maxsize;
188 char *newdata = realloc(buf->data, newsize);
198 memcpy(buf->data + offset, data, len);
200 if(required > buf->used) {
201 buf->used = required;
207 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
208 return buffer_put_at(buf, buf->used, data, len);
211 // Get data from the buffer. data can be NULL.
212 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
213 if(len > buf->used) {
218 memcpy(data, buf->data, len);
221 if(len < buf->used) {
222 memmove(buf->data, buf->data + len, buf->used - len);
229 // Copy data from the buffer without removing it.
230 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
231 if(offset >= buf->used) {
235 if(offset + len > buf->used) {
236 len = buf->used - offset;
239 memcpy(data, buf->data + offset, len);
243 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
244 memset(buf, 0, sizeof(*buf));
247 buf->data = malloc(len);
255 buf->maxsize = maxlen;
259 static void buffer_exit(struct buffer *buf) {
261 memset(buf, 0, sizeof(*buf));
264 static uint32_t buffer_free(const struct buffer *buf) {
265 return buf->maxsize - buf->used;
268 // Connections are stored in a sorted list.
269 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
271 static int compare(const void *va, const void *vb) {
274 const struct utcp_connection *a = *(struct utcp_connection **)va;
275 const struct utcp_connection *b = *(struct utcp_connection **)vb;
278 assert(a->src && b->src);
280 int c = (int)a->src - (int)b->src;
286 c = (int)a->dst - (int)b->dst;
290 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
291 if(!utcp->nconnections) {
295 struct utcp_connection key = {
299 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
300 return match ? *match : NULL;
303 static void free_connection(struct utcp_connection *c) {
304 struct utcp *utcp = c->utcp;
305 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
309 int i = cp - utcp->connections;
310 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof(*cp));
311 utcp->nconnections--;
313 buffer_exit(&c->rcvbuf);
314 buffer_exit(&c->sndbuf);
318 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
319 // Check whether this combination of src and dst is free
322 if(find_connection(utcp, src, dst)) {
326 } else { // If src == 0, generate a random port number with the high bit set
327 if(utcp->nconnections >= 32767) {
332 src = rand() | 0x8000;
334 while(find_connection(utcp, src, dst)) {
339 // Allocate memory for the new connection
341 if(utcp->nconnections >= utcp->nallocated) {
342 if(!utcp->nallocated) {
343 utcp->nallocated = 4;
345 utcp->nallocated *= 2;
348 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof(*utcp->connections));
354 utcp->connections = new_array;
357 struct utcp_connection *c = calloc(1, sizeof(*c));
363 if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
368 if(!buffer_init(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
369 buffer_exit(&c->sndbuf);
374 // Fill in the details
383 c->snd.una = c->snd.iss;
384 c->snd.nxt = c->snd.iss + 1;
385 c->rcv.wnd = utcp->mtu;
386 c->snd.last = c->snd.nxt;
387 c->snd.cwnd = utcp->mtu;
390 // Add it to the sorted list of connections
392 utcp->connections[utcp->nconnections++] = c;
393 qsort(utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
398 static inline uint32_t absdiff(uint32_t a, uint32_t b) {
406 // Update RTT variables. See RFC 6298.
407 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
409 debug("invalid rtt\n");
413 struct utcp *utcp = c->utcp;
417 utcp->rttvar = rtt / 2;
418 utcp->rto = rtt + max(2 * rtt, CLOCK_GRANULARITY);
420 utcp->rttvar = (utcp->rttvar * 3 + absdiff(utcp->srtt, rtt)) / 4;
421 utcp->srtt = (utcp->srtt * 7 + rtt) / 8;
422 utcp->rto = utcp->srtt + max(utcp->rttvar, CLOCK_GRANULARITY);
425 if(utcp->rto > MAX_RTO) {
429 debug("rtt %u srtt %u rttvar %u rto %u\n", rtt, utcp->srtt, utcp->rttvar, utcp->rto);
432 static void start_retransmit_timer(struct utcp_connection *c) {
433 gettimeofday(&c->rtrx_timeout, NULL);
434 c->rtrx_timeout.tv_usec += c->utcp->rto;
436 while(c->rtrx_timeout.tv_usec >= 1000000) {
437 c->rtrx_timeout.tv_usec -= 1000000;
438 c->rtrx_timeout.tv_sec++;
441 debug("timeout set to %lu.%06lu (%u)\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_usec, c->utcp->rto);
444 static void stop_retransmit_timer(struct utcp_connection *c) {
445 timerclear(&c->rtrx_timeout);
446 debug("timeout cleared\n");
449 struct utcp_connection *utcp_connect_ex(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv, uint32_t flags) {
450 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
456 assert((flags & ~0x1f) == 0);
467 pkt.hdr.src = c->src;
468 pkt.hdr.dst = c->dst;
469 pkt.hdr.seq = c->snd.iss;
471 pkt.hdr.wnd = c->rcv.wnd;
473 pkt.hdr.aux = 0x0101;
477 pkt.init[3] = flags & 0x7;
479 set_state(c, SYN_SENT);
481 print_packet(utcp, "send", &pkt, sizeof(pkt));
482 utcp->send(utcp, &pkt, sizeof(pkt));
484 gettimeofday(&c->conn_timeout, NULL);
485 c->conn_timeout.tv_sec += utcp->timeout;
487 start_retransmit_timer(c);
492 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
493 return utcp_connect_ex(utcp, dst, recv, priv, UTCP_TCP);
496 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
497 if(c->reapable || c->state != SYN_RECEIVED) {
498 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
502 debug("%p accepted, %p %p\n", c, recv, priv);
505 set_state(c, ESTABLISHED);
508 static void ack(struct utcp_connection *c, bool sendatleastone) {
509 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
510 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
511 debug("cwndleft = %d\n", cwndleft);
519 if(cwndleft < left) {
523 if(!left && !sendatleastone) {
532 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
538 pkt->hdr.src = c->src;
539 pkt->hdr.dst = c->dst;
540 pkt->hdr.ack = c->rcv.nxt;
541 pkt->hdr.wnd = c->snd.wnd;
546 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
547 pkt->hdr.seq = c->snd.nxt;
549 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
551 c->snd.nxt += seglen;
554 if(seglen && fin_wanted(c, c->snd.nxt)) {
559 if(!c->rtt_start.tv_sec) {
560 // Start RTT measurement
561 gettimeofday(&c->rtt_start, NULL);
562 c->rtt_seq = pkt->hdr.seq + seglen;
563 debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
566 print_packet(c->utcp, "send", pkt, sizeof(pkt->hdr) + seglen);
567 c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen);
573 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
575 debug("Error: send() called on closed connection %p\n", c);
583 debug("Error: send() called on unconnected connection %p\n", c);
598 debug("Error: send() called on closing connection %p\n", c);
603 // Exit early if we have nothing to send.
614 // Check if we need to be able to buffer all data
616 if(c->flags & UTCP_NO_PARTIAL) {
617 if(len > buffer_free(&c->sndbuf)) {
618 if(len > c->sndbuf.maxsize) {
628 // Add data to send buffer.
630 len = buffer_put(&c->sndbuf, data, len);
639 // Don't send anything yet if the connection has not fully established yet
641 if(c->state == SYN_SENT || c->state == SYN_RECEIVED) {
647 if(!is_reliable(c)) {
648 c->snd.una = c->snd.nxt = c->snd.last;
649 buffer_get(&c->sndbuf, NULL, c->sndbuf.used);
652 if(is_reliable(c) && !timerisset(&c->rtrx_timeout)) {
653 start_retransmit_timer(c);
656 if(is_reliable(c) && !timerisset(&c->conn_timeout)) {
657 gettimeofday(&c->conn_timeout, NULL);
658 c->conn_timeout.tv_sec += c->utcp->timeout;
664 static void swap_ports(struct hdr *hdr) {
665 uint16_t tmp = hdr->src;
670 static void retransmit(struct utcp_connection *c) {
671 if(c->state == CLOSED || c->snd.last == c->snd.una) {
672 debug("Retransmit() called but nothing to retransmit!\n");
673 stop_retransmit_timer(c);
677 struct utcp *utcp = c->utcp;
684 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
690 pkt->hdr.src = c->src;
691 pkt->hdr.dst = c->dst;
692 pkt->hdr.wnd = c->rcv.wnd;
697 // Send our SYN again
698 pkt->hdr.seq = c->snd.iss;
701 pkt->hdr.aux = 0x0101;
705 pkt->data[3] = c->flags & 0x7;
706 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + 4);
707 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
712 pkt->hdr.seq = c->snd.nxt;
713 pkt->hdr.ack = c->rcv.nxt;
714 pkt->hdr.ctl = SYN | ACK;
715 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr));
716 utcp->send(utcp, pkt, sizeof(pkt->hdr));
724 // Send unacked data again.
725 pkt->hdr.seq = c->snd.una;
726 pkt->hdr.ack = c->rcv.nxt;
728 uint32_t len = seqdiff(c->snd.last, c->snd.una);
730 if(len > utcp->mtu) {
734 if(fin_wanted(c, c->snd.una + len)) {
739 c->snd.nxt = c->snd.una + len;
740 c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
741 buffer_copy(&c->sndbuf, pkt->data, 0, len);
742 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + len);
743 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
750 // We shouldn't need to retransmit anything in this state.
754 stop_retransmit_timer(c);
758 start_retransmit_timer(c);
761 if(utcp->rto > MAX_RTO) {
765 c->rtt_start.tv_sec = 0; // invalidate RTT timer
771 /* Update receive buffer and SACK entries after consuming data.
775 * |.....0000..1111111111.....22222......3333|
778 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
779 * to remove data from the receive buffer. The idea is to substract "len"
780 * from the offset of all the SACK entries, and then remove/cut down entries
781 * that are shifted to before the start of the receive buffer.
783 * There are three cases:
784 * - the SACK entry is after ^, in that case just change the offset.
785 * - the SACK entry starts before and ends after ^, so we have to
786 * change both its offset and size.
787 * - the SACK entry is completely before ^, in that case delete it.
789 static void sack_consume(struct utcp_connection *c, size_t len) {
790 debug("sack_consume %lu\n", (unsigned long)len);
792 if(len > c->rcvbuf.used) {
793 debug("All SACK entries consumed");
798 buffer_get(&c->rcvbuf, NULL, len);
800 for(int i = 0; i < NSACKS && c->sacks[i].len;) {
801 if(len < c->sacks[i].offset) {
802 c->sacks[i].offset -= len;
804 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
805 c->sacks[i].len -= len - c->sacks[i].offset;
806 c->sacks[i].offset = 0;
810 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
811 c->sacks[NSACKS - 1].len = 0;
819 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
820 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
824 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
825 debug("out of order packet, offset %u\n", offset);
826 // Packet loss or reordering occured. Store the data in the buffer.
827 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
829 if(rxd < 0 || (size_t)rxd < len) {
833 // Make note of where we put it.
834 for(int i = 0; i < NSACKS; i++) {
835 if(!c->sacks[i].len) { // nothing to merge, add new entry
836 debug("New SACK entry %d\n", i);
837 c->sacks[i].offset = offset;
838 c->sacks[i].len = rxd;
840 } else if(offset < c->sacks[i].offset) {
841 if(offset + rxd < c->sacks[i].offset) { // insert before
842 if(!c->sacks[NSACKS - 1].len) { // only if room left
843 debug("Insert SACK entry at %d\n", i);
844 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
845 c->sacks[i].offset = offset;
846 c->sacks[i].len = rxd;
848 debug("SACK entries full, dropping packet\n");
853 debug("Merge with start of SACK entry at %d\n", i);
854 c->sacks[i].offset = offset;
857 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
858 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
859 debug("Merge with end of SACK entry at %d\n", i);
860 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
861 // TODO: handle potential merge with next entry
868 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
869 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
873 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
874 // Check if we can process out-of-order data now.
875 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
876 debug("incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
877 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
878 len = max(len, c->sacks[0].offset + c->sacks[0].len);
879 data = c->rcvbuf.data;
883 ssize_t rxd = c->recv(c, data, len);
885 if(rxd < 0 || (size_t)rxd != len) {
886 // TODO: handle the application not accepting all data.
892 sack_consume(c, len);
899 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
900 if(!is_reliable(c)) {
901 c->recv(c, data, len);
902 c->rcv.nxt = seq + len;
906 uint32_t offset = seqdiff(seq, c->rcv.nxt);
908 if(offset + len > c->rcvbuf.maxsize) {
913 handle_out_of_order(c, offset, data, len);
915 handle_in_order(c, data, len);
920 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
921 const uint8_t *ptr = data;
937 print_packet(utcp, "recv", data, len);
939 // Drop packets smaller than the header
943 if(len < sizeof(hdr)) {
948 // Make a copy from the potentially unaligned data to a struct hdr
950 memcpy(&hdr, ptr, sizeof(hdr));
954 // Drop packets with an unknown CTL flag
956 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
961 // Check for auxiliary headers
963 const uint8_t *init = NULL;
965 uint16_t aux = hdr.aux;
968 size_t auxlen = 4 * (aux >> 8) & 0xf;
969 uint8_t auxtype = aux & 0xff;
978 if(!(hdr.ctl & SYN) || auxlen != 4) {
1003 memcpy(&aux, ptr, 2);
1008 // Try to match the packet to an existing connection
1010 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
1012 // Is it for a new connection?
1015 // Ignore RST packets
1021 // Is it a SYN packet and are we LISTENing?
1023 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1024 // If we don't want to accept it, send a RST back
1025 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
1030 // Try to allocate memory, otherwise send a RST back
1031 c = allocate_connection(utcp, hdr.dst, hdr.src);
1038 // Parse auxilliary information
1045 c->flags = init[3] & 0x7;
1047 c->flags = UTCP_TCP;
1050 // Return SYN+ACK, go to SYN_RECEIVED state
1051 c->snd.wnd = hdr.wnd;
1052 c->rcv.irs = hdr.seq;
1053 c->rcv.nxt = c->rcv.irs + 1;
1054 set_state(c, SYN_RECEIVED);
1061 pkt.hdr.src = c->src;
1062 pkt.hdr.dst = c->dst;
1063 pkt.hdr.ack = c->rcv.irs + 1;
1064 pkt.hdr.seq = c->snd.iss;
1065 pkt.hdr.wnd = c->rcv.wnd;
1066 pkt.hdr.ctl = SYN | ACK;
1069 pkt.hdr.aux = 0x0101;
1073 pkt.data[3] = c->flags & 0x7;
1074 print_packet(c->utcp, "send", &pkt, sizeof(hdr) + 4);
1075 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1078 print_packet(c->utcp, "send", &pkt, sizeof(hdr));
1079 utcp->send(utcp, &pkt, sizeof(hdr));
1082 // No, we don't want your packets, send a RST back
1090 debug("%p state %s\n", c->utcp, strstate[c->state]);
1092 // In case this is for a CLOSED connection, ignore the packet.
1093 // TODO: make it so incoming packets can never match a CLOSED connection.
1095 if(c->state == CLOSED) {
1096 debug("Got packet for closed connection\n");
1100 // It is for an existing connection.
1102 uint32_t prevrcvnxt = c->rcv.nxt;
1104 // 1. Drop invalid packets.
1106 // 1a. Drop packets that should not happen in our current state.
1127 // 1b. Drop packets with a sequence number not in our receive window.
1131 if(c->state == SYN_SENT) {
1133 } else if(len == 0) {
1134 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1136 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1138 // cut already accepted front overlapping
1139 if(rcv_offset < 0) {
1140 acceptable = len > (size_t) - rcv_offset;
1145 hdr.seq -= rcv_offset;
1148 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1153 debug("Packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1155 // Ignore unacceptable RST packets.
1160 // Otherwise, continue processing.
1164 c->snd.wnd = hdr.wnd; // TODO: move below
1166 // 1c. Drop packets with an invalid ACK.
1167 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1168 // (= snd.una + c->sndbuf.used).
1170 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
1171 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1173 // Ignore unacceptable RST packets.
1181 // 2. Handle RST packets
1186 if(!(hdr.ctl & ACK)) {
1190 // The peer has refused our connection.
1191 set_state(c, CLOSED);
1192 errno = ECONNREFUSED;
1195 c->recv(c, NULL, 0);
1198 if(c->poll && !c->reapable) {
1209 // We haven't told the application about this connection yet. Silently delete.
1221 // The peer has aborted our connection.
1222 set_state(c, CLOSED);
1226 c->recv(c, NULL, 0);
1229 if(c->poll && !c->reapable) {
1242 // As far as the application is concerned, the connection has already been closed.
1243 // If it has called utcp_close() already, we can immediately free this connection.
1249 // Otherwise, immediately move to the CLOSED state.
1250 set_state(c, CLOSED);
1263 if(!(hdr.ctl & ACK)) {
1268 // 3. Advance snd.una
1270 advanced = seqdiff(hdr.ack, c->snd.una);
1271 prevrcvnxt = c->rcv.nxt;
1275 if(c->rtt_start.tv_sec) {
1276 if(c->rtt_seq == hdr.ack) {
1277 struct timeval now, diff;
1278 gettimeofday(&now, NULL);
1279 timersub(&now, &c->rtt_start, &diff);
1280 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
1281 c->rtt_start.tv_sec = 0;
1282 } else if(c->rtt_seq < hdr.ack) {
1283 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1284 c->rtt_start.tv_sec = 0;
1288 int32_t data_acked = advanced;
1296 // TODO: handle FIN as well.
1301 assert(data_acked >= 0);
1303 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1304 assert(data_acked <= bufused);
1307 buffer_get(&c->sndbuf, NULL, data_acked);
1310 // Also advance snd.nxt if possible
1311 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1312 c->snd.nxt = hdr.ack;
1315 c->snd.una = hdr.ack;
1318 c->snd.cwnd += utcp->mtu;
1320 if(c->snd.cwnd > c->sndbuf.maxsize) {
1321 c->snd.cwnd = c->sndbuf.maxsize;
1324 // Check if we have sent a FIN that is now ACKed.
1327 if(c->snd.una == c->snd.last) {
1328 set_state(c, FIN_WAIT_2);
1334 if(c->snd.una == c->snd.last) {
1335 gettimeofday(&c->conn_timeout, NULL);
1336 c->conn_timeout.tv_sec += 60;
1337 set_state(c, TIME_WAIT);
1346 if(!len && is_reliable(c)) {
1349 if(c->dupack == 3) {
1350 debug("Triplicate ACK\n");
1351 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1352 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1353 //Reset the congestion window so we wait for ACKs.
1354 c->snd.nxt = c->snd.una;
1355 c->snd.cwnd = utcp->mtu;
1356 start_retransmit_timer(c);
1364 if(c->snd.una == c->snd.last) {
1365 stop_retransmit_timer(c);
1366 timerclear(&c->conn_timeout);
1367 } else if(is_reliable(c)) {
1368 start_retransmit_timer(c);
1369 gettimeofday(&c->conn_timeout, NULL);
1370 c->conn_timeout.tv_sec += utcp->timeout;
1375 // 5. Process SYN stuff
1381 // This is a SYNACK. It should always have ACKed the SYN.
1386 c->rcv.irs = hdr.seq;
1387 c->rcv.nxt = hdr.seq;
1391 set_state(c, FIN_WAIT_1);
1393 set_state(c, ESTABLISHED);
1396 // TODO: notify application of this somehow.
1407 // Ehm, no. We should never receive a second SYN.
1417 // SYN counts as one sequence number
1421 // 6. Process new data
1423 if(c->state == SYN_RECEIVED) {
1424 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1429 // Are we still LISTENing?
1431 utcp->accept(c, c->src);
1434 if(c->state != ESTABLISHED) {
1435 set_state(c, CLOSED);
1445 // This should never happen.
1460 // Ehm no, We should never receive more data after a FIN.
1470 handle_incoming_data(c, hdr.seq, ptr, len);
1473 // 7. Process FIN stuff
1475 if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1479 // This should never happen.
1486 set_state(c, CLOSE_WAIT);
1490 set_state(c, CLOSING);
1494 gettimeofday(&c->conn_timeout, NULL);
1495 c->conn_timeout.tv_sec += 60;
1496 set_state(c, TIME_WAIT);
1503 // Ehm, no. We should never receive a second FIN.
1513 // FIN counts as one sequence number
1517 // Inform the application that the peer closed its end of the connection.
1520 c->recv(c, NULL, 0);
1524 // Now we send something back if:
1525 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1526 // -> sendatleastone = true
1527 // - or we got an ack, so we should maybe send a bit more data
1528 // -> sendatleastone = false
1530 ack(c, len || prevrcvnxt != c->rcv.nxt);
1542 hdr.ack = hdr.seq + len;
1544 hdr.ctl = RST | ACK;
1547 print_packet(utcp, "send", &hdr, sizeof(hdr));
1548 utcp->send(utcp, &hdr, sizeof(hdr));
1553 int utcp_shutdown(struct utcp_connection *c, int dir) {
1554 debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1562 debug("Error: shutdown() called on closed connection %p\n", c);
1567 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1572 // TCP does not have a provision for stopping incoming packets.
1573 // The best we can do is to just ignore them.
1574 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1578 // The rest of the code deals with shutting down writes.
1579 if(dir == UTCP_SHUT_RD) {
1583 // Only process shutting down writes once.
1601 set_state(c, FIN_WAIT_1);
1609 set_state(c, CLOSING);
1622 if(!timerisset(&c->rtrx_timeout)) {
1623 start_retransmit_timer(c);
1629 static bool reset_connection(struct utcp_connection *c) {
1636 debug("Error: abort() called on closed connection %p\n", c);
1653 set_state(c, CLOSED);
1661 set_state(c, CLOSED);
1671 hdr.seq = c->snd.nxt;
1676 print_packet(c->utcp, "send", &hdr, sizeof(hdr));
1677 c->utcp->send(c->utcp, &hdr, sizeof(hdr));
1681 // Closes all the opened connections
1682 void utcp_abort_all_connections(struct utcp *utcp) {
1688 for(int i = 0; i < utcp->nconnections; i++) {
1689 struct utcp_connection *c = utcp->connections[i];
1691 if(c->reapable || c->state == CLOSED) {
1695 utcp_recv_t old_recv = c->recv;
1696 utcp_poll_t old_poll = c->poll;
1698 reset_connection(c);
1702 old_recv(c, NULL, 0);
1705 if(old_poll && !c->reapable) {
1714 int utcp_close(struct utcp_connection *c) {
1715 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
1725 int utcp_abort(struct utcp_connection *c) {
1726 if(!reset_connection(c)) {
1735 * One call to this function will loop through all connections,
1736 * checking if something needs to be resent or not.
1737 * The return value is the time to the next timeout in milliseconds,
1738 * or maybe a negative value if the timeout is infinite.
1740 struct timeval utcp_timeout(struct utcp *utcp) {
1742 gettimeofday(&now, NULL);
1743 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1745 for(int i = 0; i < utcp->nconnections; i++) {
1746 struct utcp_connection *c = utcp->connections[i];
1752 // delete connections that have been utcp_close()d.
1753 if(c->state == CLOSED) {
1755 debug("Reaping %p\n", c);
1763 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1768 c->recv(c, NULL, 0);
1771 if(c->poll && !c->reapable) {
1778 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1779 debug("retransmit()\n");
1784 if((c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1785 uint32_t len = buffer_free(&c->sndbuf);
1790 } else if(c->state == CLOSED) {
1795 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <)) {
1796 next = c->conn_timeout;
1799 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <)) {
1800 next = c->rtrx_timeout;
1804 struct timeval diff;
1806 timersub(&next, &now, &diff);
1811 bool utcp_is_active(struct utcp *utcp) {
1816 for(int i = 0; i < utcp->nconnections; i++)
1817 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
1824 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1830 struct utcp *utcp = calloc(1, sizeof(*utcp));
1836 utcp->accept = accept;
1837 utcp->pre_accept = pre_accept;
1840 utcp->mtu = DEFAULT_MTU;
1841 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
1842 utcp->rto = START_RTO; // usec
1847 void utcp_exit(struct utcp *utcp) {
1852 for(int i = 0; i < utcp->nconnections; i++) {
1853 struct utcp_connection *c = utcp->connections[i];
1857 c->recv(c, NULL, 0);
1860 if(c->poll && !c->reapable) {
1865 buffer_exit(&c->rcvbuf);
1866 buffer_exit(&c->sndbuf);
1870 free(utcp->connections);
1874 uint16_t utcp_get_mtu(struct utcp *utcp) {
1875 return utcp ? utcp->mtu : 0;
1878 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1879 // TODO: handle overhead of the header
1885 void utcp_reset_timers(struct utcp *utcp) {
1890 struct timeval now, then;
1892 gettimeofday(&now, NULL);
1896 then.tv_sec += utcp->timeout;
1898 for(int i = 0; i < utcp->nconnections; i++) {
1899 struct utcp_connection *c = utcp->connections[i];
1905 c->rtrx_timeout = now;
1906 c->conn_timeout = then;
1907 c->rtt_start.tv_sec = 0;
1910 if(utcp->rto > START_RTO) {
1911 utcp->rto = START_RTO;
1915 int utcp_get_user_timeout(struct utcp *u) {
1916 return u ? u->timeout : 0;
1919 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1921 u->timeout = timeout;
1925 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1926 return c ? c->sndbuf.maxsize : 0;
1929 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1939 return buffer_free(&c->sndbuf);
1946 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1951 c->sndbuf.maxsize = size;
1953 if(c->sndbuf.maxsize != size) {
1954 c->sndbuf.maxsize = -1;
1958 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1959 return c ? c->rcvbuf.maxsize : 0;
1962 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1963 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1964 return buffer_free(&c->rcvbuf);
1970 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1975 c->rcvbuf.maxsize = size;
1977 if(c->rcvbuf.maxsize != size) {
1978 c->rcvbuf.maxsize = -1;
1982 size_t utcp_get_sendq(struct utcp_connection *c) {
1983 return c->sndbuf.used;
1986 size_t utcp_get_recvq(struct utcp_connection *c) {
1987 return c->rcvbuf.used;
1990 bool utcp_get_nodelay(struct utcp_connection *c) {
1991 return c ? c->nodelay : false;
1994 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1996 c->nodelay = nodelay;
2000 bool utcp_get_keepalive(struct utcp_connection *c) {
2001 return c ? c->keepalive : false;
2004 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
2006 c->keepalive = keepalive;
2010 size_t utcp_get_outq(struct utcp_connection *c) {
2011 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
2014 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
2020 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
2026 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
2028 utcp->accept = accept;
2029 utcp->pre_accept = pre_accept;
2033 void utcp_expect_data(struct utcp_connection *c, bool expect) {
2034 if(!c || c->reapable) {
2038 if(!(c->state == ESTABLISHED || c->state == FIN_WAIT_1 || c->state == FIN_WAIT_2)) {
2043 // If we expect data, start the connection timer.
2044 if(!timerisset(&c->conn_timeout)) {
2045 gettimeofday(&c->conn_timeout, NULL);
2046 c->conn_timeout.tv_sec += c->utcp->timeout;
2049 // If we want to cancel expecting data, only clear the timer when there is no unACKed data.
2050 if(c->snd.una == c->snd.last) {
2051 timerclear(&c->conn_timeout);
2056 void utcp_offline(struct utcp *utcp, bool offline) {
2057 for(int i = 0; i < utcp->nconnections; i++) {
2058 struct utcp_connection *c = utcp->connections[i];
2061 utcp_expect_data(c, offline);
2063 // If we are online again, reset the retransmission timers, but keep the connection timeout as it is,
2064 // to prevent peers toggling online/offline state frequently from keeping connections alive
2065 // if there is no progress in sending actual data.
2067 gettimeofday(&utcp->connections[i]->rtrx_timeout, NULL);
2068 utcp->connections[i]->rtt_start.tv_sec = 0;
2073 if(!offline && utcp->rto > START_RTO) {
2074 utcp->rto = START_RTO;