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 inline void list_connections(struct utcp *utcp) {
131 debug("%p has %d connections:\n", utcp, utcp->nconnections);
132 for(int i = 0; i < utcp->nconnections; i++)
133 debug(" %u -> %u state %s\n", utcp->connections[i]->src, utcp->connections[i]->dst, strstate[utcp->connections[i]->state]);
136 static int32_t seqdiff(uint32_t a, uint32_t b) {
141 // TODO: convert to ringbuffers to avoid memmove() operations.
143 // Store data into the buffer
144 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
145 debug("buffer_put_at %lu %lu %lu\n", (unsigned long)buf->used, (unsigned long)offset, (unsigned long)len);
147 size_t required = offset + len;
148 if(required > buf->maxsize) {
149 if(offset >= buf->maxsize)
151 len = buf->maxsize - offset;
152 required = buf->maxsize;
155 if(required > buf->size) {
156 size_t newsize = buf->size;
162 } while(newsize < required);
164 if(newsize > buf->maxsize)
165 newsize = buf->maxsize;
166 char *newdata = realloc(buf->data, newsize);
173 memcpy(buf->data + offset, data, len);
174 if(required > buf->used)
175 buf->used = required;
179 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
180 return buffer_put_at(buf, buf->used, data, len);
183 // Get data from the buffer. data can be NULL.
184 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
188 memcpy(data, buf->data, len);
190 memmove(buf->data, buf->data + len, buf->used - len);
195 // Copy data from the buffer without removing it.
196 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
197 if(offset >= buf->used)
199 if(offset + len > buf->used)
200 len = buf->used - offset;
201 memcpy(data, buf->data + offset, len);
205 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
206 memset(buf, 0, sizeof *buf);
208 buf->data = malloc(len);
213 buf->maxsize = maxlen;
217 static void buffer_exit(struct buffer *buf) {
219 memset(buf, 0, sizeof *buf);
222 static uint32_t buffer_free(const struct buffer *buf) {
223 return buf->maxsize - buf->used;
226 // Connections are stored in a sorted list.
227 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
229 static int compare(const void *va, const void *vb) {
232 const struct utcp_connection *a = *(struct utcp_connection **)va;
233 const struct utcp_connection *b = *(struct utcp_connection **)vb;
236 assert(a->src && b->src);
238 int c = (int)a->src - (int)b->src;
241 c = (int)a->dst - (int)b->dst;
245 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
246 if(!utcp->nconnections)
248 struct utcp_connection key = {
252 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
253 return match ? *match : NULL;
256 static void free_connection(struct utcp_connection *c) {
257 struct utcp *utcp = c->utcp;
258 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
262 int i = cp - utcp->connections;
263 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof *cp);
264 utcp->nconnections--;
266 buffer_exit(&c->rcvbuf);
267 buffer_exit(&c->sndbuf);
271 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
272 // Check whether this combination of src and dst is free
275 if(find_connection(utcp, src, dst)) {
279 } else { // If src == 0, generate a random port number with the high bit set
280 if(utcp->nconnections >= 32767) {
284 src = rand() | 0x8000;
285 while(find_connection(utcp, src, dst))
289 // Allocate memory for the new connection
291 if(utcp->nconnections >= utcp->nallocated) {
292 if(!utcp->nallocated)
293 utcp->nallocated = 4;
295 utcp->nallocated *= 2;
296 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
299 utcp->connections = new_array;
302 struct utcp_connection *c = calloc(1, sizeof *c);
306 if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
311 if(!buffer_init(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
312 buffer_exit(&c->sndbuf);
317 // Fill in the details
326 c->snd.una = c->snd.iss;
327 c->snd.nxt = c->snd.iss + 1;
328 c->rcv.wnd = utcp->mtu;
329 c->snd.last = c->snd.nxt;
330 c->snd.cwnd = utcp->mtu;
333 // Add it to the sorted list of connections
335 utcp->connections[utcp->nconnections++] = c;
336 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
341 // Update RTT variables. See RFC 6298.
342 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
344 debug("invalid rtt\n");
348 struct utcp *utcp = c->utcp;
352 utcp->rttvar = rtt / 2;
353 utcp->rto = rtt + max(2 * rtt, CLOCK_GRANULARITY);
355 utcp->rttvar = (utcp->rttvar * 3 + abs(utcp->srtt - rtt)) / 4;
356 utcp->srtt = (utcp->srtt * 7 + rtt) / 8;
357 utcp->rto = utcp->srtt + max(utcp->rttvar, CLOCK_GRANULARITY);
360 if(utcp->rto > MAX_RTO)
363 debug("rtt %u srtt %u rttvar %u rto %u\n", rtt, utcp->srtt, utcp->rttvar, utcp->rto);
366 static void start_retransmit_timer(struct utcp_connection *c) {
367 gettimeofday(&c->rtrx_timeout, NULL);
368 c->rtrx_timeout.tv_usec += c->utcp->rto;
369 while(c->rtrx_timeout.tv_usec >= 1000000) {
370 c->rtrx_timeout.tv_usec -= 1000000;
371 c->rtrx_timeout.tv_sec++;
373 debug("timeout set to %lu.%06lu (%u)\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_usec, c->utcp->rto);
376 static void stop_retransmit_timer(struct utcp_connection *c) {
377 timerclear(&c->rtrx_timeout);
378 debug("timeout cleared\n");
381 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
382 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
393 hdr.seq = c->snd.iss;
395 hdr.wnd = c->rcv.wnd;
399 set_state(c, SYN_SENT);
401 print_packet(utcp, "send", &hdr, sizeof hdr);
402 utcp->send(utcp, &hdr, sizeof hdr);
404 gettimeofday(&c->conn_timeout, NULL);
405 c->conn_timeout.tv_sec += utcp->timeout;
410 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
411 if(c->reapable || c->state != SYN_RECEIVED) {
412 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
416 debug("%p accepted, %p %p\n", c, recv, priv);
419 set_state(c, ESTABLISHED);
422 static void ack(struct utcp_connection *c, bool sendatleastone) {
423 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
424 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
425 debug("cwndleft = %d\n", cwndleft);
435 if(!left && !sendatleastone)
443 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
447 pkt->hdr.src = c->src;
448 pkt->hdr.dst = c->dst;
449 pkt->hdr.ack = c->rcv.nxt;
450 pkt->hdr.wnd = c->snd.wnd;
455 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
456 pkt->hdr.seq = c->snd.nxt;
458 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
460 c->snd.nxt += seglen;
463 if(seglen && fin_wanted(c, c->snd.nxt)) {
468 if(!c->rtt_start.tv_sec) {
469 // Start RTT measurement
470 gettimeofday(&c->rtt_start, NULL);
471 c->rtt_seq = pkt->hdr.seq + seglen;
472 debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
475 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
476 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
482 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
484 debug("Error: send() called on closed connection %p\n", c);
494 debug("Error: send() called on unconnected connection %p\n", c);
505 debug("Error: send() called on closing connection %p\n", c);
510 // Add data to send buffer
520 len = buffer_put(&c->sndbuf, data, len);
528 if(!timerisset(&c->rtrx_timeout))
529 start_retransmit_timer(c);
533 static void swap_ports(struct hdr *hdr) {
534 uint16_t tmp = hdr->src;
539 static void retransmit(struct utcp_connection *c) {
540 if(c->state == CLOSED || c->snd.last == c->snd.una) {
541 debug("Retransmit() called but nothing to retransmit!\n");
542 stop_retransmit_timer(c);
546 struct utcp *utcp = c->utcp;
553 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
557 pkt->hdr.src = c->src;
558 pkt->hdr.dst = c->dst;
559 pkt->hdr.wnd = c->rcv.wnd;
564 // Send our SYN again
565 pkt->hdr.seq = c->snd.iss;
568 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
569 utcp->send(utcp, pkt, sizeof pkt->hdr);
574 pkt->hdr.seq = c->snd.nxt;
575 pkt->hdr.ack = c->rcv.nxt;
576 pkt->hdr.ctl = SYN | ACK;
577 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
578 utcp->send(utcp, pkt, sizeof pkt->hdr);
586 // Send unacked data again.
587 pkt->hdr.seq = c->snd.una;
588 pkt->hdr.ack = c->rcv.nxt;
590 uint32_t len = seqdiff(c->snd.last, c->snd.una);
593 if(fin_wanted(c, c->snd.una + len)) {
597 c->snd.nxt = c->snd.una + len;
598 c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
599 buffer_copy(&c->sndbuf, pkt->data, 0, len);
600 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
601 utcp->send(utcp, pkt, sizeof pkt->hdr + len);
608 // We shouldn't need to retransmit anything in this state.
612 stop_retransmit_timer(c);
616 start_retransmit_timer(c);
618 if(utcp->rto > MAX_RTO)
620 c->rtt_start.tv_sec = 0; // invalidate RTT timer
626 /* Update receive buffer and SACK entries after consuming data.
630 * |.....0000..1111111111.....22222......3333|
633 * 0..3 represent the SACK entries. The ^ indicates up to which point we want
634 * to remove data from the receive buffer. The idea is to substract "len"
635 * from the offset of all the SACK entries, and then remove/cut down entries
636 * that are shifted to before the start of the receive buffer.
638 * There are three cases:
639 * - the SACK entry is after ^, in that case just change the offset.
640 * - the SACK entry starts before and ends after ^, so we have to
641 * change both its offset and size.
642 * - the SACK entry is completely before ^, in that case delete it.
644 static void sack_consume(struct utcp_connection *c, size_t len) {
645 debug("sack_consume %lu\n", (unsigned long)len);
646 if(len > c->rcvbuf.used) {
647 debug("All SACK entries consumed");
652 buffer_get(&c->rcvbuf, NULL, len);
654 for(int i = 0; i < NSACKS && c->sacks[i].len; ) {
655 if(len < c->sacks[i].offset) {
656 c->sacks[i].offset -= len;
658 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
659 c->sacks[i].len -= len - c->sacks[i].offset;
660 c->sacks[i].offset = 0;
664 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof c->sacks[i]);
665 c->sacks[NSACKS - 1].len = 0;
673 for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
674 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
677 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
678 debug("out of order packet, offset %u\n", offset);
679 // Packet loss or reordering occured. Store the data in the buffer.
680 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
684 // Make note of where we put it.
685 for(int i = 0; i < NSACKS; i++) {
686 if(!c->sacks[i].len) { // nothing to merge, add new entry
687 debug("New SACK entry %d\n", i);
688 c->sacks[i].offset = offset;
689 c->sacks[i].len = rxd;
691 } else if(offset < c->sacks[i].offset) {
692 if(offset + rxd < c->sacks[i].offset) { // insert before
693 if(!c->sacks[NSACKS - 1].len) { // only if room left
694 debug("Insert SACK entry at %d\n", i);
695 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof c->sacks[i]);
696 c->sacks[i].offset = offset;
697 c->sacks[i].len = rxd;
699 debug("SACK entries full, dropping packet\n");
703 debug("Merge with start of SACK entry at %d\n", i);
704 c->sacks[i].offset = offset;
707 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
708 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
709 debug("Merge with end of SACK entry at %d\n", i);
710 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
711 // TODO: handle potential merge with next entry
717 for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
718 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
721 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
722 // Check if we can process out-of-order data now.
723 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
724 debug("incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
725 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
726 len = max(len, c->sacks[0].offset + c->sacks[0].len);
727 data = c->rcvbuf.data;
731 ssize_t rxd = c->recv(c, data, len);
733 // TODO: handle the application not accepting all data.
739 sack_consume(c, len);
745 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
746 uint32_t offset = seqdiff(seq, c->rcv.nxt);
747 if(offset + len > c->rcvbuf.maxsize)
751 handle_out_of_order(c, offset, data, len);
753 handle_in_order(c, data, len);
757 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
771 print_packet(utcp, "recv", data, len);
773 // Drop packets smaller than the header
776 if(len < sizeof hdr) {
781 // Make a copy from the potentially unaligned data to a struct hdr
783 memcpy(&hdr, data, sizeof hdr);
787 // Drop packets with an unknown CTL flag
789 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
794 // Try to match the packet to an existing connection
796 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
798 // Is it for a new connection?
801 // Ignore RST packets
806 // Is it a SYN packet and are we LISTENing?
808 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
809 // If we don't want to accept it, send a RST back
810 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
815 // Try to allocate memory, otherwise send a RST back
816 c = allocate_connection(utcp, hdr.dst, hdr.src);
822 // Return SYN+ACK, go to SYN_RECEIVED state
823 c->snd.wnd = hdr.wnd;
824 c->rcv.irs = hdr.seq;
825 c->rcv.nxt = c->rcv.irs + 1;
826 set_state(c, SYN_RECEIVED);
830 hdr.ack = c->rcv.irs + 1;
831 hdr.seq = c->snd.iss;
833 print_packet(c->utcp, "send", &hdr, sizeof hdr);
834 utcp->send(utcp, &hdr, sizeof hdr);
836 // No, we don't want your packets, send a RST back
844 debug("%p state %s\n", c->utcp, strstate[c->state]);
846 // In case this is for a CLOSED connection, ignore the packet.
847 // TODO: make it so incoming packets can never match a CLOSED connection.
849 if(c->state == CLOSED) {
850 debug("Got packet for closed connection\n");
854 // It is for an existing connection.
856 uint32_t prevrcvnxt = c->rcv.nxt;
858 // 1. Drop invalid packets.
860 // 1a. Drop packets that should not happen in our current state.
880 // 1b. Drop packets with a sequence number not in our receive window.
884 if(c->state == SYN_SENT)
887 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
889 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
891 // cut already accepted front overlapping
893 acceptable = rcv_offset + len >= 0;
900 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
904 debug("Packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
905 // Ignore unacceptable RST packets.
908 // Otherwise, send an ACK back in the hope things improve.
913 c->snd.wnd = hdr.wnd; // TODO: move below
915 // 1c. Drop packets with an invalid ACK.
916 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
917 // (= snd.una + c->sndbuf.used).
919 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
920 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
921 // Ignore unacceptable RST packets.
927 // 2. Handle RST packets
934 // The peer has refused our connection.
935 set_state(c, CLOSED);
936 errno = ECONNREFUSED;
943 // We haven't told the application about this connection yet. Silently delete.
952 // The peer has aborted our connection.
953 set_state(c, CLOSED);
963 // As far as the application is concerned, the connection has already been closed.
964 // If it has called utcp_close() already, we can immediately free this connection.
969 // Otherwise, immediately move to the CLOSED state.
970 set_state(c, CLOSED);
980 // 3. Advance snd.una
982 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
983 prevrcvnxt = c->rcv.nxt;
987 if(c->rtt_start.tv_sec) {
988 if(c->rtt_seq == hdr.ack) {
989 struct timeval now, diff;
990 gettimeofday(&now, NULL);
991 timersub(&now, &c->rtt_start, &diff);
992 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
993 c->rtt_start.tv_sec = 0;
994 } else if(c->rtt_seq < hdr.ack) {
995 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
996 c->rtt_start.tv_sec = 0;
1000 int32_t data_acked = advanced;
1007 // TODO: handle FIN as well.
1012 assert(data_acked >= 0);
1014 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1015 assert(data_acked <= bufused);
1018 buffer_get(&c->sndbuf, NULL, data_acked);
1020 // Also advance snd.nxt if possible
1021 if(seqdiff(c->snd.nxt, hdr.ack) < 0)
1022 c->snd.nxt = hdr.ack;
1024 c->snd.una = hdr.ack;
1027 c->snd.cwnd += utcp->mtu;
1028 if(c->snd.cwnd > c->sndbuf.maxsize)
1029 c->snd.cwnd = c->sndbuf.maxsize;
1031 // Check if we have sent a FIN that is now ACKed.
1034 if(c->snd.una == c->snd.last)
1035 set_state(c, FIN_WAIT_2);
1038 if(c->snd.una == c->snd.last) {
1039 gettimeofday(&c->conn_timeout, NULL);
1040 c->conn_timeout.tv_sec += 60;
1041 set_state(c, TIME_WAIT);
1050 if(c->dupack == 3) {
1051 debug("Triplicate ACK\n");
1052 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1053 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1054 //Reset the congestion window so we wait for ACKs.
1055 c->snd.nxt = c->snd.una;
1056 c->snd.cwnd = utcp->mtu;
1057 start_retransmit_timer(c);
1065 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
1066 if(c->snd.una == c->snd.last)
1067 stop_retransmit_timer(c);
1069 start_retransmit_timer(c);
1072 // 5. Process SYN stuff
1077 // This is a SYNACK. It should always have ACKed the SYN.
1080 c->rcv.irs = hdr.seq;
1081 c->rcv.nxt = hdr.seq;
1082 set_state(c, ESTABLISHED);
1083 // TODO: notify application of this somehow.
1093 // Ehm, no. We should never receive a second SYN.
1102 // SYN counts as one sequence number
1106 // 6. Process new data
1108 if(c->state == SYN_RECEIVED) {
1109 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1113 // Are we still LISTENing?
1115 utcp->accept(c, c->src);
1117 if(c->state != ESTABLISHED) {
1118 set_state(c, CLOSED);
1128 // This should never happen.
1141 // Ehm no, We should never receive more data after a FIN.
1150 handle_incoming_data(c, hdr.seq, data, len);
1153 // 7. Process FIN stuff
1155 if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1159 // This should never happen.
1165 set_state(c, CLOSE_WAIT);
1168 set_state(c, CLOSING);
1171 gettimeofday(&c->conn_timeout, NULL);
1172 c->conn_timeout.tv_sec += 60;
1173 set_state(c, TIME_WAIT);
1179 // Ehm, no. We should never receive a second FIN.
1188 // FIN counts as one sequence number
1192 // Inform the application that the peer closed the connection.
1195 c->recv(c, NULL, 0);
1199 // Now we send something back if:
1200 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1201 // -> sendatleastone = true
1202 // - or we got an ack, so we should maybe send a bit more data
1203 // -> sendatleastone = false
1205 ack(c, len || prevrcvnxt != c->rcv.nxt);
1215 hdr.ack = hdr.seq + len;
1217 hdr.ctl = RST | ACK;
1219 print_packet(utcp, "send", &hdr, sizeof hdr);
1220 utcp->send(utcp, &hdr, sizeof hdr);
1225 int utcp_shutdown(struct utcp_connection *c, int dir) {
1226 debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1233 debug("Error: shutdown() called on closed connection %p\n", c);
1238 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1243 // TCP does not have a provision for stopping incoming packets.
1244 // The best we can do is to just ignore them.
1245 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR)
1248 // The rest of the code deals with shutting down writes.
1249 if(dir == UTCP_SHUT_RD)
1259 set_state(c, CLOSED);
1264 set_state(c, FIN_WAIT_1);
1270 set_state(c, CLOSING);
1282 if(!timerisset(&c->rtrx_timeout))
1283 start_retransmit_timer(c);
1287 int utcp_close(struct utcp_connection *c) {
1288 if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN)
1296 int utcp_abort(struct utcp_connection *c) {
1303 debug("Error: abort() called on closed connection %p\n", c);
1320 set_state(c, CLOSED);
1328 set_state(c, CLOSED);
1338 hdr.seq = c->snd.nxt;
1343 print_packet(c->utcp, "send", &hdr, sizeof hdr);
1344 c->utcp->send(c->utcp, &hdr, sizeof hdr);
1349 * One call to this function will loop through all connections,
1350 * checking if something needs to be resent or not.
1351 * The return value is the time to the next timeout in milliseconds,
1352 * or maybe a negative value if the timeout is infinite.
1354 struct timeval utcp_timeout(struct utcp *utcp) {
1356 gettimeofday(&now, NULL);
1357 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1359 for(int i = 0; i < utcp->nconnections; i++) {
1360 struct utcp_connection *c = utcp->connections[i];
1364 // delete connections that have been utcp_close()d.
1365 if(c->state == CLOSED) {
1367 debug("Reaping %p\n", c);
1374 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1378 c->recv(c, NULL, 0);
1382 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1383 debug("retransmit()\n");
1387 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1388 c->poll(c, buffer_free(&c->sndbuf));
1390 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1391 next = c->conn_timeout;
1393 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1394 next = c->rtrx_timeout;
1397 struct timeval diff;
1398 timersub(&next, &now, &diff);
1402 bool utcp_is_active(struct utcp *utcp) {
1406 for(int i = 0; i < utcp->nconnections; i++)
1407 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT)
1413 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1419 struct utcp *utcp = calloc(1, sizeof *utcp);
1423 utcp->accept = accept;
1424 utcp->pre_accept = pre_accept;
1427 utcp->mtu = DEFAULT_MTU;
1428 utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
1429 utcp->rto = START_RTO; // usec
1434 void utcp_exit(struct utcp *utcp) {
1437 for(int i = 0; i < utcp->nconnections; i++) {
1438 if(!utcp->connections[i]->reapable)
1439 debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1440 buffer_exit(&utcp->connections[i]->rcvbuf);
1441 buffer_exit(&utcp->connections[i]->sndbuf);
1442 free(utcp->connections[i]);
1444 free(utcp->connections);
1448 uint16_t utcp_get_mtu(struct utcp *utcp) {
1449 return utcp ? utcp->mtu : 0;
1452 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1453 // TODO: handle overhead of the header
1458 int utcp_get_user_timeout(struct utcp *u) {
1459 return u ? u->timeout : 0;
1462 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1464 u->timeout = timeout;
1467 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1468 return c ? c->sndbuf.maxsize : 0;
1471 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1472 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1473 return buffer_free(&c->sndbuf);
1478 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1481 c->sndbuf.maxsize = size;
1482 if(c->sndbuf.maxsize != size)
1483 c->sndbuf.maxsize = -1;
1486 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1487 return c ? c->rcvbuf.maxsize : 0;
1490 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1491 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1492 return buffer_free(&c->rcvbuf);
1497 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1500 c->rcvbuf.maxsize = size;
1501 if(c->rcvbuf.maxsize != size)
1502 c->rcvbuf.maxsize = -1;
1505 bool utcp_get_nodelay(struct utcp_connection *c) {
1506 return c ? c->nodelay : false;
1509 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1511 c->nodelay = nodelay;
1514 bool utcp_get_keepalive(struct utcp_connection *c) {
1515 return c ? c->keepalive : false;
1518 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1520 c->keepalive = keepalive;
1523 size_t utcp_get_outq(struct utcp_connection *c) {
1524 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1527 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1532 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1537 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
1539 utcp->accept = accept;
1540 utcp->pre_accept = pre_accept;