2 utcp.c -- Userspace TCP
3 Copyright (C) 2014-2017 Guus Sliepen <guus@tinc-vpn.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
31 #include <sys/socket.h>
33 #include "utcp_priv.h"
48 #define timersub(a, b, r)\
50 (r)->tv_sec = (a)->tv_sec - (b)->tv_sec;\
51 (r)->tv_usec = (a)->tv_usec - (b)->tv_usec;\
53 (r)->tv_sec--, (r)->tv_usec += USEC_PER_SEC;\
57 static inline size_t min(size_t a, size_t b) {
61 static inline size_t max(size_t a, size_t b) {
68 static void debug(const char *format, ...) {
71 vfprintf(stderr, format, ap);
75 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
78 if(len < sizeof(hdr)) {
79 debug("%p %s: short packet (%lu bytes)\n", utcp, dir, (unsigned long)len);
83 memcpy(&hdr, pkt, sizeof(hdr));
84 debug("%p %s: len=%lu, src=%u dst=%u seq=%u ack=%u wnd=%u aux=%x ctl=", utcp, dir, (unsigned long)len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd, hdr.aux);
102 if(len > sizeof(hdr)) {
103 uint32_t datalen = len - sizeof(hdr);
104 const uint8_t *data = (uint8_t *)pkt + sizeof(hdr);
105 char str[datalen * 2 + 1];
108 for(uint32_t i = 0; i < datalen; i++) {
109 *p++ = "0123456789ABCDEF"[data[i] >> 4];
110 *p++ = "0123456789ABCDEF"[data[i] & 15];
115 debug(" data=%s", str);
121 static void debug_cwnd(struct utcp_connection *c) {
122 debug("snd.cwnd = %u\n", c->snd.cwnd);
125 #define debug(...) do {} while(0)
126 #define print_packet(...) do {} while(0)
127 #define debug_cwnd(...) do {} while(0)
130 static void set_state(struct utcp_connection *c, enum state state) {
133 if(state == ESTABLISHED) {
134 timerclear(&c->conn_timeout);
137 debug("%p new state: %s\n", c->utcp, strstate[state]);
140 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
141 if(seq != c->snd.last) {
156 static bool is_reliable(struct utcp_connection *c) {
157 return c->flags & UTCP_RELIABLE;
160 static int32_t seqdiff(uint32_t a, uint32_t b) {
165 // TODO: convert to ringbuffers to avoid memmove() operations.
167 // Store data into the buffer
168 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
169 debug("buffer_put_at %lu %lu %lu\n", (unsigned long)buf->used, (unsigned long)offset, (unsigned long)len);
171 size_t required = offset + len;
173 if(required > buf->maxsize) {
174 if(offset >= buf->maxsize) {
178 len = buf->maxsize - offset;
179 required = buf->maxsize;
182 if(required > buf->size) {
183 size_t newsize = buf->size;
190 } while(newsize < required);
193 if(newsize > buf->maxsize) {
194 newsize = buf->maxsize;
197 char *newdata = realloc(buf->data, newsize);
207 memcpy(buf->data + offset, data, len);
209 if(required > buf->used) {
210 buf->used = required;
216 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
217 return buffer_put_at(buf, buf->used, data, len);
220 // Get data from the buffer. data can be NULL.
221 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
222 if(len > buf->used) {
227 memcpy(data, buf->data, len);
230 if(len < buf->used) {
231 memmove(buf->data, buf->data + len, buf->used - len);
238 // Copy data from the buffer without removing it.
239 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
240 if(offset >= buf->used) {
244 if(offset + len > buf->used) {
245 len = buf->used - offset;
248 memcpy(data, buf->data + offset, len);
252 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
253 memset(buf, 0, sizeof(*buf));
256 buf->data = malloc(len);
264 buf->maxsize = maxlen;
268 static void buffer_exit(struct buffer *buf) {
270 memset(buf, 0, sizeof(*buf));
273 static uint32_t buffer_free(const struct buffer *buf) {
274 return buf->maxsize - buf->used;
277 // Connections are stored in a sorted list.
278 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
280 static int compare(const void *va, const void *vb) {
283 const struct utcp_connection *a = *(struct utcp_connection **)va;
284 const struct utcp_connection *b = *(struct utcp_connection **)vb;
287 assert(a->src && b->src);
289 int c = (int)a->src - (int)b->src;
295 c = (int)a->dst - (int)b->dst;
299 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
300 if(!utcp->nconnections) {
304 struct utcp_connection key = {
308 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
309 return match ? *match : NULL;
312 static void free_connection(struct utcp_connection *c) {
313 struct utcp *utcp = c->utcp;
314 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
318 int i = cp - utcp->connections;
319 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof(*cp));
320 utcp->nconnections--;
322 buffer_exit(&c->rcvbuf);
323 buffer_exit(&c->sndbuf);
327 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
328 // Check whether this combination of src and dst is free
331 if(find_connection(utcp, src, dst)) {
335 } else { // If src == 0, generate a random port number with the high bit set
336 if(utcp->nconnections >= 32767) {
341 src = rand() | 0x8000;
343 while(find_connection(utcp, src, dst)) {
348 // Allocate memory for the new connection
350 if(utcp->nconnections >= utcp->nallocated) {
351 if(!utcp->nallocated) {
352 utcp->nallocated = 4;
354 utcp->nallocated *= 2;
357 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof(*utcp->connections));
363 utcp->connections = new_array;
366 struct utcp_connection *c = calloc(1, sizeof(*c));
372 if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
377 if(!buffer_init(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
378 buffer_exit(&c->sndbuf);
383 // Fill in the details
392 c->snd.una = c->snd.iss;
393 c->snd.nxt = c->snd.iss + 1;
394 c->snd.last = c->snd.nxt;
395 c->snd.cwnd = (utcp->mtu > 2190 ? 2 : utcp->mtu > 1095 ? 3 : 4) * utcp->mtu;
396 c->snd.ssthresh = ~0;
400 // Add it to the sorted list of connections
402 utcp->connections[utcp->nconnections++] = c;
403 qsort(utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
408 static inline uint32_t absdiff(uint32_t a, uint32_t b) {
416 // Update RTT variables. See RFC 6298.
417 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
419 debug("invalid rtt\n");
423 struct utcp *utcp = c->utcp;
427 utcp->rttvar = rtt / 2;
429 utcp->rttvar = (utcp->rttvar * 3 + absdiff(utcp->srtt, rtt)) / 4;
430 utcp->srtt = (utcp->srtt * 7 + rtt) / 8;
433 utcp->rto = utcp->srtt + max(4 * utcp->rttvar, CLOCK_GRANULARITY);
435 if(utcp->rto > MAX_RTO) {
439 debug("rtt %u srtt %u rttvar %u rto %u\n", rtt, utcp->srtt, utcp->rttvar, utcp->rto);
442 static void start_retransmit_timer(struct utcp_connection *c) {
443 gettimeofday(&c->rtrx_timeout, NULL);
444 c->rtrx_timeout.tv_usec += c->utcp->rto;
446 while(c->rtrx_timeout.tv_usec >= 1000000) {
447 c->rtrx_timeout.tv_usec -= 1000000;
448 c->rtrx_timeout.tv_sec++;
451 debug("timeout set to %lu.%06lu (%u)\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_usec, c->utcp->rto);
454 static void stop_retransmit_timer(struct utcp_connection *c) {
455 timerclear(&c->rtrx_timeout);
456 debug("timeout cleared\n");
459 struct utcp_connection *utcp_connect_ex(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv, uint32_t flags) {
460 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
466 assert((flags & ~0x1f) == 0);
477 pkt.hdr.src = c->src;
478 pkt.hdr.dst = c->dst;
479 pkt.hdr.seq = c->snd.iss;
481 pkt.hdr.wnd = c->rcvbuf.maxsize;
483 pkt.hdr.aux = 0x0101;
487 pkt.init[3] = flags & 0x7;
489 set_state(c, SYN_SENT);
491 print_packet(utcp, "send", &pkt, sizeof(pkt));
492 utcp->send(utcp, &pkt, sizeof(pkt));
494 gettimeofday(&c->conn_timeout, NULL);
495 c->conn_timeout.tv_sec += utcp->timeout;
497 start_retransmit_timer(c);
502 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
503 return utcp_connect_ex(utcp, dst, recv, priv, UTCP_TCP);
506 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
507 if(c->reapable || c->state != SYN_RECEIVED) {
508 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
512 debug("%p accepted, %p %p\n", c, recv, priv);
515 set_state(c, ESTABLISHED);
518 static void ack(struct utcp_connection *c, bool sendatleastone) {
519 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
520 int32_t cwndleft = min(c->snd.cwnd, c->snd.wnd) - seqdiff(c->snd.nxt, c->snd.una);
526 } else if(cwndleft < left) {
529 if(!sendatleastone || cwndleft > c->utcp->mtu) {
530 left -= left % c->utcp->mtu;
534 debug("cwndleft = %d, left = %d\n", cwndleft, left);
536 if(!left && !sendatleastone) {
545 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
551 pkt->hdr.src = c->src;
552 pkt->hdr.dst = c->dst;
553 pkt->hdr.ack = c->rcv.nxt;
554 pkt->hdr.wnd = c->rcvbuf.maxsize;
559 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
560 pkt->hdr.seq = c->snd.nxt;
562 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
564 c->snd.nxt += seglen;
567 if(seglen && fin_wanted(c, c->snd.nxt)) {
572 if(!c->rtt_start.tv_sec) {
573 // Start RTT measurement
574 gettimeofday(&c->rtt_start, NULL);
575 c->rtt_seq = pkt->hdr.seq + seglen;
576 debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
579 print_packet(c->utcp, "send", pkt, sizeof(pkt->hdr) + seglen);
580 c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen);
586 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
588 debug("Error: send() called on closed connection %p\n", c);
596 debug("Error: send() called on unconnected connection %p\n", c);
611 debug("Error: send() called on closing connection %p\n", c);
616 // Exit early if we have nothing to send.
627 // Check if we need to be able to buffer all data
629 if(c->flags & UTCP_NO_PARTIAL) {
630 if(len > buffer_free(&c->sndbuf)) {
631 if(len > c->sndbuf.maxsize) {
641 // Add data to send buffer.
643 if(is_reliable(c) || (c->state != SYN_SENT && c->state != SYN_RECEIVED)) {
644 len = buffer_put(&c->sndbuf, data, len);
660 // Don't send anything yet if the connection has not fully established yet
662 if(c->state == SYN_SENT || c->state == SYN_RECEIVED) {
668 if(!is_reliable(c)) {
669 c->snd.una = c->snd.nxt = c->snd.last;
670 buffer_get(&c->sndbuf, NULL, c->sndbuf.used);
673 if(is_reliable(c) && !timerisset(&c->rtrx_timeout)) {
674 start_retransmit_timer(c);
677 if(is_reliable(c) && !timerisset(&c->conn_timeout)) {
678 gettimeofday(&c->conn_timeout, NULL);
679 c->conn_timeout.tv_sec += c->utcp->timeout;
685 static void swap_ports(struct hdr *hdr) {
686 uint16_t tmp = hdr->src;
691 static void fast_retransmit(struct utcp_connection *c) {
692 if(c->state == CLOSED || c->snd.last == c->snd.una) {
693 debug("fast_retransmit() called but nothing to retransmit!\n");
697 struct utcp *utcp = c->utcp;
704 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
710 pkt->hdr.src = c->src;
711 pkt->hdr.dst = c->dst;
712 pkt->hdr.wnd = c->rcvbuf.maxsize;
721 // Send unacked data again.
722 pkt->hdr.seq = c->snd.una;
723 pkt->hdr.ack = c->rcv.nxt;
725 uint32_t len = min(seqdiff(c->snd.last, c->snd.una), utcp->mtu);
727 if(fin_wanted(c, c->snd.una + len)) {
732 buffer_copy(&c->sndbuf, pkt->data, 0, len);
733 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + len);
734 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
744 static void retransmit(struct utcp_connection *c) {
745 if(c->state == CLOSED || c->snd.last == c->snd.una) {
746 debug("Retransmit() called but nothing to retransmit!\n");
747 stop_retransmit_timer(c);
751 struct utcp *utcp = c->utcp;
758 pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
764 pkt->hdr.src = c->src;
765 pkt->hdr.dst = c->dst;
766 pkt->hdr.wnd = c->rcvbuf.maxsize;
771 // Send our SYN again
772 pkt->hdr.seq = c->snd.iss;
775 pkt->hdr.aux = 0x0101;
779 pkt->data[3] = c->flags & 0x7;
780 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + 4);
781 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
786 pkt->hdr.seq = c->snd.nxt;
787 pkt->hdr.ack = c->rcv.nxt;
788 pkt->hdr.ctl = SYN | ACK;
789 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr));
790 utcp->send(utcp, pkt, sizeof(pkt->hdr));
798 // Send unacked data again.
799 pkt->hdr.seq = c->snd.una;
800 pkt->hdr.ack = c->rcv.nxt;
802 uint32_t len = seqdiff(c->snd.last, c->snd.una);
804 if(len > utcp->mtu) {
808 if(fin_wanted(c, c->snd.una + len)) {
813 c->snd.nxt = c->snd.una + len;
815 // RFC 5681 slow start after timeout
816 c->snd.ssthresh = max(c->snd.cwnd / 2, utcp->mtu * 2); // eq. 4
817 c->snd.cwnd = utcp->mtu;
820 buffer_copy(&c->sndbuf, pkt->data, 0, len);
821 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + len);
822 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
829 // We shouldn't need to retransmit anything in this state.
833 stop_retransmit_timer(c);
837 start_retransmit_timer(c);
840 if(utcp->rto > MAX_RTO) {
844 c->rtt_start.tv_sec = 0; // invalidate RTT timer
850 /* Update receive buffer and SACK entries after consuming data.
854 * |.....0000..1111111111.....22222......3333|
857 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
858 * to remove data from the receive buffer. The idea is to substract "len"
859 * from the offset of all the SACK entries, and then remove/cut down entries
860 * that are shifted to before the start of the receive buffer.
862 * There are three cases:
863 * - the SACK entry is after ^, in that case just change the offset.
864 * - the SACK entry starts before and ends after ^, so we have to
865 * change both its offset and size.
866 * - the SACK entry is completely before ^, in that case delete it.
868 static void sack_consume(struct utcp_connection *c, size_t len) {
869 debug("sack_consume %lu\n", (unsigned long)len);
871 if(len > c->rcvbuf.used) {
872 debug("All SACK entries consumed");
877 buffer_get(&c->rcvbuf, NULL, len);
879 for(int i = 0; i < NSACKS && c->sacks[i].len;) {
880 if(len < c->sacks[i].offset) {
881 c->sacks[i].offset -= len;
883 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
884 c->sacks[i].len -= len - c->sacks[i].offset;
885 c->sacks[i].offset = 0;
889 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
890 c->sacks[NSACKS - 1].len = 0;
898 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
899 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
903 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
904 debug("out of order packet, offset %u\n", offset);
905 // Packet loss or reordering occured. Store the data in the buffer.
906 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
908 if(rxd < 0 || (size_t)rxd < len) {
912 // Make note of where we put it.
913 for(int i = 0; i < NSACKS; i++) {
914 if(!c->sacks[i].len) { // nothing to merge, add new entry
915 debug("New SACK entry %d\n", i);
916 c->sacks[i].offset = offset;
917 c->sacks[i].len = rxd;
919 } else if(offset < c->sacks[i].offset) {
920 if(offset + rxd < c->sacks[i].offset) { // insert before
921 if(!c->sacks[NSACKS - 1].len) { // only if room left
922 debug("Insert SACK entry at %d\n", i);
923 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
924 c->sacks[i].offset = offset;
925 c->sacks[i].len = rxd;
927 debug("SACK entries full, dropping packet\n");
932 debug("Merge with start of SACK entry at %d\n", i);
933 c->sacks[i].offset = offset;
936 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
937 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
938 debug("Merge with end of SACK entry at %d\n", i);
939 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
940 // TODO: handle potential merge with next entry
947 for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
948 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
952 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
953 // Check if we can process out-of-order data now.
954 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
955 debug("incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
956 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
957 len = max(len, c->sacks[0].offset + c->sacks[0].len);
958 data = c->rcvbuf.data;
962 ssize_t rxd = c->recv(c, data, len);
964 if(rxd < 0 || (size_t)rxd != len) {
965 // TODO: handle the application not accepting all data.
971 sack_consume(c, len);
978 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
979 if(!is_reliable(c)) {
980 c->recv(c, data, len);
981 c->rcv.nxt = seq + len;
985 uint32_t offset = seqdiff(seq, c->rcv.nxt);
987 if(offset + len > c->rcvbuf.maxsize) {
992 handle_out_of_order(c, offset, data, len);
994 handle_in_order(c, data, len);
999 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
1000 const uint8_t *ptr = data;
1016 print_packet(utcp, "recv", data, len);
1018 // Drop packets smaller than the header
1022 if(len < sizeof(hdr)) {
1027 // Make a copy from the potentially unaligned data to a struct hdr
1029 memcpy(&hdr, ptr, sizeof(hdr));
1033 // Drop packets with an unknown CTL flag
1035 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
1040 // Check for auxiliary headers
1042 const uint8_t *init = NULL;
1044 uint16_t aux = hdr.aux;
1047 size_t auxlen = 4 * (aux >> 8) & 0xf;
1048 uint8_t auxtype = aux & 0xff;
1057 if(!(hdr.ctl & SYN) || auxlen != 4) {
1073 if(!(aux & 0x800)) {
1082 memcpy(&aux, ptr, 2);
1087 bool has_data = len || (hdr.ctl & (SYN | FIN));
1089 // Try to match the packet to an existing connection
1091 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
1093 // Is it for a new connection?
1096 // Ignore RST packets
1102 // Is it a SYN packet and are we LISTENing?
1104 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1105 // If we don't want to accept it, send a RST back
1106 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
1111 // Try to allocate memory, otherwise send a RST back
1112 c = allocate_connection(utcp, hdr.dst, hdr.src);
1119 // Parse auxilliary information
1126 c->flags = init[3] & 0x7;
1128 c->flags = UTCP_TCP;
1132 // Return SYN+ACK, go to SYN_RECEIVED state
1133 c->snd.wnd = hdr.wnd;
1134 c->rcv.irs = hdr.seq;
1135 c->rcv.nxt = c->rcv.irs + 1;
1136 set_state(c, SYN_RECEIVED);
1143 pkt.hdr.src = c->src;
1144 pkt.hdr.dst = c->dst;
1145 pkt.hdr.ack = c->rcv.irs + 1;
1146 pkt.hdr.seq = c->snd.iss;
1147 pkt.hdr.wnd = c->rcvbuf.maxsize;
1148 pkt.hdr.ctl = SYN | ACK;
1151 pkt.hdr.aux = 0x0101;
1155 pkt.data[3] = c->flags & 0x7;
1156 print_packet(c->utcp, "send", &pkt, sizeof(hdr) + 4);
1157 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1160 print_packet(c->utcp, "send", &pkt, sizeof(hdr));
1161 utcp->send(utcp, &pkt, sizeof(hdr));
1164 // No, we don't want your packets, send a RST back
1172 debug("%p state %s\n", c->utcp, strstate[c->state]);
1174 // In case this is for a CLOSED connection, ignore the packet.
1175 // TODO: make it so incoming packets can never match a CLOSED connection.
1177 if(c->state == CLOSED) {
1178 debug("Got packet for closed connection\n");
1182 // It is for an existing connection.
1184 // 1. Drop invalid packets.
1186 // 1a. Drop packets that should not happen in our current state.
1207 // 1b. Discard data that is not in our receive window.
1209 if(is_reliable(c)) {
1212 if(c->state == SYN_SENT) {
1214 } else if(len == 0) {
1215 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1217 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1219 // cut already accepted front overlapping
1220 if(rcv_offset < 0) {
1221 acceptable = len > (size_t) - rcv_offset;
1226 hdr.seq -= rcv_offset;
1229 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1234 debug("Packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1236 // Ignore unacceptable RST packets.
1241 // Otherwise, continue processing.
1246 c->snd.wnd = hdr.wnd; // TODO: move below
1248 // 1c. Drop packets with an invalid ACK.
1249 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1250 // (= snd.una + c->sndbuf.used).
1252 if(!is_reliable(c)) {
1253 if(hdr.ack != c->snd.last && c->state >= ESTABLISHED) {
1254 hdr.ack = c->snd.una;
1258 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
1259 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1261 // Ignore unacceptable RST packets.
1269 // 2. Handle RST packets
1274 if(!(hdr.ctl & ACK)) {
1278 // The peer has refused our connection.
1279 set_state(c, CLOSED);
1280 errno = ECONNREFUSED;
1283 c->recv(c, NULL, 0);
1286 if(c->poll && !c->reapable) {
1297 // We haven't told the application about this connection yet. Silently delete.
1309 // The peer has aborted our connection.
1310 set_state(c, CLOSED);
1314 c->recv(c, NULL, 0);
1317 if(c->poll && !c->reapable) {
1330 // As far as the application is concerned, the connection has already been closed.
1331 // If it has called utcp_close() already, we can immediately free this connection.
1337 // Otherwise, immediately move to the CLOSED state.
1338 set_state(c, CLOSED);
1351 if(!(hdr.ctl & ACK)) {
1356 // 3. Advance snd.una
1358 advanced = seqdiff(hdr.ack, c->snd.una);
1362 if(c->rtt_start.tv_sec) {
1363 if(c->rtt_seq == hdr.ack) {
1364 struct timeval now, diff;
1365 gettimeofday(&now, NULL);
1366 timersub(&now, &c->rtt_start, &diff);
1367 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
1368 c->rtt_start.tv_sec = 0;
1369 } else if(c->rtt_seq < hdr.ack) {
1370 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1371 c->rtt_start.tv_sec = 0;
1375 int32_t data_acked = advanced;
1383 // TODO: handle FIN as well.
1388 assert(data_acked >= 0);
1391 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1392 assert(data_acked <= bufused);
1396 buffer_get(&c->sndbuf, NULL, data_acked);
1399 // Also advance snd.nxt if possible
1400 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1401 c->snd.nxt = hdr.ack;
1404 c->snd.una = hdr.ack;
1407 if(c->dupack >= 3) {
1408 c->snd.cwnd = c->snd.ssthresh;
1414 // Increase the congestion window according to RFC 5681
1415 if(c->snd.cwnd < c->snd.ssthresh) {
1416 c->snd.cwnd += min(advanced, utcp->mtu); // eq. 2
1418 c->snd.cwnd += max(1, (utcp->mtu * utcp->mtu) / c->snd.cwnd); // eq. 3
1421 if(c->snd.cwnd > c->sndbuf.maxsize) {
1422 c->snd.cwnd = c->sndbuf.maxsize;
1427 // Check if we have sent a FIN that is now ACKed.
1430 if(c->snd.una == c->snd.last) {
1431 set_state(c, FIN_WAIT_2);
1437 if(c->snd.una == c->snd.last) {
1438 gettimeofday(&c->conn_timeout, NULL);
1439 c->conn_timeout.tv_sec += utcp->timeout;
1440 set_state(c, TIME_WAIT);
1449 if(!len && is_reliable(c)) {
1452 if(c->dupack == 3) {
1453 debug("Triplicate ACK\n");
1455 // RFC 5681 fast recovery
1456 c->snd.ssthresh = max(c->snd.cwnd / 2, utcp->mtu * 2); // eq. 4
1457 c->snd.cwnd = max(c->snd.ssthresh + 3 * utcp->mtu, c->sndbuf.maxsize);
1459 if(c->snd.cwnd > c->sndbuf.maxsize) {
1460 c->snd.cwnd = c->sndbuf.maxsize;
1466 } else if(c->dupack > 3) {
1467 c->snd.cwnd += utcp->mtu;
1469 if(c->snd.cwnd > c->sndbuf.maxsize) {
1470 c->snd.cwnd = c->sndbuf.maxsize;
1481 if(c->snd.una == c->snd.last) {
1482 stop_retransmit_timer(c);
1483 timerclear(&c->conn_timeout);
1484 } else if(is_reliable(c)) {
1485 start_retransmit_timer(c);
1486 gettimeofday(&c->conn_timeout, NULL);
1487 c->conn_timeout.tv_sec += utcp->timeout;
1492 // 5. Process SYN stuff
1498 // This is a SYNACK. It should always have ACKed the SYN.
1503 c->rcv.irs = hdr.seq;
1504 c->rcv.nxt = hdr.seq;
1508 set_state(c, FIN_WAIT_1);
1510 set_state(c, ESTABLISHED);
1513 // TODO: notify application of this somehow.
1517 // This is a retransmit of a SYN, send back the SYNACK.
1527 // Ehm, no. We should never receive a second SYN.
1537 // SYN counts as one sequence number
1541 // 6. Process new data
1543 if(c->state == SYN_RECEIVED) {
1544 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1549 // Are we still LISTENing?
1551 utcp->accept(c, c->src);
1554 if(c->state != ESTABLISHED) {
1555 set_state(c, CLOSED);
1565 // This should never happen.
1580 // Ehm no, We should never receive more data after a FIN.
1590 handle_incoming_data(c, hdr.seq, ptr, len);
1593 // 7. Process FIN stuff
1595 if((hdr.ctl & FIN) && (!is_reliable(c) || hdr.seq + len == c->rcv.nxt)) {
1599 // This should never happen.
1606 set_state(c, CLOSE_WAIT);
1610 set_state(c, CLOSING);
1614 gettimeofday(&c->conn_timeout, NULL);
1615 c->conn_timeout.tv_sec += utcp->timeout;
1616 set_state(c, TIME_WAIT);
1623 // Ehm, no. We should never receive a second FIN.
1633 // FIN counts as one sequence number
1637 // Inform the application that the peer closed its end of the connection.
1640 c->recv(c, NULL, 0);
1644 // Now we send something back if:
1645 // - we received data, so we have to send back an ACK
1646 // -> sendatleastone = true
1647 // - or we got an ack, so we should maybe send a bit more data
1648 // -> sendatleastone = false
1650 if(is_reliable(c) || hdr.ctl & SYN || hdr.ctl & FIN) {
1665 hdr.ack = hdr.seq + len;
1667 hdr.ctl = RST | ACK;
1670 print_packet(utcp, "send", &hdr, sizeof(hdr));
1671 utcp->send(utcp, &hdr, sizeof(hdr));
1676 int utcp_shutdown(struct utcp_connection *c, int dir) {
1677 debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1685 debug("Error: shutdown() called on closed connection %p\n", c);
1690 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1695 // TCP does not have a provision for stopping incoming packets.
1696 // The best we can do is to just ignore them.
1697 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1701 // The rest of the code deals with shutting down writes.
1702 if(dir == UTCP_SHUT_RD) {
1706 // Only process shutting down writes once.
1724 set_state(c, FIN_WAIT_1);
1732 set_state(c, CLOSING);
1745 if(!timerisset(&c->rtrx_timeout)) {
1746 start_retransmit_timer(c);
1752 static bool reset_connection(struct utcp_connection *c) {
1759 debug("Error: abort() called on closed connection %p\n", c);
1776 set_state(c, CLOSED);
1784 set_state(c, CLOSED);
1794 hdr.seq = c->snd.nxt;
1799 print_packet(c->utcp, "send", &hdr, sizeof(hdr));
1800 c->utcp->send(c->utcp, &hdr, sizeof(hdr));
1804 // Closes all the opened connections
1805 void utcp_abort_all_connections(struct utcp *utcp) {
1811 for(int i = 0; i < utcp->nconnections; i++) {
1812 struct utcp_connection *c = utcp->connections[i];
1814 if(c->reapable || c->state == CLOSED) {
1818 utcp_recv_t old_recv = c->recv;
1819 utcp_poll_t old_poll = c->poll;
1821 reset_connection(c);
1825 old_recv(c, NULL, 0);
1828 if(old_poll && !c->reapable) {
1837 int utcp_close(struct utcp_connection *c) {
1838 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
1848 int utcp_abort(struct utcp_connection *c) {
1849 if(!reset_connection(c)) {
1858 * One call to this function will loop through all connections,
1859 * checking if something needs to be resent or not.
1860 * The return value is the time to the next timeout in milliseconds,
1861 * or maybe a negative value if the timeout is infinite.
1863 struct timeval utcp_timeout(struct utcp *utcp) {
1865 gettimeofday(&now, NULL);
1866 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1868 for(int i = 0; i < utcp->nconnections; i++) {
1869 struct utcp_connection *c = utcp->connections[i];
1875 // delete connections that have been utcp_close()d.
1876 if(c->state == CLOSED) {
1878 debug("Reaping %p\n", c);
1886 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1891 c->recv(c, NULL, 0);
1894 if(c->poll && !c->reapable) {
1901 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1902 debug("retransmit()\n");
1907 if((c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1908 uint32_t len = buffer_free(&c->sndbuf);
1913 } else if(c->state == CLOSED) {
1918 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <)) {
1919 next = c->conn_timeout;
1922 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <)) {
1923 next = c->rtrx_timeout;
1927 struct timeval diff;
1929 timersub(&next, &now, &diff);
1934 bool utcp_is_active(struct utcp *utcp) {
1939 for(int i = 0; i < utcp->nconnections; i++)
1940 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
1947 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1953 struct utcp *utcp = calloc(1, sizeof(*utcp));
1959 utcp->accept = accept;
1960 utcp->pre_accept = pre_accept;
1963 utcp->mtu = DEFAULT_MTU;
1964 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
1965 utcp->rto = START_RTO; // usec
1970 void utcp_exit(struct utcp *utcp) {
1975 for(int i = 0; i < utcp->nconnections; i++) {
1976 struct utcp_connection *c = utcp->connections[i];
1980 c->recv(c, NULL, 0);
1983 if(c->poll && !c->reapable) {
1988 buffer_exit(&c->rcvbuf);
1989 buffer_exit(&c->sndbuf);
1993 free(utcp->connections);
1997 uint16_t utcp_get_mtu(struct utcp *utcp) {
1998 return utcp ? utcp->mtu : 0;
2001 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
2002 // TODO: handle overhead of the header
2008 void utcp_reset_timers(struct utcp *utcp) {
2013 struct timeval now, then;
2015 gettimeofday(&now, NULL);
2019 then.tv_sec += utcp->timeout;
2021 for(int i = 0; i < utcp->nconnections; i++) {
2022 struct utcp_connection *c = utcp->connections[i];
2028 if(timerisset(&c->rtrx_timeout)) {
2029 c->rtrx_timeout = now;
2032 if(timerisset(&c->conn_timeout)) {
2033 c->conn_timeout = then;
2036 c->rtt_start.tv_sec = 0;
2039 if(utcp->rto > START_RTO) {
2040 utcp->rto = START_RTO;
2044 int utcp_get_user_timeout(struct utcp *u) {
2045 return u ? u->timeout : 0;
2048 void utcp_set_user_timeout(struct utcp *u, int timeout) {
2050 u->timeout = timeout;
2054 size_t utcp_get_sndbuf(struct utcp_connection *c) {
2055 return c ? c->sndbuf.maxsize : 0;
2058 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
2068 return buffer_free(&c->sndbuf);
2075 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
2080 c->sndbuf.maxsize = size;
2082 if(c->sndbuf.maxsize != size) {
2083 c->sndbuf.maxsize = -1;
2087 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
2088 return c ? c->rcvbuf.maxsize : 0;
2091 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
2092 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
2093 return buffer_free(&c->rcvbuf);
2099 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
2104 c->rcvbuf.maxsize = size;
2106 if(c->rcvbuf.maxsize != size) {
2107 c->rcvbuf.maxsize = -1;
2111 size_t utcp_get_sendq(struct utcp_connection *c) {
2112 return c->sndbuf.used;
2115 size_t utcp_get_recvq(struct utcp_connection *c) {
2116 return c->rcvbuf.used;
2119 bool utcp_get_nodelay(struct utcp_connection *c) {
2120 return c ? c->nodelay : false;
2123 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
2125 c->nodelay = nodelay;
2129 bool utcp_get_keepalive(struct utcp_connection *c) {
2130 return c ? c->keepalive : false;
2133 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
2135 c->keepalive = keepalive;
2139 size_t utcp_get_outq(struct utcp_connection *c) {
2140 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
2143 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
2149 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
2155 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
2157 utcp->accept = accept;
2158 utcp->pre_accept = pre_accept;
2162 void utcp_expect_data(struct utcp_connection *c, bool expect) {
2163 if(!c || c->reapable) {
2167 if(!(c->state == ESTABLISHED || c->state == FIN_WAIT_1 || c->state == FIN_WAIT_2)) {
2172 // If we expect data, start the connection timer.
2173 if(!timerisset(&c->conn_timeout)) {
2174 gettimeofday(&c->conn_timeout, NULL);
2175 c->conn_timeout.tv_sec += c->utcp->timeout;
2178 // If we want to cancel expecting data, only clear the timer when there is no unACKed data.
2179 if(c->snd.una == c->snd.last) {
2180 timerclear(&c->conn_timeout);
2185 void utcp_offline(struct utcp *utcp, bool offline) {
2187 gettimeofday(&now, NULL);
2189 for(int i = 0; i < utcp->nconnections; i++) {
2190 struct utcp_connection *c = utcp->connections[i];
2196 utcp_expect_data(c, offline);
2199 if(timerisset(&c->rtrx_timeout)) {
2200 c->rtrx_timeout = now;
2203 utcp->connections[i]->rtt_start.tv_sec = 0;
2207 if(!offline && utcp->rto > START_RTO) {
2208 utcp->rto = START_RTO;