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 & ~0xf) == 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);
585 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 // Add data to send buffer.
616 len = buffer_put(&c->sndbuf, data, len);
626 if(!is_reliable(c)) {
627 c->snd.una = c->snd.nxt = c->snd.last;
628 buffer_get(&c->sndbuf, NULL, c->sndbuf.used);
631 if(is_reliable(c) && !timerisset(&c->rtrx_timeout)) {
632 start_retransmit_timer(c);
638 static void swap_ports(struct hdr *hdr) {
639 uint16_t tmp = hdr->src;
644 static void retransmit(struct utcp_connection *c) {
645 if(c->state == CLOSED || c->snd.last == c->snd.una) {
646 debug("Retransmit() called but nothing to retransmit!\n");
647 stop_retransmit_timer(c);
651 struct utcp *utcp = c->utcp;
658 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
664 pkt->hdr.src = c->src;
665 pkt->hdr.dst = c->dst;
666 pkt->hdr.wnd = c->rcv.wnd;
671 // Send our SYN again
672 pkt->hdr.seq = c->snd.iss;
675 pkt->hdr.aux = 0x0101;
679 pkt->data[3] = c->flags & 0x7;
680 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + 4);
681 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
686 pkt->hdr.seq = c->snd.nxt;
687 pkt->hdr.ack = c->rcv.nxt;
688 pkt->hdr.ctl = SYN | ACK;
689 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr));
690 utcp->send(utcp, pkt, sizeof(pkt->hdr));
698 // Send unacked data again.
699 pkt->hdr.seq = c->snd.una;
700 pkt->hdr.ack = c->rcv.nxt;
702 uint32_t len = seqdiff(c->snd.last, c->snd.una);
704 if(len > utcp->mtu) {
708 if(fin_wanted(c, c->snd.una + len)) {
713 c->snd.nxt = c->snd.una + len;
714 c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
715 buffer_copy(&c->sndbuf, pkt->data, 0, len);
716 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + len);
717 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
724 // We shouldn't need to retransmit anything in this state.
728 stop_retransmit_timer(c);
732 start_retransmit_timer(c);
735 if(utcp->rto > MAX_RTO) {
739 c->rtt_start.tv_sec = 0; // invalidate RTT timer
745 /* Update receive buffer and SACK entries after consuming data.
749 * |.....0000..1111111111.....22222......3333|
752 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
753 * to remove data from the receive buffer. The idea is to substract "len"
754 * from the offset of all the SACK entries, and then remove/cut down entries
755 * that are shifted to before the start of the receive buffer.
757 * There are three cases:
758 * - the SACK entry is after ^, in that case just change the offset.
759 * - the SACK entry starts before and ends after ^, so we have to
760 * change both its offset and size.
761 * - the SACK entry is completely before ^, in that case delete it.
763 static void sack_consume(struct utcp_connection *c, size_t len) {
764 debug("sack_consume %lu\n", (unsigned long)len);
766 if(len > c->rcvbuf.used) {
767 debug("All SACK entries consumed");
772 buffer_get(&c->rcvbuf, NULL, len);
774 for(int i = 0; i < NSACKS && c->sacks[i].len;) {
775 if(len < c->sacks[i].offset) {
776 c->sacks[i].offset -= len;
778 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
779 c->sacks[i].len -= len - c->sacks[i].offset;
780 c->sacks[i].offset = 0;
784 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
785 c->sacks[NSACKS - 1].len = 0;
793 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
794 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
798 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
799 debug("out of order packet, offset %u\n", offset);
800 // Packet loss or reordering occured. Store the data in the buffer.
801 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
803 if(rxd < 0 || (size_t)rxd < len) {
807 // Make note of where we put it.
808 for(int i = 0; i < NSACKS; i++) {
809 if(!c->sacks[i].len) { // nothing to merge, add new entry
810 debug("New SACK entry %d\n", i);
811 c->sacks[i].offset = offset;
812 c->sacks[i].len = rxd;
814 } else if(offset < c->sacks[i].offset) {
815 if(offset + rxd < c->sacks[i].offset) { // insert before
816 if(!c->sacks[NSACKS - 1].len) { // only if room left
817 debug("Insert SACK entry at %d\n", i);
818 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
819 c->sacks[i].offset = offset;
820 c->sacks[i].len = rxd;
822 debug("SACK entries full, dropping packet\n");
827 debug("Merge with start of SACK entry at %d\n", i);
828 c->sacks[i].offset = offset;
831 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
832 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
833 debug("Merge with end of SACK entry at %d\n", i);
834 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
835 // TODO: handle potential merge with next entry
842 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
843 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
847 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
848 // Check if we can process out-of-order data now.
849 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
850 debug("incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
851 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
852 len = max(len, c->sacks[0].offset + c->sacks[0].len);
853 data = c->rcvbuf.data;
857 ssize_t rxd = c->recv(c, data, len);
859 if(rxd < 0 || (size_t)rxd != len) {
860 // TODO: handle the application not accepting all data.
866 sack_consume(c, len);
873 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
874 if(!is_reliable(c)) {
875 c->recv(c, data, len);
876 c->rcv.nxt = seq + len;
880 uint32_t offset = seqdiff(seq, c->rcv.nxt);
882 if(offset + len > c->rcvbuf.maxsize) {
887 handle_out_of_order(c, offset, data, len);
889 handle_in_order(c, data, len);
894 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
909 print_packet(utcp, "recv", data, len);
911 // Drop packets smaller than the header
915 if(len < sizeof(hdr)) {
920 // Make a copy from the potentially unaligned data to a struct hdr
922 memcpy(&hdr, data, sizeof(hdr));
926 // Drop packets with an unknown CTL flag
928 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
933 // Check for auxiliary headers
935 const uint8_t *init = NULL;
937 uint16_t aux = hdr.aux;
940 size_t auxlen = 4 * (aux >> 8) & 0xf;
941 uint8_t auxtype = aux & 0xff;
950 if(!(hdr.ctl & SYN) || auxlen != 4) {
975 memcpy(&aux, data, 2);
980 // Try to match the packet to an existing connection
982 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
984 // Is it for a new connection?
987 // Ignore RST packets
993 // Is it a SYN packet and are we LISTENing?
995 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
996 // If we don't want to accept it, send a RST back
997 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
1002 // Try to allocate memory, otherwise send a RST back
1003 c = allocate_connection(utcp, hdr.dst, hdr.src);
1010 // Parse auxilliary information
1017 c->flags = init[3] & 0x7;
1019 c->flags = UTCP_TCP;
1022 // Return SYN+ACK, go to SYN_RECEIVED state
1023 c->snd.wnd = hdr.wnd;
1024 c->rcv.irs = hdr.seq;
1025 c->rcv.nxt = c->rcv.irs + 1;
1026 set_state(c, SYN_RECEIVED);
1033 pkt.hdr.src = c->src;
1034 pkt.hdr.dst = c->dst;
1035 pkt.hdr.ack = c->rcv.irs + 1;
1036 pkt.hdr.seq = c->snd.iss;
1037 pkt.hdr.wnd = c->rcv.wnd;
1038 pkt.hdr.ctl = SYN | ACK;
1041 pkt.hdr.aux = 0x0101;
1045 pkt.data[3] = c->flags & 0x7;
1046 print_packet(c->utcp, "send", &pkt, sizeof(hdr) + 4);
1047 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1050 print_packet(c->utcp, "send", &pkt, sizeof(hdr));
1051 utcp->send(utcp, &pkt, sizeof(hdr));
1054 // No, we don't want your packets, send a RST back
1062 debug("%p state %s\n", c->utcp, strstate[c->state]);
1064 // In case this is for a CLOSED connection, ignore the packet.
1065 // TODO: make it so incoming packets can never match a CLOSED connection.
1067 if(c->state == CLOSED) {
1068 debug("Got packet for closed connection\n");
1072 // It is for an existing connection.
1074 uint32_t prevrcvnxt = c->rcv.nxt;
1076 // 1. Drop invalid packets.
1078 // 1a. Drop packets that should not happen in our current state.
1099 // 1b. Drop packets with a sequence number not in our receive window.
1103 if(c->state == SYN_SENT) {
1105 } else if(len == 0) {
1106 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1108 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1110 // cut already accepted front overlapping
1111 if(rcv_offset < 0) {
1112 acceptable = len > (size_t) - rcv_offset;
1117 hdr.seq -= rcv_offset;
1120 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1125 debug("Packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1127 // Ignore unacceptable RST packets.
1132 // Otherwise, continue processing.
1136 c->snd.wnd = hdr.wnd; // TODO: move below
1138 // 1c. Drop packets with an invalid ACK.
1139 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1140 // (= snd.una + c->sndbuf.used).
1142 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
1143 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1145 // Ignore unacceptable RST packets.
1153 // 2. Handle RST packets
1158 if(!(hdr.ctl & ACK)) {
1162 // The peer has refused our connection.
1163 set_state(c, CLOSED);
1164 errno = ECONNREFUSED;
1167 c->recv(c, NULL, 0);
1177 // We haven't told the application about this connection yet. Silently delete.
1189 // The peer has aborted our connection.
1190 set_state(c, CLOSED);
1194 c->recv(c, NULL, 0);
1206 // As far as the application is concerned, the connection has already been closed.
1207 // If it has called utcp_close() already, we can immediately free this connection.
1213 // Otherwise, immediately move to the CLOSED state.
1214 set_state(c, CLOSED);
1225 if(!(hdr.ctl & ACK)) {
1229 // 3. Advance snd.una
1231 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
1232 prevrcvnxt = c->rcv.nxt;
1236 if(c->rtt_start.tv_sec) {
1237 if(c->rtt_seq == hdr.ack) {
1238 struct timeval now, diff;
1239 gettimeofday(&now, NULL);
1240 timersub(&now, &c->rtt_start, &diff);
1241 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
1242 c->rtt_start.tv_sec = 0;
1243 } else if(c->rtt_seq < hdr.ack) {
1244 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1245 c->rtt_start.tv_sec = 0;
1249 int32_t data_acked = advanced;
1257 // TODO: handle FIN as well.
1262 assert(data_acked >= 0);
1264 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1265 assert(data_acked <= bufused);
1268 buffer_get(&c->sndbuf, NULL, data_acked);
1271 // Also advance snd.nxt if possible
1272 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1273 c->snd.nxt = hdr.ack;
1276 c->snd.una = hdr.ack;
1279 c->snd.cwnd += utcp->mtu;
1281 if(c->snd.cwnd > c->sndbuf.maxsize) {
1282 c->snd.cwnd = c->sndbuf.maxsize;
1285 // Check if we have sent a FIN that is now ACKed.
1288 if(c->snd.una == c->snd.last) {
1289 set_state(c, FIN_WAIT_2);
1295 if(c->snd.una == c->snd.last) {
1296 gettimeofday(&c->conn_timeout, NULL);
1297 c->conn_timeout.tv_sec += 60;
1298 set_state(c, TIME_WAIT);
1307 if(!len && is_reliable(c)) {
1310 if(c->dupack == 3) {
1311 debug("Triplicate ACK\n");
1312 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1313 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1314 //Reset the congestion window so we wait for ACKs.
1315 c->snd.nxt = c->snd.una;
1316 c->snd.cwnd = utcp->mtu;
1317 start_retransmit_timer(c);
1325 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
1327 if(c->snd.una == c->snd.last) {
1328 stop_retransmit_timer(c);
1329 } else if(is_reliable(c)) {
1330 start_retransmit_timer(c);
1335 // 5. Process SYN stuff
1341 // This is a SYNACK. It should always have ACKed the SYN.
1346 c->rcv.irs = hdr.seq;
1347 c->rcv.nxt = hdr.seq;
1348 set_state(c, ESTABLISHED);
1349 // TODO: notify application of this somehow.
1360 // Ehm, no. We should never receive a second SYN.
1370 // SYN counts as one sequence number
1374 // 6. Process new data
1376 if(c->state == SYN_RECEIVED) {
1377 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1382 // Are we still LISTENing?
1384 utcp->accept(c, c->src);
1387 if(c->state != ESTABLISHED) {
1388 set_state(c, CLOSED);
1398 // This should never happen.
1413 // Ehm no, We should never receive more data after a FIN.
1423 handle_incoming_data(c, hdr.seq, data, len);
1426 // 7. Process FIN stuff
1428 if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1432 // This should never happen.
1439 set_state(c, CLOSE_WAIT);
1443 set_state(c, CLOSING);
1447 gettimeofday(&c->conn_timeout, NULL);
1448 c->conn_timeout.tv_sec += 60;
1449 set_state(c, TIME_WAIT);
1456 // Ehm, no. We should never receive a second FIN.
1466 // FIN counts as one sequence number
1470 // Inform the application that the peer closed the connection.
1473 c->recv(c, NULL, 0);
1477 // Now we send something back if:
1478 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1479 // -> sendatleastone = true
1480 // - or we got an ack, so we should maybe send a bit more data
1481 // -> sendatleastone = false
1483 ack(c, len || prevrcvnxt != c->rcv.nxt);
1495 hdr.ack = hdr.seq + len;
1497 hdr.ctl = RST | ACK;
1500 print_packet(utcp, "send", &hdr, sizeof(hdr));
1501 utcp->send(utcp, &hdr, sizeof(hdr));
1506 int utcp_shutdown(struct utcp_connection *c, int dir) {
1507 debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1515 debug("Error: shutdown() called on closed connection %p\n", c);
1520 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1525 // TCP does not have a provision for stopping incoming packets.
1526 // The best we can do is to just ignore them.
1527 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1531 // The rest of the code deals with shutting down writes.
1532 if(dir == UTCP_SHUT_RD) {
1543 set_state(c, CLOSED);
1548 set_state(c, FIN_WAIT_1);
1556 set_state(c, CLOSING);
1569 if(!timerisset(&c->rtrx_timeout)) {
1570 start_retransmit_timer(c);
1576 int utcp_close(struct utcp_connection *c) {
1577 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
1587 int utcp_abort(struct utcp_connection *c) {
1594 debug("Error: abort() called on closed connection %p\n", c);
1612 set_state(c, CLOSED);
1620 set_state(c, CLOSED);
1630 hdr.seq = c->snd.nxt;
1635 print_packet(c->utcp, "send", &hdr, sizeof(hdr));
1636 c->utcp->send(c->utcp, &hdr, sizeof(hdr));
1641 * One call to this function will loop through all connections,
1642 * checking if something needs to be resent or not.
1643 * The return value is the time to the next timeout in milliseconds,
1644 * or maybe a negative value if the timeout is infinite.
1646 struct timeval utcp_timeout(struct utcp *utcp) {
1648 gettimeofday(&now, NULL);
1649 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1651 for(int i = 0; i < utcp->nconnections; i++) {
1652 struct utcp_connection *c = utcp->connections[i];
1658 // delete connections that have been utcp_close()d.
1659 if(c->state == CLOSED) {
1661 debug("Reaping %p\n", c);
1669 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1674 c->recv(c, NULL, 0);
1680 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1681 debug("retransmit()\n");
1686 if((c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1687 uint32_t len = buffer_free(&c->sndbuf);
1692 } else if(c->state == CLOSED) {
1697 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <)) {
1698 next = c->conn_timeout;
1701 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <)) {
1702 next = c->rtrx_timeout;
1706 struct timeval diff;
1708 timersub(&next, &now, &diff);
1713 bool utcp_is_active(struct utcp *utcp) {
1718 for(int i = 0; i < utcp->nconnections; i++)
1719 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
1726 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1732 struct utcp *utcp = calloc(1, sizeof(*utcp));
1738 utcp->accept = accept;
1739 utcp->pre_accept = pre_accept;
1742 utcp->mtu = DEFAULT_MTU;
1743 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
1744 utcp->rto = START_RTO; // usec
1749 void utcp_exit(struct utcp *utcp) {
1754 for(int i = 0; i < utcp->nconnections; i++) {
1755 struct utcp_connection *c = utcp->connections[i];
1759 c->recv(c, NULL, 0);
1762 buffer_exit(&c->rcvbuf);
1763 buffer_exit(&c->sndbuf);
1767 free(utcp->connections);
1771 uint16_t utcp_get_mtu(struct utcp *utcp) {
1772 return utcp ? utcp->mtu : 0;
1775 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1776 // TODO: handle overhead of the header
1782 void utcp_reset_timers(struct utcp *utcp) {
1787 struct timeval now, then;
1789 gettimeofday(&now, NULL);
1793 then.tv_sec += utcp->timeout;
1795 for(int i = 0; i < utcp->nconnections; i++) {
1796 utcp->connections[i]->rtrx_timeout = now;
1797 utcp->connections[i]->conn_timeout = then;
1798 utcp->connections[i]->rtt_start.tv_sec = 0;
1801 if(utcp->rto > START_RTO) {
1802 utcp->rto = START_RTO;
1806 int utcp_get_user_timeout(struct utcp *u) {
1807 return u ? u->timeout : 0;
1810 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1812 u->timeout = timeout;
1816 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1817 return c ? c->sndbuf.maxsize : 0;
1820 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1821 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1822 return buffer_free(&c->sndbuf);
1828 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1833 c->sndbuf.maxsize = size;
1835 if(c->sndbuf.maxsize != size) {
1836 c->sndbuf.maxsize = -1;
1840 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1841 return c ? c->rcvbuf.maxsize : 0;
1844 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1845 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1846 return buffer_free(&c->rcvbuf);
1852 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1857 c->rcvbuf.maxsize = size;
1859 if(c->rcvbuf.maxsize != size) {
1860 c->rcvbuf.maxsize = -1;
1864 bool utcp_get_nodelay(struct utcp_connection *c) {
1865 return c ? c->nodelay : false;
1868 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1870 c->nodelay = nodelay;
1874 bool utcp_get_keepalive(struct utcp_connection *c) {
1875 return c ? c->keepalive : false;
1878 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1880 c->keepalive = keepalive;
1884 size_t utcp_get_outq(struct utcp_connection *c) {
1885 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1888 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1894 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1900 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
1902 utcp->accept = accept;
1903 utcp->pre_accept = pre_accept;