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->snd.last = c->snd.nxt;
386 c->snd.cwnd = utcp->mtu;
389 // Add it to the sorted list of connections
391 utcp->connections[utcp->nconnections++] = c;
392 qsort(utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
397 static inline uint32_t absdiff(uint32_t a, uint32_t b) {
405 // Update RTT variables. See RFC 6298.
406 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
408 debug("invalid rtt\n");
412 struct utcp *utcp = c->utcp;
416 utcp->rttvar = rtt / 2;
418 utcp->rttvar = (utcp->rttvar * 3 + absdiff(utcp->srtt, rtt)) / 4;
419 utcp->srtt = (utcp->srtt * 7 + rtt) / 8;
422 utcp->rto = utcp->srtt + max(4 * utcp->rttvar, CLOCK_GRANULARITY);
424 if(utcp->rto > MAX_RTO) {
428 debug("rtt %u srtt %u rttvar %u rto %u\n", rtt, utcp->srtt, utcp->rttvar, utcp->rto);
431 static void start_retransmit_timer(struct utcp_connection *c) {
432 gettimeofday(&c->rtrx_timeout, NULL);
433 c->rtrx_timeout.tv_usec += c->utcp->rto;
435 while(c->rtrx_timeout.tv_usec >= 1000000) {
436 c->rtrx_timeout.tv_usec -= 1000000;
437 c->rtrx_timeout.tv_sec++;
440 debug("timeout set to %lu.%06lu (%u)\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_usec, c->utcp->rto);
443 static void stop_retransmit_timer(struct utcp_connection *c) {
444 timerclear(&c->rtrx_timeout);
445 debug("timeout cleared\n");
448 struct utcp_connection *utcp_connect_ex(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv, uint32_t flags) {
449 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
455 assert((flags & ~0x1f) == 0);
466 pkt.hdr.src = c->src;
467 pkt.hdr.dst = c->dst;
468 pkt.hdr.seq = c->snd.iss;
470 pkt.hdr.wnd = c->rcvbuf.maxsize;
472 pkt.hdr.aux = 0x0101;
476 pkt.init[3] = flags & 0x7;
478 set_state(c, SYN_SENT);
480 print_packet(utcp, "send", &pkt, sizeof(pkt));
481 utcp->send(utcp, &pkt, sizeof(pkt));
483 gettimeofday(&c->conn_timeout, NULL);
484 c->conn_timeout.tv_sec += utcp->timeout;
486 start_retransmit_timer(c);
491 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
492 return utcp_connect_ex(utcp, dst, recv, priv, UTCP_TCP);
495 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
496 if(c->reapable || c->state != SYN_RECEIVED) {
497 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
501 debug("%p accepted, %p %p\n", c, recv, priv);
504 set_state(c, ESTABLISHED);
507 static void ack(struct utcp_connection *c, bool sendatleastone) {
508 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
509 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
510 debug("cwndleft = %d\n", cwndleft);
518 if(cwndleft < left) {
522 if(!left && !sendatleastone) {
531 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
537 pkt->hdr.src = c->src;
538 pkt->hdr.dst = c->dst;
539 pkt->hdr.ack = c->rcv.nxt;
540 pkt->hdr.wnd = c->rcvbuf.maxsize;
545 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
546 pkt->hdr.seq = c->snd.nxt;
548 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
550 c->snd.nxt += seglen;
553 if(seglen && fin_wanted(c, c->snd.nxt)) {
558 if(!c->rtt_start.tv_sec) {
559 // Start RTT measurement
560 gettimeofday(&c->rtt_start, NULL);
561 c->rtt_seq = pkt->hdr.seq + seglen;
562 debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
565 print_packet(c->utcp, "send", pkt, sizeof(pkt->hdr) + seglen);
566 c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen);
572 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
574 debug("Error: send() called on closed connection %p\n", c);
582 debug("Error: send() called on unconnected connection %p\n", c);
597 debug("Error: send() called on closing connection %p\n", c);
602 // Exit early if we have nothing to send.
613 // Check if we need to be able to buffer all data
615 if(c->flags & UTCP_NO_PARTIAL) {
616 if(len > buffer_free(&c->sndbuf)) {
617 if(len > c->sndbuf.maxsize) {
627 // Add data to send buffer.
629 if(is_reliable(c) || (c->state != SYN_SENT && c->state != SYN_RECEIVED)) {
630 len = buffer_put(&c->sndbuf, data, len);
646 // Don't send anything yet if the connection has not fully established yet
648 if(c->state == SYN_SENT || c->state == SYN_RECEIVED) {
654 if(!is_reliable(c)) {
655 c->snd.una = c->snd.nxt = c->snd.last;
656 buffer_get(&c->sndbuf, NULL, c->sndbuf.used);
659 if(is_reliable(c) && !timerisset(&c->rtrx_timeout)) {
660 start_retransmit_timer(c);
663 if(is_reliable(c) && !timerisset(&c->conn_timeout)) {
664 gettimeofday(&c->conn_timeout, NULL);
665 c->conn_timeout.tv_sec += c->utcp->timeout;
671 static void swap_ports(struct hdr *hdr) {
672 uint16_t tmp = hdr->src;
677 static void retransmit(struct utcp_connection *c) {
678 if(c->state == CLOSED || c->snd.last == c->snd.una) {
679 debug("Retransmit() called but nothing to retransmit!\n");
680 stop_retransmit_timer(c);
684 struct utcp *utcp = c->utcp;
691 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
697 pkt->hdr.src = c->src;
698 pkt->hdr.dst = c->dst;
699 pkt->hdr.wnd = c->rcvbuf.maxsize;
704 // Send our SYN again
705 pkt->hdr.seq = c->snd.iss;
708 pkt->hdr.aux = 0x0101;
712 pkt->data[3] = c->flags & 0x7;
713 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + 4);
714 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
719 pkt->hdr.seq = c->snd.nxt;
720 pkt->hdr.ack = c->rcv.nxt;
721 pkt->hdr.ctl = SYN | ACK;
722 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr));
723 utcp->send(utcp, pkt, sizeof(pkt->hdr));
731 // Send unacked data again.
732 pkt->hdr.seq = c->snd.una;
733 pkt->hdr.ack = c->rcv.nxt;
735 uint32_t len = seqdiff(c->snd.last, c->snd.una);
737 if(len > utcp->mtu) {
741 if(fin_wanted(c, c->snd.una + len)) {
746 c->snd.nxt = c->snd.una + len;
747 c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
748 buffer_copy(&c->sndbuf, pkt->data, 0, len);
749 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + len);
750 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
757 // We shouldn't need to retransmit anything in this state.
761 stop_retransmit_timer(c);
765 start_retransmit_timer(c);
768 if(utcp->rto > MAX_RTO) {
772 c->rtt_start.tv_sec = 0; // invalidate RTT timer
778 /* Update receive buffer and SACK entries after consuming data.
782 * |.....0000..1111111111.....22222......3333|
785 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
786 * to remove data from the receive buffer. The idea is to substract "len"
787 * from the offset of all the SACK entries, and then remove/cut down entries
788 * that are shifted to before the start of the receive buffer.
790 * There are three cases:
791 * - the SACK entry is after ^, in that case just change the offset.
792 * - the SACK entry starts before and ends after ^, so we have to
793 * change both its offset and size.
794 * - the SACK entry is completely before ^, in that case delete it.
796 static void sack_consume(struct utcp_connection *c, size_t len) {
797 debug("sack_consume %lu\n", (unsigned long)len);
799 if(len > c->rcvbuf.used) {
800 debug("All SACK entries consumed");
805 buffer_get(&c->rcvbuf, NULL, len);
807 for(int i = 0; i < NSACKS && c->sacks[i].len;) {
808 if(len < c->sacks[i].offset) {
809 c->sacks[i].offset -= len;
811 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
812 c->sacks[i].len -= len - c->sacks[i].offset;
813 c->sacks[i].offset = 0;
817 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
818 c->sacks[NSACKS - 1].len = 0;
826 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
827 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
831 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
832 debug("out of order packet, offset %u\n", offset);
833 // Packet loss or reordering occured. Store the data in the buffer.
834 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
836 if(rxd < 0 || (size_t)rxd < len) {
840 // Make note of where we put it.
841 for(int i = 0; i < NSACKS; i++) {
842 if(!c->sacks[i].len) { // nothing to merge, add new entry
843 debug("New SACK entry %d\n", i);
844 c->sacks[i].offset = offset;
845 c->sacks[i].len = rxd;
847 } else if(offset < c->sacks[i].offset) {
848 if(offset + rxd < c->sacks[i].offset) { // insert before
849 if(!c->sacks[NSACKS - 1].len) { // only if room left
850 debug("Insert SACK entry at %d\n", i);
851 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
852 c->sacks[i].offset = offset;
853 c->sacks[i].len = rxd;
855 debug("SACK entries full, dropping packet\n");
860 debug("Merge with start of SACK entry at %d\n", i);
861 c->sacks[i].offset = offset;
864 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
865 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
866 debug("Merge with end of SACK entry at %d\n", i);
867 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
868 // TODO: handle potential merge with next entry
875 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
876 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
880 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
881 // Check if we can process out-of-order data now.
882 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
883 debug("incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
884 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
885 len = max(len, c->sacks[0].offset + c->sacks[0].len);
886 data = c->rcvbuf.data;
890 ssize_t rxd = c->recv(c, data, len);
892 if(rxd < 0 || (size_t)rxd != len) {
893 // TODO: handle the application not accepting all data.
899 sack_consume(c, len);
906 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
907 if(!is_reliable(c)) {
908 c->recv(c, data, len);
909 c->rcv.nxt = seq + len;
913 uint32_t offset = seqdiff(seq, c->rcv.nxt);
915 if(offset + len > c->rcvbuf.maxsize) {
920 handle_out_of_order(c, offset, data, len);
922 handle_in_order(c, data, len);
927 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
928 const uint8_t *ptr = data;
944 print_packet(utcp, "recv", data, len);
946 // Drop packets smaller than the header
950 if(len < sizeof(hdr)) {
955 // Make a copy from the potentially unaligned data to a struct hdr
957 memcpy(&hdr, ptr, sizeof(hdr));
961 // Drop packets with an unknown CTL flag
963 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
968 // Check for auxiliary headers
970 const uint8_t *init = NULL;
972 uint16_t aux = hdr.aux;
975 size_t auxlen = 4 * (aux >> 8) & 0xf;
976 uint8_t auxtype = aux & 0xff;
985 if(!(hdr.ctl & SYN) || auxlen != 4) {
1001 if(!(aux & 0x800)) {
1010 memcpy(&aux, ptr, 2);
1015 bool has_data = len || (hdr.ctl & (SYN | FIN));
1017 // Try to match the packet to an existing connection
1019 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
1021 // Is it for a new connection?
1024 // Ignore RST packets
1030 // Is it a SYN packet and are we LISTENing?
1032 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1033 // If we don't want to accept it, send a RST back
1034 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
1039 // Try to allocate memory, otherwise send a RST back
1040 c = allocate_connection(utcp, hdr.dst, hdr.src);
1047 // Parse auxilliary information
1054 c->flags = init[3] & 0x7;
1056 c->flags = UTCP_TCP;
1060 // Return SYN+ACK, go to SYN_RECEIVED state
1061 c->snd.wnd = hdr.wnd;
1062 c->rcv.irs = hdr.seq;
1063 c->rcv.nxt = c->rcv.irs + 1;
1064 set_state(c, SYN_RECEIVED);
1071 pkt.hdr.src = c->src;
1072 pkt.hdr.dst = c->dst;
1073 pkt.hdr.ack = c->rcv.irs + 1;
1074 pkt.hdr.seq = c->snd.iss;
1075 pkt.hdr.wnd = c->rcvbuf.maxsize;
1076 pkt.hdr.ctl = SYN | ACK;
1079 pkt.hdr.aux = 0x0101;
1083 pkt.data[3] = c->flags & 0x7;
1084 print_packet(c->utcp, "send", &pkt, sizeof(hdr) + 4);
1085 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1088 print_packet(c->utcp, "send", &pkt, sizeof(hdr));
1089 utcp->send(utcp, &pkt, sizeof(hdr));
1092 // No, we don't want your packets, send a RST back
1100 debug("%p state %s\n", c->utcp, strstate[c->state]);
1102 // In case this is for a CLOSED connection, ignore the packet.
1103 // TODO: make it so incoming packets can never match a CLOSED connection.
1105 if(c->state == CLOSED) {
1106 debug("Got packet for closed connection\n");
1110 // It is for an existing connection.
1112 // 1. Drop invalid packets.
1114 // 1a. Drop packets that should not happen in our current state.
1135 // 1b. Discard data that is not in our receive window.
1137 if(is_reliable(c)) {
1140 if(c->state == SYN_SENT) {
1142 } else if(len == 0) {
1143 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1145 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1147 // cut already accepted front overlapping
1148 if(rcv_offset < 0) {
1149 acceptable = len > (size_t) - rcv_offset;
1154 hdr.seq -= rcv_offset;
1157 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1162 debug("Packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1164 // Ignore unacceptable RST packets.
1169 // Otherwise, continue processing.
1174 c->snd.wnd = hdr.wnd; // TODO: move below
1176 // 1c. Drop packets with an invalid ACK.
1177 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1178 // (= snd.una + c->sndbuf.used).
1180 if(!is_reliable(c)) {
1181 if(hdr.ack != c->snd.last && c->state >= ESTABLISHED) {
1182 hdr.ack = c->snd.una;
1186 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
1187 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1189 // Ignore unacceptable RST packets.
1197 // 2. Handle RST packets
1202 if(!(hdr.ctl & ACK)) {
1206 // The peer has refused our connection.
1207 set_state(c, CLOSED);
1208 errno = ECONNREFUSED;
1211 c->recv(c, NULL, 0);
1214 if(c->poll && !c->reapable) {
1225 // We haven't told the application about this connection yet. Silently delete.
1237 // The peer has aborted our connection.
1238 set_state(c, CLOSED);
1242 c->recv(c, NULL, 0);
1245 if(c->poll && !c->reapable) {
1258 // As far as the application is concerned, the connection has already been closed.
1259 // If it has called utcp_close() already, we can immediately free this connection.
1265 // Otherwise, immediately move to the CLOSED state.
1266 set_state(c, CLOSED);
1279 if(!(hdr.ctl & ACK)) {
1284 // 3. Advance snd.una
1286 advanced = seqdiff(hdr.ack, c->snd.una);
1290 if(c->rtt_start.tv_sec) {
1291 if(c->rtt_seq == hdr.ack) {
1292 struct timeval now, diff;
1293 gettimeofday(&now, NULL);
1294 timersub(&now, &c->rtt_start, &diff);
1295 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
1296 c->rtt_start.tv_sec = 0;
1297 } else if(c->rtt_seq < hdr.ack) {
1298 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1299 c->rtt_start.tv_sec = 0;
1303 int32_t data_acked = advanced;
1311 // TODO: handle FIN as well.
1316 assert(data_acked >= 0);
1319 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1320 assert(data_acked <= bufused);
1324 buffer_get(&c->sndbuf, NULL, data_acked);
1327 // Also advance snd.nxt if possible
1328 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1329 c->snd.nxt = hdr.ack;
1332 c->snd.una = hdr.ack;
1335 c->snd.cwnd += utcp->mtu;
1337 if(c->snd.cwnd > c->sndbuf.maxsize) {
1338 c->snd.cwnd = c->sndbuf.maxsize;
1341 // Check if we have sent a FIN that is now ACKed.
1344 if(c->snd.una == c->snd.last) {
1345 set_state(c, FIN_WAIT_2);
1351 if(c->snd.una == c->snd.last) {
1352 gettimeofday(&c->conn_timeout, NULL);
1353 c->conn_timeout.tv_sec += utcp->timeout;
1354 set_state(c, TIME_WAIT);
1363 if(!len && is_reliable(c)) {
1366 if(c->dupack == 3) {
1367 debug("Triplicate ACK\n");
1368 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1369 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1370 //Reset the congestion window so we wait for ACKs.
1371 c->snd.nxt = c->snd.una;
1372 c->snd.cwnd = utcp->mtu;
1373 start_retransmit_timer(c);
1381 if(c->snd.una == c->snd.last) {
1382 stop_retransmit_timer(c);
1383 timerclear(&c->conn_timeout);
1384 } else if(is_reliable(c)) {
1385 start_retransmit_timer(c);
1386 gettimeofday(&c->conn_timeout, NULL);
1387 c->conn_timeout.tv_sec += utcp->timeout;
1392 // 5. Process SYN stuff
1398 // This is a SYNACK. It should always have ACKed the SYN.
1403 c->rcv.irs = hdr.seq;
1404 c->rcv.nxt = hdr.seq;
1408 set_state(c, FIN_WAIT_1);
1410 set_state(c, ESTABLISHED);
1413 // TODO: notify application of this somehow.
1417 // This is a retransmit of a SYN, send back the SYNACK.
1427 // Ehm, no. We should never receive a second SYN.
1437 // SYN counts as one sequence number
1441 // 6. Process new data
1443 if(c->state == SYN_RECEIVED) {
1444 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1449 // Are we still LISTENing?
1451 utcp->accept(c, c->src);
1454 if(c->state != ESTABLISHED) {
1455 set_state(c, CLOSED);
1465 // This should never happen.
1480 // Ehm no, We should never receive more data after a FIN.
1490 handle_incoming_data(c, hdr.seq, ptr, len);
1493 // 7. Process FIN stuff
1495 if((hdr.ctl & FIN) && (!is_reliable(c) || hdr.seq + len == c->rcv.nxt)) {
1499 // This should never happen.
1506 set_state(c, CLOSE_WAIT);
1510 set_state(c, CLOSING);
1514 gettimeofday(&c->conn_timeout, NULL);
1515 c->conn_timeout.tv_sec += utcp->timeout;
1516 set_state(c, TIME_WAIT);
1523 // Ehm, no. We should never receive a second FIN.
1533 // FIN counts as one sequence number
1537 // Inform the application that the peer closed its end of the connection.
1540 c->recv(c, NULL, 0);
1544 // Now we send something back if:
1545 // - we received data, so we have to send back an ACK
1546 // -> sendatleastone = true
1547 // - or we got an ack, so we should maybe send a bit more data
1548 // -> sendatleastone = false
1550 if(is_reliable(c) || hdr.ctl & SYN || hdr.ctl & FIN) {
1565 hdr.ack = hdr.seq + len;
1567 hdr.ctl = RST | ACK;
1570 print_packet(utcp, "send", &hdr, sizeof(hdr));
1571 utcp->send(utcp, &hdr, sizeof(hdr));
1576 int utcp_shutdown(struct utcp_connection *c, int dir) {
1577 debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1585 debug("Error: shutdown() called on closed connection %p\n", c);
1590 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1595 // TCP does not have a provision for stopping incoming packets.
1596 // The best we can do is to just ignore them.
1597 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1601 // The rest of the code deals with shutting down writes.
1602 if(dir == UTCP_SHUT_RD) {
1606 // Only process shutting down writes once.
1624 set_state(c, FIN_WAIT_1);
1632 set_state(c, CLOSING);
1645 if(!timerisset(&c->rtrx_timeout)) {
1646 start_retransmit_timer(c);
1652 static bool reset_connection(struct utcp_connection *c) {
1659 debug("Error: abort() called on closed connection %p\n", c);
1676 set_state(c, CLOSED);
1684 set_state(c, CLOSED);
1694 hdr.seq = c->snd.nxt;
1699 print_packet(c->utcp, "send", &hdr, sizeof(hdr));
1700 c->utcp->send(c->utcp, &hdr, sizeof(hdr));
1704 // Closes all the opened connections
1705 void utcp_abort_all_connections(struct utcp *utcp) {
1711 for(int i = 0; i < utcp->nconnections; i++) {
1712 struct utcp_connection *c = utcp->connections[i];
1714 if(c->reapable || c->state == CLOSED) {
1718 utcp_recv_t old_recv = c->recv;
1719 utcp_poll_t old_poll = c->poll;
1721 reset_connection(c);
1725 old_recv(c, NULL, 0);
1728 if(old_poll && !c->reapable) {
1737 int utcp_close(struct utcp_connection *c) {
1738 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
1748 int utcp_abort(struct utcp_connection *c) {
1749 if(!reset_connection(c)) {
1758 * One call to this function will loop through all connections,
1759 * checking if something needs to be resent or not.
1760 * The return value is the time to the next timeout in milliseconds,
1761 * or maybe a negative value if the timeout is infinite.
1763 struct timeval utcp_timeout(struct utcp *utcp) {
1765 gettimeofday(&now, NULL);
1766 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1768 for(int i = 0; i < utcp->nconnections; i++) {
1769 struct utcp_connection *c = utcp->connections[i];
1775 // delete connections that have been utcp_close()d.
1776 if(c->state == CLOSED) {
1778 debug("Reaping %p\n", c);
1786 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1791 c->recv(c, NULL, 0);
1794 if(c->poll && !c->reapable) {
1801 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1802 debug("retransmit()\n");
1807 if((c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1808 uint32_t len = buffer_free(&c->sndbuf);
1813 } else if(c->state == CLOSED) {
1818 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <)) {
1819 next = c->conn_timeout;
1822 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <)) {
1823 next = c->rtrx_timeout;
1827 struct timeval diff;
1829 timersub(&next, &now, &diff);
1834 bool utcp_is_active(struct utcp *utcp) {
1839 for(int i = 0; i < utcp->nconnections; i++)
1840 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
1847 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1853 struct utcp *utcp = calloc(1, sizeof(*utcp));
1859 utcp->accept = accept;
1860 utcp->pre_accept = pre_accept;
1863 utcp->mtu = DEFAULT_MTU;
1864 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
1865 utcp->rto = START_RTO; // usec
1870 void utcp_exit(struct utcp *utcp) {
1875 for(int i = 0; i < utcp->nconnections; i++) {
1876 struct utcp_connection *c = utcp->connections[i];
1880 c->recv(c, NULL, 0);
1883 if(c->poll && !c->reapable) {
1888 buffer_exit(&c->rcvbuf);
1889 buffer_exit(&c->sndbuf);
1893 free(utcp->connections);
1897 uint16_t utcp_get_mtu(struct utcp *utcp) {
1898 return utcp ? utcp->mtu : 0;
1901 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1902 // TODO: handle overhead of the header
1908 void utcp_reset_timers(struct utcp *utcp) {
1913 struct timeval now, then;
1915 gettimeofday(&now, NULL);
1919 then.tv_sec += utcp->timeout;
1921 for(int i = 0; i < utcp->nconnections; i++) {
1922 struct utcp_connection *c = utcp->connections[i];
1928 if(timerisset(&c->rtrx_timeout)) {
1929 c->rtrx_timeout = now;
1932 if(timerisset(&c->conn_timeout)) {
1933 c->conn_timeout = then;
1936 c->rtt_start.tv_sec = 0;
1939 if(utcp->rto > START_RTO) {
1940 utcp->rto = START_RTO;
1944 int utcp_get_user_timeout(struct utcp *u) {
1945 return u ? u->timeout : 0;
1948 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1950 u->timeout = timeout;
1954 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1955 return c ? c->sndbuf.maxsize : 0;
1958 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1968 return buffer_free(&c->sndbuf);
1975 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1980 c->sndbuf.maxsize = size;
1982 if(c->sndbuf.maxsize != size) {
1983 c->sndbuf.maxsize = -1;
1987 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1988 return c ? c->rcvbuf.maxsize : 0;
1991 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1992 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1993 return buffer_free(&c->rcvbuf);
1999 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
2004 c->rcvbuf.maxsize = size;
2006 if(c->rcvbuf.maxsize != size) {
2007 c->rcvbuf.maxsize = -1;
2011 size_t utcp_get_sendq(struct utcp_connection *c) {
2012 return c->sndbuf.used;
2015 size_t utcp_get_recvq(struct utcp_connection *c) {
2016 return c->rcvbuf.used;
2019 bool utcp_get_nodelay(struct utcp_connection *c) {
2020 return c ? c->nodelay : false;
2023 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
2025 c->nodelay = nodelay;
2029 bool utcp_get_keepalive(struct utcp_connection *c) {
2030 return c ? c->keepalive : false;
2033 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
2035 c->keepalive = keepalive;
2039 size_t utcp_get_outq(struct utcp_connection *c) {
2040 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
2043 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
2049 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
2055 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
2057 utcp->accept = accept;
2058 utcp->pre_accept = pre_accept;
2062 void utcp_expect_data(struct utcp_connection *c, bool expect) {
2063 if(!c || c->reapable) {
2067 if(!(c->state == ESTABLISHED || c->state == FIN_WAIT_1 || c->state == FIN_WAIT_2)) {
2072 // If we expect data, start the connection timer.
2073 if(!timerisset(&c->conn_timeout)) {
2074 gettimeofday(&c->conn_timeout, NULL);
2075 c->conn_timeout.tv_sec += c->utcp->timeout;
2078 // If we want to cancel expecting data, only clear the timer when there is no unACKed data.
2079 if(c->snd.una == c->snd.last) {
2080 timerclear(&c->conn_timeout);
2085 void utcp_offline(struct utcp *utcp, bool offline) {
2087 gettimeofday(&now, NULL);
2089 for(int i = 0; i < utcp->nconnections; i++) {
2090 struct utcp_connection *c = utcp->connections[i];
2096 utcp_expect_data(c, offline);
2099 if(timerisset(&c->rtrx_timeout)) {
2100 c->rtrx_timeout = now;
2103 utcp->connections[i]->rtt_start.tv_sec = 0;
2107 if(!offline && utcp->rto > START_RTO) {
2108 utcp->rto = START_RTO;