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 += 1000000;\
59 static void debug(const char *format, ...) {
62 vfprintf(stderr, format, ap);
66 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
68 if(len < sizeof hdr) {
69 debug("%p %s: short packet (%zu bytes)\n", utcp, dir, len);
73 memcpy(&hdr, pkt, sizeof hdr);
74 fprintf (stderr, "%p %s: len=%zu, src=%u dst=%u seq=%u ack=%u wnd=%u ctl=", utcp, dir, len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd);
84 if(len > sizeof hdr) {
86 for(int i = sizeof hdr; i < len; i++) {
87 const char *data = pkt;
88 debug("%c", data[i] >= 32 ? data[i] : '.');
96 #define print_packet(...)
99 static void set_state(struct utcp_connection *c, enum state state) {
101 if(state == ESTABLISHED)
102 timerclear(&c->conn_timeout);
103 debug("%p new state: %s\n", c->utcp, strstate[state]);
106 static inline void list_connections(struct utcp *utcp) {
107 debug("%p has %d connections:\n", utcp, utcp->nconnections);
108 for(int i = 0; i < utcp->nconnections; i++)
109 debug(" %u -> %u state %s\n", utcp->connections[i]->src, utcp->connections[i]->dst, strstate[utcp->connections[i]->state]);
112 static int32_t seqdiff(uint32_t a, uint32_t b) {
117 // TODO: convert to ringbuffers to avoid memmove() operations.
119 // Store data into the buffer
120 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
121 if(buf->maxsize <= buf->used)
123 if(len > buf->maxsize - buf->used)
124 len = buf->maxsize - buf->used;
125 if(len > buf->size - buf->used) {
126 size_t newsize = buf->size;
129 } while(newsize < buf->used + len);
130 if(newsize > buf->maxsize)
131 newsize = buf->maxsize;
132 char *newdata = realloc(buf->data, newsize);
138 memcpy(buf->data + buf->used, data, len);
143 // Get data from the buffer. data can be NULL.
144 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
148 memcpy(data, buf->data, len);
150 memmove(buf->data, buf->data + len, buf->used - len);
155 // Copy data from the buffer without removing it.
156 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
157 if(offset >= buf->used)
159 if(offset + len > buf->used)
160 len = buf->used - offset;
161 memcpy(data, buf->data + offset, len);
165 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
166 memset(buf, 0, sizeof *buf);
167 buf->data = malloc(len);
171 buf->maxsize = maxlen;
175 static void buffer_exit(struct buffer *buf) {
177 memset(buf, 0, sizeof *buf);
180 static uint32_t buffer_free(const struct buffer *buf) {
181 return buf->maxsize - buf->used;
184 // Connections are stored in a sorted list.
185 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
187 static int compare(const void *va, const void *vb) {
190 const struct utcp_connection *a = *(struct utcp_connection **)va;
191 const struct utcp_connection *b = *(struct utcp_connection **)vb;
194 assert(a->src && b->src);
196 int c = (int)a->src - (int)b->src;
199 c = (int)a->dst - (int)b->dst;
203 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
204 if(!utcp->nconnections)
206 struct utcp_connection key = {
210 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
211 return match ? *match : NULL;
214 static void free_connection(struct utcp_connection *c) {
215 struct utcp *utcp = c->utcp;
216 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
220 int i = cp - utcp->connections;
221 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof *cp);
222 utcp->nconnections--;
224 buffer_exit(&c->sndbuf);
228 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
229 // Check whether this combination of src and dst is free
232 if(find_connection(utcp, src, dst)) {
236 } else { // If src == 0, generate a random port number with the high bit set
237 if(utcp->nconnections >= 32767) {
241 src = rand() | 0x8000;
242 while(find_connection(utcp, src, dst))
246 // Allocate memory for the new connection
248 if(utcp->nconnections >= utcp->nallocated) {
249 if(!utcp->nallocated)
250 utcp->nallocated = 4;
252 utcp->nallocated *= 2;
253 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
256 utcp->connections = new_array;
259 struct utcp_connection *c = calloc(1, sizeof *c);
263 if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
268 // Fill in the details
273 c->snd.una = c->snd.iss;
274 c->snd.nxt = c->snd.iss + 1;
275 c->rcv.wnd = utcp->mtu;
276 c->snd.last = c->snd.nxt;
277 c->snd.cwnd = utcp->mtu;
280 // Add it to the sorted list of connections
282 utcp->connections[utcp->nconnections++] = c;
283 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
288 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
289 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
300 hdr.seq = c->snd.iss;
302 hdr.wnd = c->rcv.wnd;
306 set_state(c, SYN_SENT);
308 print_packet(utcp, "send", &hdr, sizeof hdr);
309 utcp->send(utcp, &hdr, sizeof hdr);
311 gettimeofday(&c->conn_timeout, NULL);
312 c->conn_timeout.tv_sec += utcp->timeout;
317 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
318 if(c->reapable || c->state != SYN_RECEIVED) {
319 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
323 debug("%p accepted, %p %p\n", c, recv, priv);
326 set_state(c, ESTABLISHED);
329 static void ack(struct utcp_connection *c, bool sendatleastone) {
330 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
331 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
341 if(!left && !sendatleastone)
349 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
353 pkt->hdr.src = c->src;
354 pkt->hdr.dst = c->dst;
355 pkt->hdr.ack = c->rcv.nxt;
356 pkt->hdr.wnd = c->snd.wnd;
361 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
362 pkt->hdr.seq = c->snd.nxt;
364 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
366 c->snd.nxt += seglen;
369 if(c->state != ESTABLISHED && !left && seglen) {
381 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
382 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
388 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
390 debug("Error: send() called on closed connection %p\n", c);
400 debug("Error: send() called on unconnected connection %p\n", c);
411 debug("Error: send() called on closing connection %p\n", c);
416 // Add data to send buffer
426 len = buffer_put(&c->sndbuf, data, len);
437 static void swap_ports(struct hdr *hdr) {
438 uint16_t tmp = hdr->src;
443 static void retransmit(struct utcp_connection *c) {
444 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
447 struct utcp *utcp = c->utcp;
454 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
458 pkt->hdr.src = c->src;
459 pkt->hdr.dst = c->dst;
463 // TODO: this should not happen
467 pkt->hdr.seq = c->snd.iss;
469 pkt->hdr.wnd = c->rcv.wnd;
471 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
472 utcp->send(utcp, pkt, sizeof pkt->hdr);
476 pkt->hdr.seq = c->snd.nxt;
477 pkt->hdr.ack = c->rcv.nxt;
478 pkt->hdr.ctl = SYN | ACK;
479 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
480 utcp->send(utcp, pkt, sizeof pkt->hdr);
485 pkt->hdr.seq = c->snd.una;
486 pkt->hdr.ack = c->rcv.nxt;
488 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
489 fprintf(stderr, "retransmit %u %u %u\n", pkt->hdr.seq, pkt->hdr.ack, len);
490 if(c->state == FIN_WAIT_1)
495 if(c->state == FIN_WAIT_1)
498 buffer_copy(&c->sndbuf, pkt->data, 0, len);
499 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
500 utcp->send(utcp, pkt, sizeof pkt->hdr + len);
512 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
526 print_packet(utcp, "recv", data, len);
528 // Drop packets smaller than the header
531 if(len < sizeof hdr) {
536 // Make a copy from the potentially unaligned data to a struct hdr
538 memcpy(&hdr, data, sizeof hdr);
542 // Drop packets with an unknown CTL flag
544 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
549 // Try to match the packet to an existing connection
551 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
553 // Is it for a new connection?
556 // Ignore RST packets
561 // Is it a SYN packet and are we LISTENing?
563 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
564 // If we don't want to accept it, send a RST back
565 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
570 // Try to allocate memory, otherwise send a RST back
571 c = allocate_connection(utcp, hdr.dst, hdr.src);
577 // Return SYN+ACK, go to SYN_RECEIVED state
578 c->snd.wnd = hdr.wnd;
579 c->rcv.irs = hdr.seq;
580 c->rcv.nxt = c->rcv.irs + 1;
581 set_state(c, SYN_RECEIVED);
585 hdr.ack = c->rcv.irs + 1;
586 hdr.seq = c->snd.iss;
588 print_packet(c->utcp, "send", &hdr, sizeof hdr);
589 utcp->send(utcp, &hdr, sizeof hdr);
591 // No, we don't want your packets, send a RST back
599 debug("%p state %s\n", c->utcp, strstate[c->state]);
601 // In case this is for a CLOSED connection, ignore the packet.
602 // TODO: make it so incoming packets can never match a CLOSED connection.
604 if(c->state == CLOSED)
607 // It is for an existing connection.
609 uint32_t prevrcvnxt = c->rcv.nxt;
611 // 1. Drop invalid packets.
613 // 1a. Drop packets that should not happen in our current state.
630 // 1b. Drop packets with a sequence number not in our receive window.
634 if(c->state == SYN_SENT)
637 // TODO: handle packets overlapping c->rcv.nxt.
639 // Only use this when accepting out-of-order packets.
642 acceptable = hdr.seq == c->rcv.nxt;
644 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
647 // We don't accept data when the receive window is zero.
650 // Both start and end of packet must be within the receive window
651 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
652 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
654 if(c->state != SYN_SENT)
655 acceptable = hdr.seq == c->rcv.nxt;
659 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
660 // Ignore unacceptable RST packets.
663 // Otherwise, send an ACK back in the hope things improve.
668 c->snd.wnd = hdr.wnd; // TODO: move below
670 // 1c. Drop packets with an invalid ACK.
671 // ackno should not roll back, and it should also not be bigger than snd.nxt.
673 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
674 debug("Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
675 // Ignore unacceptable RST packets.
681 // 2. Handle RST packets
688 // The peer has refused our connection.
689 set_state(c, CLOSED);
690 errno = ECONNREFUSED;
697 // We haven't told the application about this connection yet. Silently delete.
706 // The peer has aborted our connection.
707 set_state(c, CLOSED);
717 // As far as the application is concerned, the connection has already been closed.
718 // If it has called utcp_close() already, we can immediately free this connection.
723 // Otherwise, immediately move to the CLOSED state.
724 set_state(c, CLOSED);
731 // 3. Advance snd.una
733 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
734 prevrcvnxt = c->rcv.nxt;
737 int32_t data_acked = advanced;
744 // TODO: handle FIN as well.
749 assert(data_acked >= 0);
751 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
752 assert(data_acked <= bufused);
755 buffer_get(&c->sndbuf, NULL, data_acked);
757 c->snd.una = hdr.ack;
760 c->snd.cwnd += utcp->mtu;
761 if(c->snd.cwnd > c->sndbuf.maxsize)
762 c->snd.cwnd = c->sndbuf.maxsize;
764 // Check if we have sent a FIN that is now ACKed.
767 if(c->snd.una == c->snd.last)
768 set_state(c, FIN_WAIT_2);
771 if(c->snd.una == c->snd.last) {
772 gettimeofday(&c->conn_timeout, NULL);
773 c->conn_timeout.tv_sec += 60;
774 set_state(c, TIME_WAIT);
784 debug("Triplicate ACK\n");
785 fprintf(stderr, "Triplicate ACK\n");
786 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
787 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
788 //This will cause us to start retransmitting, but at the same speed as the incoming ACKs arrive,
789 //thus preventing a drop in speed.
790 c->snd.nxt = c->snd.una;
798 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
799 if(c->snd.una == c->snd.nxt)
800 timerclear(&c->rtrx_timeout);
803 // 5. Process SYN stuff
808 // This is a SYNACK. It should always have ACKed the SYN.
811 c->rcv.irs = hdr.seq;
812 c->rcv.nxt = hdr.seq;
813 set_state(c, ESTABLISHED);
814 // TODO: notify application of this somehow.
824 // Ehm, no. We should never receive a second SYN.
830 // SYN counts as one sequence number
834 // 6. Process new data
836 if(c->state == SYN_RECEIVED) {
837 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
841 // Are we still LISTENing?
843 utcp->accept(c, c->src);
845 if(c->state != ESTABLISHED) {
846 set_state(c, CLOSED);
856 // This should never happen.
866 // Ehm no, We should never receive more data after a FIN.
875 rxd = c->recv(c, data, len);
877 // TODO: once we have a receive buffer, handle the application not accepting all data.
883 rxd = len; // Bad application, bad!
891 // 7. Process FIN stuff
897 // This should never happen.
900 set_state(c, CLOSE_WAIT);
903 set_state(c, CLOSING);
906 gettimeofday(&c->conn_timeout, NULL);
907 c->conn_timeout.tv_sec += 60;
908 set_state(c, TIME_WAIT);
914 // Ehm, no. We should never receive a second FIN.
920 // FIN counts as one sequence number
924 // Inform the application that the peer closed the connection.
931 // Now we send something back if:
932 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
933 // -> sendatleastone = true
934 // - or we got an ack, so we should maybe send a bit more data
935 // -> sendatleastone = false
938 ack(c, prevrcvnxt != c->rcv.nxt);
948 hdr.ack = hdr.seq + len;
952 print_packet(utcp, "send", &hdr, sizeof hdr);
953 utcp->send(utcp, &hdr, sizeof hdr);
958 int utcp_shutdown(struct utcp_connection *c, int dir) {
959 debug("%p shutdown %d\n", c ? c->utcp : NULL, dir);
966 debug("Error: shutdown() called on closed connection %p\n", c);
978 set_state(c, CLOSED);
983 set_state(c, FIN_WAIT_1);
989 set_state(c, CLOSING);
1004 int utcp_close(struct utcp_connection *c) {
1005 if(utcp_shutdown(c, SHUT_RDWR))
1013 int utcp_abort(struct utcp_connection *c) {
1020 debug("Error: abort() called on closed connection %p\n", c);
1037 set_state(c, CLOSED);
1045 set_state(c, CLOSED);
1055 hdr.seq = c->snd.nxt;
1060 print_packet(c->utcp, "send", &hdr, sizeof hdr);
1061 c->utcp->send(c->utcp, &hdr, sizeof hdr);
1066 * One call to this function will loop through all connections,
1067 * checking if something needs to be resent or not.
1068 * The return value is the time to the next timeout in milliseconds,
1069 * or maybe a negative value if the timeout is infinite.
1071 struct timeval utcp_timeout(struct utcp *utcp) {
1073 gettimeofday(&now, NULL);
1074 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1076 for(int i = 0; i < utcp->nconnections; i++) {
1077 struct utcp_connection *c = utcp->connections[i];
1081 if(c->state == CLOSED) {
1083 debug("Reaping %p\n", c);
1090 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1094 c->recv(c, NULL, 0);
1098 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1102 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1103 c->poll(c, buffer_free(&c->sndbuf));
1105 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1106 next = c->conn_timeout;
1108 if(c->snd.nxt != c->snd.una) {
1109 c->rtrx_timeout = now;
1110 c->rtrx_timeout.tv_sec++;
1112 timerclear(&c->rtrx_timeout);
1115 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1116 next = c->rtrx_timeout;
1119 struct timeval diff;
1120 timersub(&next, &now, &diff);
1124 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1125 struct utcp *utcp = calloc(1, sizeof *utcp);
1134 utcp->accept = accept;
1135 utcp->pre_accept = pre_accept;
1144 void utcp_exit(struct utcp *utcp) {
1147 for(int i = 0; i < utcp->nconnections; i++) {
1148 if(!utcp->connections[i]->reapable)
1149 debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1150 buffer_exit(&utcp->connections[i]->sndbuf);
1151 free(utcp->connections[i]);
1153 free(utcp->connections);
1157 uint16_t utcp_get_mtu(struct utcp *utcp) {
1161 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1162 // TODO: handle overhead of the header
1166 int utcp_get_user_timeout(struct utcp *u) {
1170 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1171 u->timeout = timeout;
1174 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1175 return c->sndbuf.maxsize;
1178 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1179 return buffer_free(&c->sndbuf);
1182 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1183 c->sndbuf.maxsize = size;
1184 if(c->sndbuf.maxsize != size)
1185 c->sndbuf.maxsize = -1;
1188 bool utcp_get_nodelay(struct utcp_connection *c) {
1192 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1193 c->nodelay = nodelay;
1196 bool utcp_get_keepalive(struct utcp_connection *c) {
1197 return c->keepalive;
1200 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1201 c->keepalive = keepalive;
1204 size_t utcp_get_outq(struct utcp_connection *c) {
1205 return seqdiff(c->snd.nxt, c->snd.una);
1208 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1212 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {