2 utcp.c -- Userspace TCP
3 Copyright (C) 2014 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) do {\
49 (r)->tv_sec = (a)->tv_sec - (b)->tv_sec;\
50 (r)->tv_usec = (a)->tv_usec - (b)->tv_usec;\
52 (r)->tv_sec--, (r)->tv_usec += USEC_PER_SEC;\
56 static inline size_t max(size_t a, size_t b) {
63 static void debug(const char *format, ...) {
66 vfprintf(stderr, format, ap);
70 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
72 if(len < sizeof hdr) {
73 debug("%p %s: short packet (%lu bytes)\n", utcp, dir, (unsigned long)len);
77 memcpy(&hdr, pkt, sizeof hdr);
78 debug("%p %s: len=%lu, src=%u dst=%u seq=%u ack=%u wnd=%u ctl=", utcp, dir, (unsigned long)len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd);
88 if(len > sizeof hdr) {
89 uint32_t datalen = len - sizeof hdr;
90 const uint8_t *data = (uint8_t *)pkt + sizeof hdr;
91 char str[datalen * 2 + 1];
94 for(uint32_t i = 0; i < datalen; i++) {
95 *p++ = "0123456789ABCDEF"[data[i] >> 4];
96 *p++ = "0123456789ABCDEF"[data[i] & 15];
100 debug(" data=%s", str);
107 #define print_packet(...)
110 static void set_state(struct utcp_connection *c, enum state state) {
112 if(state == ESTABLISHED)
113 timerclear(&c->conn_timeout);
114 debug("%p new state: %s\n", c->utcp, strstate[state]);
117 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
118 if(seq != c->snd.last)
130 static bool is_reliable(struct utcp_connection *c) {
131 return c->flags & UTCP_RELIABLE;
134 static inline void list_connections(struct utcp *utcp) {
135 debug("%p has %d connections:\n", utcp, utcp->nconnections);
136 for(int i = 0; i < utcp->nconnections; i++)
137 debug(" %u -> %u state %s\n", utcp->connections[i]->src, utcp->connections[i]->dst, strstate[utcp->connections[i]->state]);
140 static int32_t seqdiff(uint32_t a, uint32_t b) {
145 // TODO: convert to ringbuffers to avoid memmove() operations.
147 // Store data into the buffer
148 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
149 debug("buffer_put_at %lu %lu %lu\n", (unsigned long)buf->used, (unsigned long)offset, (unsigned long)len);
151 size_t required = offset + len;
152 if(required > buf->maxsize) {
153 if(offset >= buf->maxsize)
155 len = buf->maxsize - offset;
156 required = buf->maxsize;
159 if(required > buf->size) {
160 size_t newsize = buf->size;
166 } while(newsize < required);
168 if(newsize > buf->maxsize)
169 newsize = buf->maxsize;
170 char *newdata = realloc(buf->data, newsize);
177 memcpy(buf->data + offset, data, len);
178 if(required > buf->used)
179 buf->used = required;
183 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
184 return buffer_put_at(buf, buf->used, data, len);
187 // Get data from the buffer. data can be NULL.
188 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
192 memcpy(data, buf->data, len);
194 memmove(buf->data, buf->data + len, buf->used - len);
199 // Copy data from the buffer without removing it.
200 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
201 if(offset >= buf->used)
203 if(offset + len > buf->used)
204 len = buf->used - offset;
205 memcpy(data, buf->data + offset, len);
209 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
210 memset(buf, 0, sizeof *buf);
212 buf->data = malloc(len);
217 buf->maxsize = maxlen;
221 static void buffer_exit(struct buffer *buf) {
223 memset(buf, 0, sizeof *buf);
226 static uint32_t buffer_free(const struct buffer *buf) {
227 return buf->maxsize - buf->used;
230 // Connections are stored in a sorted list.
231 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
233 static int compare(const void *va, const void *vb) {
236 const struct utcp_connection *a = *(struct utcp_connection **)va;
237 const struct utcp_connection *b = *(struct utcp_connection **)vb;
240 assert(a->src && b->src);
242 int c = (int)a->src - (int)b->src;
245 c = (int)a->dst - (int)b->dst;
249 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
250 if(!utcp->nconnections)
252 struct utcp_connection key = {
256 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
257 return match ? *match : NULL;
260 static void free_connection(struct utcp_connection *c) {
261 struct utcp *utcp = c->utcp;
262 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
266 int i = cp - utcp->connections;
267 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof *cp);
268 utcp->nconnections--;
270 buffer_exit(&c->rcvbuf);
271 buffer_exit(&c->sndbuf);
275 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
276 // Check whether this combination of src and dst is free
279 if(find_connection(utcp, src, dst)) {
283 } else { // If src == 0, generate a random port number with the high bit set
284 if(utcp->nconnections >= 32767) {
288 src = rand() | 0x8000;
289 while(find_connection(utcp, src, dst))
293 // Allocate memory for the new connection
295 if(utcp->nconnections >= utcp->nallocated) {
296 if(!utcp->nallocated)
297 utcp->nallocated = 4;
299 utcp->nallocated *= 2;
300 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
303 utcp->connections = new_array;
306 struct utcp_connection *c = calloc(1, sizeof *c);
310 if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
315 if(!buffer_init(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
316 buffer_exit(&c->sndbuf);
321 // Fill in the details
330 c->snd.una = c->snd.iss;
331 c->snd.nxt = c->snd.iss + 1;
332 c->rcv.wnd = utcp->mtu;
333 c->snd.last = c->snd.nxt;
334 c->snd.cwnd = utcp->mtu;
337 // Add it to the sorted list of connections
339 utcp->connections[utcp->nconnections++] = c;
340 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
345 // Update RTT variables. See RFC 6298.
346 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
348 debug("invalid rtt\n");
352 struct utcp *utcp = c->utcp;
356 utcp->rttvar = rtt / 2;
357 utcp->rto = rtt + max(2 * rtt, CLOCK_GRANULARITY);
359 utcp->rttvar = (utcp->rttvar * 3 + abs(utcp->srtt - rtt)) / 4;
360 utcp->srtt = (utcp->srtt * 7 + rtt) / 8;
361 utcp->rto = utcp->srtt + max(utcp->rttvar, CLOCK_GRANULARITY);
364 if(utcp->rto > MAX_RTO)
367 debug("rtt %u srtt %u rttvar %u rto %u\n", rtt, utcp->srtt, utcp->rttvar, utcp->rto);
370 static void start_retransmit_timer(struct utcp_connection *c) {
371 gettimeofday(&c->rtrx_timeout, NULL);
372 c->rtrx_timeout.tv_usec += c->utcp->rto;
373 while(c->rtrx_timeout.tv_usec >= 1000000) {
374 c->rtrx_timeout.tv_usec -= 1000000;
375 c->rtrx_timeout.tv_sec++;
377 debug("timeout set to %lu.%06lu (%u)\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_usec, c->utcp->rto);
380 static void stop_retransmit_timer(struct utcp_connection *c) {
381 timerclear(&c->rtrx_timeout);
382 debug("timeout cleared\n");
385 struct utcp_connection *utcp_connect_ex(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv, uint32_t flags) {
386 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
390 assert((flags & ~0xf) == 0);
401 pkt.hdr.src = c->src;
402 pkt.hdr.dst = c->dst;
403 pkt.hdr.seq = c->snd.iss;
405 pkt.hdr.wnd = c->rcv.wnd;
407 pkt.hdr.aux = 0x0101;
411 pkt.init[3] = flags & 0x7;
413 set_state(c, SYN_SENT);
415 print_packet(utcp, "send", &pkt, sizeof pkt);
416 utcp->send(utcp, &pkt, sizeof pkt);
418 gettimeofday(&c->conn_timeout, NULL);
419 c->conn_timeout.tv_sec += utcp->timeout;
424 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
425 return utcp_connect_ex(utcp, dst, recv, priv, UTCP_TCP);
428 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
429 if(c->reapable || c->state != SYN_RECEIVED) {
430 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
434 debug("%p accepted, %p %p\n", c, recv, priv);
437 set_state(c, ESTABLISHED);
440 static void ack(struct utcp_connection *c, bool sendatleastone) {
441 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
442 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
443 debug("cwndleft = %d\n", cwndleft);
453 if(!left && !sendatleastone)
461 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
465 pkt->hdr.src = c->src;
466 pkt->hdr.dst = c->dst;
467 pkt->hdr.ack = c->rcv.nxt;
468 pkt->hdr.wnd = c->snd.wnd;
473 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
474 pkt->hdr.seq = c->snd.nxt;
476 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
478 c->snd.nxt += seglen;
481 if(seglen && fin_wanted(c, c->snd.nxt)) {
486 if(!c->rtt_start.tv_sec) {
487 // Start RTT measurement
488 gettimeofday(&c->rtt_start, NULL);
489 c->rtt_seq = pkt->hdr.seq + seglen;
490 debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
493 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
494 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
500 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
502 debug("Error: send() called on closed connection %p\n", c);
512 debug("Error: send() called on unconnected connection %p\n", c);
523 debug("Error: send() called on closing connection %p\n", c);
528 // Exit early if we have nothing to send.
538 // Add data to send buffer.
540 len = buffer_put(&c->sndbuf, data, len);
548 if(!is_reliable(c)) {
549 c->snd.una = c->snd.nxt = c->snd.last;
550 buffer_get(&c->sndbuf, NULL, c->sndbuf.used);
552 if(is_reliable(c) && !timerisset(&c->rtrx_timeout))
553 start_retransmit_timer(c);
557 static void swap_ports(struct hdr *hdr) {
558 uint16_t tmp = hdr->src;
563 static void retransmit(struct utcp_connection *c) {
564 if(c->state == CLOSED || c->snd.last == c->snd.una) {
565 debug("Retransmit() called but nothing to retransmit!\n");
566 stop_retransmit_timer(c);
570 struct utcp *utcp = c->utcp;
577 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
581 pkt->hdr.src = c->src;
582 pkt->hdr.dst = c->dst;
583 pkt->hdr.wnd = c->rcv.wnd;
588 // Send our SYN again
589 pkt->hdr.seq = c->snd.iss;
592 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
593 utcp->send(utcp, pkt, sizeof pkt->hdr);
598 pkt->hdr.seq = c->snd.nxt;
599 pkt->hdr.ack = c->rcv.nxt;
600 pkt->hdr.ctl = SYN | ACK;
601 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
602 utcp->send(utcp, pkt, sizeof pkt->hdr);
610 // Send unacked data again.
611 pkt->hdr.seq = c->snd.una;
612 pkt->hdr.ack = c->rcv.nxt;
614 uint32_t len = seqdiff(c->snd.last, c->snd.una);
617 if(fin_wanted(c, c->snd.una + len)) {
621 c->snd.nxt = c->snd.una + len;
622 c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
623 buffer_copy(&c->sndbuf, pkt->data, 0, len);
624 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
625 utcp->send(utcp, pkt, sizeof pkt->hdr + len);
632 // We shouldn't need to retransmit anything in this state.
636 stop_retransmit_timer(c);
640 start_retransmit_timer(c);
642 if(utcp->rto > MAX_RTO)
644 c->rtt_start.tv_sec = 0; // invalidate RTT timer
650 /* Update receive buffer and SACK entries after consuming data.
654 * |.....0000..1111111111.....22222......3333|
657 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
658 * to remove data from the receive buffer. The idea is to substract "len"
659 * from the offset of all the SACK entries, and then remove/cut down entries
660 * that are shifted to before the start of the receive buffer.
662 * There are three cases:
663 * - the SACK entry is after ^, in that case just change the offset.
664 * - the SACK entry starts before and ends after ^, so we have to
665 * change both its offset and size.
666 * - the SACK entry is completely before ^, in that case delete it.
668 static void sack_consume(struct utcp_connection *c, size_t len) {
669 debug("sack_consume %lu\n", (unsigned long)len);
670 if(len > c->rcvbuf.used) {
671 debug("All SACK entries consumed");
676 buffer_get(&c->rcvbuf, NULL, len);
678 for(int i = 0; i < NSACKS && c->sacks[i].len; ) {
679 if(len < c->sacks[i].offset) {
680 c->sacks[i].offset -= len;
682 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
683 c->sacks[i].len -= len - c->sacks[i].offset;
684 c->sacks[i].offset = 0;
688 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof c->sacks[i]);
689 c->sacks[NSACKS - 1].len = 0;
697 for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
698 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
701 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
702 debug("out of order packet, offset %u\n", offset);
703 // Packet loss or reordering occured. Store the data in the buffer.
704 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
708 // Make note of where we put it.
709 for(int i = 0; i < NSACKS; i++) {
710 if(!c->sacks[i].len) { // nothing to merge, add new entry
711 debug("New SACK entry %d\n", i);
712 c->sacks[i].offset = offset;
713 c->sacks[i].len = rxd;
715 } else if(offset < c->sacks[i].offset) {
716 if(offset + rxd < c->sacks[i].offset) { // insert before
717 if(!c->sacks[NSACKS - 1].len) { // only if room left
718 debug("Insert SACK entry at %d\n", i);
719 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof c->sacks[i]);
720 c->sacks[i].offset = offset;
721 c->sacks[i].len = rxd;
723 debug("SACK entries full, dropping packet\n");
727 debug("Merge with start of SACK entry at %d\n", i);
728 c->sacks[i].offset = offset;
731 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
732 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
733 debug("Merge with end of SACK entry at %d\n", i);
734 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
735 // TODO: handle potential merge with next entry
741 for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
742 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
745 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
746 // Check if we can process out-of-order data now.
747 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
748 debug("incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
749 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
750 len = max(len, c->sacks[0].offset + c->sacks[0].len);
751 data = c->rcvbuf.data;
755 ssize_t rxd = c->recv(c, data, len);
757 // TODO: handle the application not accepting all data.
763 sack_consume(c, len);
769 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
770 if(!is_reliable(c)) {
771 c->recv(c, data, len);
772 c->rcv.nxt = seq + len;
776 uint32_t offset = seqdiff(seq, c->rcv.nxt);
777 if(offset + len > c->rcvbuf.maxsize)
781 handle_out_of_order(c, offset, data, len);
783 handle_in_order(c, data, len);
787 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
801 print_packet(utcp, "recv", data, len);
803 // Drop packets smaller than the header
806 if(len < sizeof hdr) {
811 // Make a copy from the potentially unaligned data to a struct hdr
813 memcpy(&hdr, data, sizeof hdr);
817 // Drop packets with an unknown CTL flag
819 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
824 // Try to match the packet to an existing connection
826 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
828 // Is it for a new connection?
831 // Ignore RST packets
836 // Is it a SYN packet and are we LISTENing?
838 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
839 // If we don't want to accept it, send a RST back
840 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
845 // Try to allocate memory, otherwise send a RST back
846 c = allocate_connection(utcp, hdr.dst, hdr.src);
852 // Parse auxilliary information
854 if(hdr.aux != 0x0101 || len < 4 || ((uint8_t *)data)[0] != 1) {
858 c->flags = ((uint8_t *)data)[3] & 0x7;
865 // Return SYN+ACK, go to SYN_RECEIVED state
866 c->snd.wnd = hdr.wnd;
867 c->rcv.irs = hdr.seq;
868 c->rcv.nxt = c->rcv.irs + 1;
869 set_state(c, SYN_RECEIVED);
873 hdr.ack = c->rcv.irs + 1;
874 hdr.seq = c->snd.iss;
876 print_packet(c->utcp, "send", &hdr, sizeof hdr);
877 utcp->send(utcp, &hdr, sizeof hdr);
879 // No, we don't want your packets, send a RST back
887 debug("%p state %s\n", c->utcp, strstate[c->state]);
889 // In case this is for a CLOSED connection, ignore the packet.
890 // TODO: make it so incoming packets can never match a CLOSED connection.
892 if(c->state == CLOSED) {
893 debug("Got packet for closed connection\n");
897 // It is for an existing connection.
899 uint32_t prevrcvnxt = c->rcv.nxt;
901 // 1. Drop invalid packets.
903 // 1a. Drop packets that should not happen in our current state.
923 // 1b. Drop packets with a sequence number not in our receive window.
927 if(c->state == SYN_SENT)
930 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
932 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
934 // cut already accepted front overlapping
936 acceptable = len > -rcv_offset;
940 hdr.seq -= rcv_offset;
943 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
948 debug("Packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
949 // Ignore unacceptable RST packets.
952 // Otherwise, continue processing.
956 c->snd.wnd = hdr.wnd; // TODO: move below
958 // 1c. Drop packets with an invalid ACK.
959 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
960 // (= snd.una + c->sndbuf.used).
962 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
963 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
964 // Ignore unacceptable RST packets.
970 // 2. Handle RST packets
977 // The peer has refused our connection.
978 set_state(c, CLOSED);
979 errno = ECONNREFUSED;
986 // We haven't told the application about this connection yet. Silently delete.
995 // The peer has aborted our connection.
996 set_state(c, CLOSED);
1006 // As far as the application is concerned, the connection has already been closed.
1007 // If it has called utcp_close() already, we can immediately free this connection.
1012 // Otherwise, immediately move to the CLOSED state.
1013 set_state(c, CLOSED);
1023 // 3. Advance snd.una
1025 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
1026 prevrcvnxt = c->rcv.nxt;
1030 if(c->rtt_start.tv_sec) {
1031 if(c->rtt_seq == hdr.ack) {
1032 struct timeval now, diff;
1033 gettimeofday(&now, NULL);
1034 timersub(&now, &c->rtt_start, &diff);
1035 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
1036 c->rtt_start.tv_sec = 0;
1037 } else if(c->rtt_seq < hdr.ack) {
1038 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1039 c->rtt_start.tv_sec = 0;
1043 int32_t data_acked = advanced;
1050 // TODO: handle FIN as well.
1055 assert(data_acked >= 0);
1057 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1058 assert(data_acked <= bufused);
1061 buffer_get(&c->sndbuf, NULL, data_acked);
1063 // Also advance snd.nxt if possible
1064 if(seqdiff(c->snd.nxt, hdr.ack) < 0)
1065 c->snd.nxt = hdr.ack;
1067 c->snd.una = hdr.ack;
1070 c->snd.cwnd += utcp->mtu;
1071 if(c->snd.cwnd > c->sndbuf.maxsize)
1072 c->snd.cwnd = c->sndbuf.maxsize;
1074 // Check if we have sent a FIN that is now ACKed.
1077 if(c->snd.una == c->snd.last)
1078 set_state(c, FIN_WAIT_2);
1081 if(c->snd.una == c->snd.last) {
1082 gettimeofday(&c->conn_timeout, NULL);
1083 c->conn_timeout.tv_sec += 60;
1084 set_state(c, TIME_WAIT);
1091 if(!len && is_reliable(c)) {
1093 if(c->dupack == 3) {
1094 debug("Triplicate ACK\n");
1095 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1096 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1097 //Reset the congestion window so we wait for ACKs.
1098 c->snd.nxt = c->snd.una;
1099 c->snd.cwnd = utcp->mtu;
1100 start_retransmit_timer(c);
1108 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
1109 if(c->snd.una == c->snd.last)
1110 stop_retransmit_timer(c);
1111 else if(is_reliable(c))
1112 start_retransmit_timer(c);
1115 // 5. Process SYN stuff
1120 // This is a SYNACK. It should always have ACKed the SYN.
1123 c->rcv.irs = hdr.seq;
1124 c->rcv.nxt = hdr.seq;
1125 set_state(c, ESTABLISHED);
1126 // TODO: notify application of this somehow.
1136 // Ehm, no. We should never receive a second SYN.
1145 // SYN counts as one sequence number
1149 // 6. Process new data
1151 if(c->state == SYN_RECEIVED) {
1152 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1156 // Are we still LISTENing?
1158 utcp->accept(c, c->src);
1160 if(c->state != ESTABLISHED) {
1161 set_state(c, CLOSED);
1171 // This should never happen.
1184 // Ehm no, We should never receive more data after a FIN.
1193 handle_incoming_data(c, hdr.seq, data, len);
1196 // 7. Process FIN stuff
1198 if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1202 // This should never happen.
1208 set_state(c, CLOSE_WAIT);
1211 set_state(c, CLOSING);
1214 gettimeofday(&c->conn_timeout, NULL);
1215 c->conn_timeout.tv_sec += 60;
1216 set_state(c, TIME_WAIT);
1222 // Ehm, no. We should never receive a second FIN.
1231 // FIN counts as one sequence number
1235 // Inform the application that the peer closed the connection.
1238 c->recv(c, NULL, 0);
1242 // Now we send something back if:
1243 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1244 // -> sendatleastone = true
1245 // - or we got an ack, so we should maybe send a bit more data
1246 // -> sendatleastone = false
1248 ack(c, len || prevrcvnxt != c->rcv.nxt);
1258 hdr.ack = hdr.seq + len;
1260 hdr.ctl = RST | ACK;
1262 print_packet(utcp, "send", &hdr, sizeof hdr);
1263 utcp->send(utcp, &hdr, sizeof hdr);
1268 int utcp_shutdown(struct utcp_connection *c, int dir) {
1269 debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1276 debug("Error: shutdown() called on closed connection %p\n", c);
1281 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1286 // TCP does not have a provision for stopping incoming packets.
1287 // The best we can do is to just ignore them.
1288 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR)
1291 // The rest of the code deals with shutting down writes.
1292 if(dir == UTCP_SHUT_RD)
1302 set_state(c, CLOSED);
1307 set_state(c, FIN_WAIT_1);
1313 set_state(c, CLOSING);
1325 if(!timerisset(&c->rtrx_timeout))
1326 start_retransmit_timer(c);
1330 int utcp_close(struct utcp_connection *c) {
1331 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN)
1339 int utcp_abort(struct utcp_connection *c) {
1346 debug("Error: abort() called on closed connection %p\n", c);
1363 set_state(c, CLOSED);
1371 set_state(c, CLOSED);
1381 hdr.seq = c->snd.nxt;
1386 print_packet(c->utcp, "send", &hdr, sizeof hdr);
1387 c->utcp->send(c->utcp, &hdr, sizeof hdr);
1392 * One call to this function will loop through all connections,
1393 * checking if something needs to be resent or not.
1394 * The return value is the time to the next timeout in milliseconds,
1395 * or maybe a negative value if the timeout is infinite.
1397 struct timeval utcp_timeout(struct utcp *utcp) {
1399 gettimeofday(&now, NULL);
1400 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1402 for(int i = 0; i < utcp->nconnections; i++) {
1403 struct utcp_connection *c = utcp->connections[i];
1407 // delete connections that have been utcp_close()d.
1408 if(c->state == CLOSED) {
1410 debug("Reaping %p\n", c);
1417 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1421 c->recv(c, NULL, 0);
1425 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1426 debug("retransmit()\n");
1430 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1431 c->poll(c, buffer_free(&c->sndbuf));
1433 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1434 next = c->conn_timeout;
1436 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1437 next = c->rtrx_timeout;
1440 struct timeval diff;
1441 timersub(&next, &now, &diff);
1445 bool utcp_is_active(struct utcp *utcp) {
1449 for(int i = 0; i < utcp->nconnections; i++)
1450 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT)
1456 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1462 struct utcp *utcp = calloc(1, sizeof *utcp);
1466 utcp->accept = accept;
1467 utcp->pre_accept = pre_accept;
1470 utcp->mtu = DEFAULT_MTU;
1471 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
1472 utcp->rto = START_RTO; // usec
1477 void utcp_exit(struct utcp *utcp) {
1480 for(int i = 0; i < utcp->nconnections; i++) {
1481 if(!utcp->connections[i]->reapable)
1482 debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1483 buffer_exit(&utcp->connections[i]->rcvbuf);
1484 buffer_exit(&utcp->connections[i]->sndbuf);
1485 free(utcp->connections[i]);
1487 free(utcp->connections);
1491 uint16_t utcp_get_mtu(struct utcp *utcp) {
1492 return utcp ? utcp->mtu : 0;
1495 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1496 // TODO: handle overhead of the header
1501 int utcp_get_user_timeout(struct utcp *u) {
1502 return u ? u->timeout : 0;
1505 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1507 u->timeout = timeout;
1510 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1511 return c ? c->sndbuf.maxsize : 0;
1514 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1515 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1516 return buffer_free(&c->sndbuf);
1521 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1524 c->sndbuf.maxsize = size;
1525 if(c->sndbuf.maxsize != size)
1526 c->sndbuf.maxsize = -1;
1529 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1530 return c ? c->rcvbuf.maxsize : 0;
1533 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1534 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1535 return buffer_free(&c->rcvbuf);
1540 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1543 c->rcvbuf.maxsize = size;
1544 if(c->rcvbuf.maxsize != size)
1545 c->rcvbuf.maxsize = -1;
1548 bool utcp_get_nodelay(struct utcp_connection *c) {
1549 return c ? c->nodelay : false;
1552 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1554 c->nodelay = nodelay;
1557 bool utcp_get_keepalive(struct utcp_connection *c) {
1558 return c ? c->keepalive : false;
1561 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1563 c->keepalive = keepalive;
1566 size_t utcp_get_outq(struct utcp_connection *c) {
1567 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1570 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1575 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1580 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
1582 utcp->accept = accept;
1583 utcp->pre_accept = pre_accept;