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) {
116 // Connections are stored in a sorted list.
117 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
119 static int compare(const void *va, const void *vb) {
122 const struct utcp_connection *a = *(struct utcp_connection **)va;
123 const struct utcp_connection *b = *(struct utcp_connection **)vb;
126 assert(a->src && b->src);
128 int c = (int)a->src - (int)b->src;
131 c = (int)a->dst - (int)b->dst;
135 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
136 if(!utcp->nconnections)
138 struct utcp_connection key = {
142 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
143 return match ? *match : NULL;
146 static void free_connection(struct utcp_connection *c) {
147 struct utcp *utcp = c->utcp;
148 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
152 int i = cp - utcp->connections;
153 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof *cp);
154 utcp->nconnections--;
160 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
161 // Check whether this combination of src and dst is free
164 if(find_connection(utcp, src, dst)) {
168 } else { // If src == 0, generate a random port number with the high bit set
169 if(utcp->nconnections >= 32767) {
173 src = rand() | 0x8000;
174 while(find_connection(utcp, src, dst))
178 // Allocate memory for the new connection
180 if(utcp->nconnections >= utcp->nallocated) {
181 if(!utcp->nallocated)
182 utcp->nallocated = 4;
184 utcp->nallocated *= 2;
185 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
188 utcp->connections = new_array;
191 struct utcp_connection *c = calloc(1, sizeof *c);
195 c->sndbufsize = DEFAULT_SNDBUFSIZE;
196 c->maxsndbufsize = DEFAULT_MAXSNDBUFSIZE;
197 c->sndbuf = malloc(c->sndbufsize);
203 // Fill in the details
208 c->snd.una = c->snd.iss;
209 c->snd.nxt = c->snd.iss + 1;
210 c->rcv.wnd = utcp->mtu;
211 c->snd.last = c->snd.nxt;
212 c->snd.cwnd = utcp->mtu;
215 // Add it to the sorted list of connections
217 utcp->connections[utcp->nconnections++] = c;
218 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
223 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
224 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
235 hdr.seq = c->snd.iss;
237 hdr.wnd = c->rcv.wnd;
241 set_state(c, SYN_SENT);
243 print_packet(utcp, "send", &hdr, sizeof hdr);
244 utcp->send(utcp, &hdr, sizeof hdr);
246 gettimeofday(&c->conn_timeout, NULL);
247 c->conn_timeout.tv_sec += utcp->timeout;
252 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
253 if(c->reapable || c->state != SYN_RECEIVED) {
254 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
258 debug("%p accepted, %p %p\n", c, recv, priv);
261 set_state(c, ESTABLISHED);
264 static void ack(struct utcp_connection *c, bool sendatleastone) {
265 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
266 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
267 char *data = c->sndbuf + seqdiff(c->snd.nxt, c->snd.una);
277 if(!left && !sendatleastone)
285 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
289 pkt->hdr.src = c->src;
290 pkt->hdr.dst = c->dst;
291 pkt->hdr.ack = c->rcv.nxt;
292 pkt->hdr.wnd = c->snd.wnd;
297 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
298 pkt->hdr.seq = c->snd.nxt;
300 memcpy(pkt->data, data, seglen);
302 c->snd.nxt += seglen;
306 if(c->state != ESTABLISHED && !left && seglen) {
318 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
319 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
325 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
327 debug("Error: send() called on closed connection %p\n", c);
337 debug("Error: send() called on unconnected connection %p\n", c);
348 debug("Error: send() called on closing connection %p\n", c);
353 // Add data to send buffer
363 uint32_t bufused = seqdiff(c->snd.nxt, c->snd.una);
365 /* Check our send buffer.
366 * - If it's big enough, just put the data in there.
367 * - If not, decide whether to enlarge if possible.
368 * - Cap len so it doesn't overflow our buffer.
371 if(len > c->sndbufsize - bufused && c->sndbufsize < c->maxsndbufsize) {
373 if(c->sndbufsize > c->maxsndbufsize / 2)
374 newbufsize = c->maxsndbufsize;
376 newbufsize = c->sndbufsize * 2;
377 if(bufused + len > newbufsize) {
378 if(bufused + len > c->maxsndbufsize)
379 newbufsize = c->maxsndbufsize;
381 newbufsize = bufused + len;
383 char *newbuf = realloc(c->sndbuf, newbufsize);
386 c->sndbufsize = newbufsize;
390 if(len > c->sndbufsize - bufused)
391 len = c->sndbufsize - bufused;
394 errno == EWOULDBLOCK;
398 memcpy(c->sndbuf + bufused, data, len);
405 static void swap_ports(struct hdr *hdr) {
406 uint16_t tmp = hdr->src;
411 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
425 print_packet(utcp, "recv", data, len);
427 // Drop packets smaller than the header
430 if(len < sizeof hdr) {
435 // Make a copy from the potentially unaligned data to a struct hdr
437 memcpy(&hdr, data, sizeof hdr);
441 // Drop packets with an unknown CTL flag
443 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
448 // Try to match the packet to an existing connection
450 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
452 // Is it for a new connection?
455 // Ignore RST packets
460 // Is it a SYN packet and are we LISTENing?
462 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
463 // If we don't want to accept it, send a RST back
464 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
469 // Try to allocate memory, otherwise send a RST back
470 c = allocate_connection(utcp, hdr.dst, hdr.src);
476 // Return SYN+ACK, go to SYN_RECEIVED state
477 c->snd.wnd = hdr.wnd;
478 c->rcv.irs = hdr.seq;
479 c->rcv.nxt = c->rcv.irs + 1;
480 set_state(c, SYN_RECEIVED);
484 hdr.ack = c->rcv.irs + 1;
485 hdr.seq = c->snd.iss;
487 print_packet(c->utcp, "send", &hdr, sizeof hdr);
488 utcp->send(utcp, &hdr, sizeof hdr);
490 // No, we don't want your packets, send a RST back
498 debug("%p state %s\n", c->utcp, strstate[c->state]);
500 // In case this is for a CLOSED connection, ignore the packet.
501 // TODO: make it so incoming packets can never match a CLOSED connection.
503 if(c->state == CLOSED)
506 // It is for an existing connection.
508 // 1. Drop invalid packets.
510 // 1a. Drop packets that should not happen in our current state.
527 // 1b. Drop packets with a sequence number not in our receive window.
531 if(c->state == SYN_SENT)
534 // TODO: handle packets overlapping c->rcv.nxt.
536 // Only use this when accepting out-of-order packets.
539 acceptable = hdr.seq == c->rcv.nxt;
541 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
544 // We don't accept data when the receive window is zero.
547 // Both start and end of packet must be within the receive window
548 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
549 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
551 if(c->state != SYN_SENT)
552 acceptable = hdr.seq == c->rcv.nxt;
556 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
557 // Ignore unacceptable RST packets.
560 // Otherwise, send an ACK back in the hope things improve.
564 c->snd.wnd = hdr.wnd; // TODO: move below
566 // 1c. Drop packets with an invalid ACK.
567 // ackno should not roll back, and it should also not be bigger than snd.nxt.
569 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
570 debug("Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
571 // Ignore unacceptable RST packets.
577 // 2. Handle RST packets
584 // The peer has refused our connection.
585 set_state(c, CLOSED);
586 errno = ECONNREFUSED;
593 // We haven't told the application about this connection yet. Silently delete.
602 // The peer has aborted our connection.
603 set_state(c, CLOSED);
613 // As far as the application is concerned, the connection has already been closed.
614 // If it has called utcp_close() already, we can immediately free this connection.
619 // Otherwise, immediately move to the CLOSED state.
620 set_state(c, CLOSED);
627 // 3. Advance snd.una
629 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
630 uint32_t prevrcvnxt = c->rcv.nxt;
633 int32_t data_acked = advanced;
640 // TODO: handle FIN as well.
645 assert(data_acked >= 0);
647 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
648 assert(data_acked <= bufused);
650 // Make room in the send buffer.
651 // TODO: try to avoid memmoving too much. Circular buffer?
652 uint32_t left = bufused - data_acked;
653 if(data_acked && left)
654 memmove(c->sndbuf, c->sndbuf + data_acked, left);
656 c->snd.una = hdr.ack;
659 c->snd.cwnd += utcp->mtu;
660 if(c->snd.cwnd > c->maxsndbufsize)
661 c->snd.cwnd = c->maxsndbufsize;
663 // Check if we have sent a FIN that is now ACKed.
666 if(c->snd.una == c->snd.last)
667 set_state(c, FIN_WAIT_2);
670 if(c->snd.una == c->snd.last) {
671 gettimeofday(&c->conn_timeout, NULL);
672 c->conn_timeout.tv_sec += 60;
673 set_state(c, TIME_WAIT);
683 debug("Triplicate ACK\n");
684 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
693 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
694 if(c->snd.una == c->snd.nxt)
695 timerclear(&c->rtrx_timeout);
698 // 5. Process SYN stuff
703 // This is a SYNACK. It should always have ACKed the SYN.
706 c->rcv.irs = hdr.seq;
707 c->rcv.nxt = hdr.seq;
708 set_state(c, ESTABLISHED);
709 // TODO: notify application of this somehow.
719 // Ehm, no. We should never receive a second SYN.
725 // SYN counts as one sequence number
729 // 6. Process new data
731 if(c->state == SYN_RECEIVED) {
732 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
736 // Are we still LISTENing?
738 utcp->accept(c, c->src);
740 if(c->state != ESTABLISHED) {
741 set_state(c, CLOSED);
751 // This should never happen.
761 // Ehm no, We should never receive more data after a FIN.
770 rxd = c->recv(c, data, len);
772 // TODO: once we have a receive buffer, handle the application not accepting all data.
773 fprintf(stderr, "c->recv(%p, %p, %zu) returned %zd\n", c, data, len, rxd);
779 rxd = len; // Bad application, bad!
787 // 7. Process FIN stuff
793 // This should never happen.
796 set_state(c, CLOSE_WAIT);
799 set_state(c, CLOSING);
802 gettimeofday(&c->conn_timeout, NULL);
803 c->conn_timeout.tv_sec += 60;
804 set_state(c, TIME_WAIT);
810 // Ehm, no. We should never receive a second FIN.
816 // FIN counts as one sequence number
820 // Inform the application that the peer closed the connection.
827 // Now we send something back if:
828 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
829 // -> sendatleastone = true
830 // - or we got an ack, so we should maybe send a bit more data
831 // -> sendatleastone = false
834 ack(c, prevrcvnxt != c->rcv.nxt);
844 hdr.ack = hdr.seq + len;
848 print_packet(utcp, "send", &hdr, sizeof hdr);
849 utcp->send(utcp, &hdr, sizeof hdr);
854 int utcp_shutdown(struct utcp_connection *c, int dir) {
855 debug("%p shutdown %d\n", c ? c->utcp : NULL, dir);
862 debug("Error: shutdown() called on closed connection %p\n", c);
874 set_state(c, CLOSED);
879 set_state(c, FIN_WAIT_1);
885 set_state(c, CLOSING);
900 int utcp_close(struct utcp_connection *c) {
901 if(utcp_shutdown(c, SHUT_RDWR))
907 int utcp_abort(struct utcp_connection *c) {
914 debug("Error: abort() called on closed connection %p\n", c);
929 set_state(c, CLOSED);
937 set_state(c, CLOSED);
947 hdr.seq = c->snd.nxt;
952 print_packet(c->utcp, "send", &hdr, sizeof hdr);
953 c->utcp->send(c->utcp, &hdr, sizeof hdr);
957 static void retransmit(struct utcp_connection *c) {
958 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
961 struct utcp *utcp = c->utcp;
968 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
972 pkt->hdr.src = c->src;
973 pkt->hdr.dst = c->dst;
977 // TODO: this should not happen
981 pkt->hdr.seq = c->snd.iss;
983 pkt->hdr.wnd = c->rcv.wnd;
985 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
986 utcp->send(utcp, pkt, sizeof pkt->hdr);
990 pkt->hdr.seq = c->snd.nxt;
991 pkt->hdr.ack = c->rcv.nxt;
992 pkt->hdr.ctl = SYN | ACK;
993 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
994 utcp->send(utcp, pkt, sizeof pkt->hdr);
999 pkt->hdr.seq = c->snd.una;
1000 pkt->hdr.ack = c->rcv.nxt;
1002 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
1003 if(c->state == FIN_WAIT_1)
1008 if(c->state == FIN_WAIT_1)
1009 pkt->hdr.ctl |= FIN;
1011 memcpy(pkt->data, c->sndbuf, len);
1012 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
1013 utcp->send(utcp, pkt, sizeof pkt->hdr + len);
1025 * One call to this function will loop through all connections,
1026 * checking if something needs to be resent or not.
1027 * The return value is the time to the next timeout in milliseconds,
1028 * or maybe a negative value if the timeout is infinite.
1030 int utcp_timeout(struct utcp *utcp) {
1032 gettimeofday(&now, NULL);
1033 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1035 for(int i = 0; i < utcp->nconnections; i++) {
1036 struct utcp_connection *c = utcp->connections[i];
1040 if(c->state == CLOSED) {
1042 debug("Reaping %p\n", c);
1049 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1053 c->recv(c, NULL, 0);
1057 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1061 if(c->poll && c->sndbufsize < c->maxsndbufsize / 2 && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1062 c->poll(c, c->maxsndbufsize - c->sndbufsize);
1064 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1065 next = c->conn_timeout;
1067 if(c->snd.nxt != c->snd.una) {
1068 c->rtrx_timeout = now;
1069 c->rtrx_timeout.tv_sec++;
1071 timerclear(&c->rtrx_timeout);
1074 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1075 next = c->rtrx_timeout;
1078 struct timeval diff;
1079 timersub(&next, &now, &diff);
1082 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
1085 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1086 struct utcp *utcp = calloc(1, sizeof *utcp);
1095 utcp->accept = accept;
1096 utcp->pre_accept = pre_accept;
1105 void utcp_exit(struct utcp *utcp) {
1108 for(int i = 0; i < utcp->nconnections; i++) {
1109 if(!utcp->connections[i]->reapable)
1110 debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1111 free(utcp->connections[i]->sndbuf);
1112 free(utcp->connections[i]);
1114 free(utcp->connections);
1118 uint16_t utcp_get_mtu(struct utcp *utcp) {
1122 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1123 // TODO: handle overhead of the header
1127 int utcp_get_user_timeout(struct utcp *u) {
1131 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1132 u->timeout = timeout;
1135 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1136 return c->maxsndbufsize;
1139 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1140 return c->maxsndbufsize - c->sndbufsize;
1143 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1144 c->maxsndbufsize = size;
1145 if(c->maxsndbufsize != size)
1146 c->maxsndbufsize = -1;
1149 bool utcp_get_nodelay(struct utcp_connection *c) {
1153 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1154 c->nodelay = nodelay;
1157 bool utcp_get_keepalive(struct utcp_connection *c) {
1158 return c->keepalive;
1161 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1162 c->keepalive = keepalive;
1165 size_t utcp_get_outq(struct utcp_connection *c) {
1166 return seqdiff(c->snd.nxt, c->snd.una);
1169 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1173 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {