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) {
120 const struct utcp_connection *a = *(struct utcp_connection **)va;
121 const struct utcp_connection *b = *(struct utcp_connection **)vb;
123 assert(a->src && b->src);
125 int c = (int)a->src - (int)b->src;
128 c = (int)a->dst - (int)b->dst;
132 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
133 if(!utcp->nconnections)
135 struct utcp_connection key = {
139 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
140 return match ? *match : NULL;
143 static void free_connection(struct utcp_connection *c) {
144 struct utcp *utcp = c->utcp;
145 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
149 int i = cp - utcp->connections;
150 memmove(cp + i, cp + i + 1, (utcp->nconnections - i - 1) * sizeof *cp);
151 utcp->nconnections--;
157 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
158 // Check whether this combination of src and dst is free
161 if(find_connection(utcp, src, dst)) {
165 } else { // If src == 0, generate a random port number with the high bit set
166 if(utcp->nconnections >= 32767) {
170 src = rand() | 0x8000;
171 while(find_connection(utcp, src, dst))
175 // Allocate memory for the new connection
177 if(utcp->nconnections >= utcp->nallocated) {
178 if(!utcp->nallocated)
179 utcp->nallocated = 4;
181 utcp->nallocated *= 2;
182 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
185 utcp->connections = new_array;
188 struct utcp_connection *c = calloc(1, sizeof *c);
192 c->sndbufsize = DEFAULT_SNDBUFSIZE;
193 c->maxsndbufsize = DEFAULT_MAXSNDBUFSIZE;
194 c->sndbuf = malloc(c->sndbufsize);
200 // Fill in the details
205 c->snd.una = c->snd.iss;
206 c->snd.nxt = c->snd.iss + 1;
207 c->rcv.wnd = utcp->mtu;
208 c->snd.last = c->snd.nxt;
209 c->snd.cwnd = utcp->mtu;
212 // Add it to the sorted list of connections
214 utcp->connections[utcp->nconnections++] = c;
215 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
220 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
221 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
232 hdr.seq = c->snd.iss;
234 hdr.wnd = c->rcv.wnd;
238 set_state(c, SYN_SENT);
240 print_packet(utcp, "send", &hdr, sizeof hdr);
241 utcp->send(utcp, &hdr, sizeof hdr);
243 gettimeofday(&c->conn_timeout, NULL);
244 c->conn_timeout.tv_sec += utcp->timeout;
249 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
250 if(c->reapable || c->state != SYN_RECEIVED) {
251 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
255 debug("%p accepted, %p %p\n", c, recv, priv);
258 set_state(c, ESTABLISHED);
261 static void ack(struct utcp_connection *c, bool sendatleastone) {
262 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
263 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
264 char *data = c->sndbuf + seqdiff(c->snd.nxt, c->snd.una);
274 if(!left && !sendatleastone)
282 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
286 pkt->hdr.src = c->src;
287 pkt->hdr.dst = c->dst;
288 pkt->hdr.ack = c->rcv.nxt;
289 pkt->hdr.wnd = c->snd.wnd;
294 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
295 pkt->hdr.seq = c->snd.nxt;
297 memcpy(pkt->data, data, seglen);
299 c->snd.nxt += seglen;
303 if(c->state != ESTABLISHED && !left && seglen) {
315 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
316 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
322 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
324 debug("Error: send() called on closed connection %p\n", c);
334 debug("Error: send() called on unconnected connection %p\n", c);
345 debug("Error: send() called on closing connection %p\n", c);
350 // Add data to send buffer
360 uint32_t bufused = seqdiff(c->snd.nxt, c->snd.una);
362 /* Check our send buffer.
363 * - If it's big enough, just put the data in there.
364 * - If not, decide whether to enlarge if possible.
365 * - Cap len so it doesn't overflow our buffer.
368 if(len > c->sndbufsize - bufused && c->sndbufsize < c->maxsndbufsize) {
370 if(c->sndbufsize > c->maxsndbufsize / 2)
371 newbufsize = c->maxsndbufsize;
373 newbufsize = c->sndbufsize * 2;
374 if(bufused + len > newbufsize) {
375 if(bufused + len > c->maxsndbufsize)
376 newbufsize = c->maxsndbufsize;
378 newbufsize = bufused + len;
380 char *newbuf = realloc(c->sndbuf, newbufsize);
383 c->sndbufsize = newbufsize;
387 if(len > c->sndbufsize - bufused)
388 len = c->sndbufsize - bufused;
391 errno == EWOULDBLOCK;
395 memcpy(c->sndbuf + bufused, data, len);
402 static void swap_ports(struct hdr *hdr) {
403 uint16_t tmp = hdr->src;
408 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
422 print_packet(utcp, "recv", data, len);
424 // Drop packets smaller than the header
427 if(len < sizeof hdr) {
432 // Make a copy from the potentially unaligned data to a struct hdr
434 memcpy(&hdr, data, sizeof hdr);
438 // Drop packets with an unknown CTL flag
440 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
445 // Try to match the packet to an existing connection
447 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
449 // Is it for a new connection?
452 // Ignore RST packets
457 // Is it a SYN packet and are we LISTENing?
459 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
460 // If we don't want to accept it, send a RST back
461 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
466 // Try to allocate memory, otherwise send a RST back
467 c = allocate_connection(utcp, hdr.dst, hdr.src);
473 // Return SYN+ACK, go to SYN_RECEIVED state
474 c->snd.wnd = hdr.wnd;
475 c->rcv.irs = hdr.seq;
476 c->rcv.nxt = c->rcv.irs + 1;
477 set_state(c, SYN_RECEIVED);
481 hdr.ack = c->rcv.irs + 1;
482 hdr.seq = c->snd.iss;
484 print_packet(c->utcp, "send", &hdr, sizeof hdr);
485 utcp->send(utcp, &hdr, sizeof hdr);
487 // No, we don't want your packets, send a RST back
495 debug("%p state %s\n", c->utcp, strstate[c->state]);
497 // In case this is for a CLOSED connection, ignore the packet.
498 // TODO: make it so incoming packets can never match a CLOSED connection.
500 if(c->state == CLOSED)
503 // It is for an existing connection.
505 // 1. Drop invalid packets.
507 // 1a. Drop packets that should not happen in our current state.
524 // 1b. Drop packets with a sequence number not in our receive window.
528 if(c->state == SYN_SENT)
531 // TODO: handle packets overlapping c->rcv.nxt.
533 // Only use this when accepting out-of-order packets.
536 acceptable = hdr.seq == c->rcv.nxt;
538 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
541 // We don't accept data when the receive window is zero.
544 // Both start and end of packet must be within the receive window
545 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
546 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
548 if(c->state != SYN_SENT)
549 acceptable = hdr.seq == c->rcv.nxt;
553 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
554 // Ignore unacceptable RST packets.
557 // Otherwise, send an ACK back in the hope things improve.
561 c->snd.wnd = hdr.wnd; // TODO: move below
563 // 1c. Drop packets with an invalid ACK.
564 // ackno should not roll back, and it should also not be bigger than snd.nxt.
566 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
567 debug("Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
568 // Ignore unacceptable RST packets.
574 // 2. Handle RST packets
581 // The peer has refused our connection.
582 set_state(c, CLOSED);
583 errno = ECONNREFUSED;
590 // We haven't told the application about this connection yet. Silently delete.
599 // The peer has aborted our connection.
600 set_state(c, CLOSED);
610 // As far as the application is concerned, the connection has already been closed.
611 // If it has called utcp_close() already, we can immediately free this connection.
616 // Otherwise, immediately move to the CLOSED state.
617 set_state(c, CLOSED);
624 // 3. Advance snd.una
626 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
627 uint32_t prevrcvnxt = c->rcv.nxt;
630 int32_t data_acked = advanced;
637 // TODO: handle FIN as well.
642 assert(data_acked >= 0);
644 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
645 assert(data_acked <= bufused);
647 // Make room in the send buffer.
648 // TODO: try to avoid memmoving too much. Circular buffer?
649 uint32_t left = bufused - data_acked;
650 if(data_acked && left)
651 memmove(c->sndbuf, c->sndbuf + data_acked, left);
653 c->snd.una = hdr.ack;
656 c->snd.cwnd += utcp->mtu;
657 if(c->snd.cwnd > c->maxsndbufsize)
658 c->snd.cwnd = c->maxsndbufsize;
660 // Check if we have sent a FIN that is now ACKed.
663 if(c->snd.una == c->snd.last)
664 set_state(c, FIN_WAIT_2);
667 if(c->snd.una == c->snd.last) {
668 gettimeofday(&c->conn_timeout, NULL);
669 c->conn_timeout.tv_sec += 60;
670 set_state(c, TIME_WAIT);
680 debug("Triplicate ACK\n");
681 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
690 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
691 if(c->snd.una == c->snd.nxt)
692 timerclear(&c->rtrx_timeout);
695 // 5. Process SYN stuff
700 // This is a SYNACK. It should always have ACKed the SYN.
703 c->rcv.irs = hdr.seq;
704 c->rcv.nxt = hdr.seq;
705 set_state(c, ESTABLISHED);
706 // TODO: notify application of this somehow.
716 // Ehm, no. We should never receive a second SYN.
722 // SYN counts as one sequence number
726 // 6. Process new data
728 if(c->state == SYN_RECEIVED) {
729 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
733 // Are we still LISTENing?
735 utcp->accept(c, c->src);
737 if(c->state != ESTABLISHED) {
738 set_state(c, CLOSED);
748 // This should never happen.
758 // Ehm no, We should never receive more data after a FIN.
767 rxd = c->recv(c, data, len);
769 // TODO: once we have a receive buffer, handle the application not accepting all data.
770 fprintf(stderr, "c->recv(%p, %p, %zu) returned %zd\n", c, data, len, rxd);
776 rxd = len; // Bad application, bad!
784 // 7. Process FIN stuff
790 // This should never happen.
793 set_state(c, CLOSE_WAIT);
796 set_state(c, CLOSING);
799 gettimeofday(&c->conn_timeout, NULL);
800 c->conn_timeout.tv_sec += 60;
801 set_state(c, TIME_WAIT);
807 // Ehm, no. We should never receive a second FIN.
813 // FIN counts as one sequence number
817 // Inform the application that the peer closed the connection.
824 // Now we send something back if:
825 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
826 // -> sendatleastone = true
827 // - or we got an ack, so we should maybe send a bit more data
828 // -> sendatleastone = false
831 ack(c, prevrcvnxt != c->rcv.nxt);
841 hdr.ack = hdr.seq + len;
845 print_packet(utcp, "send", &hdr, sizeof hdr);
846 utcp->send(utcp, &hdr, sizeof hdr);
851 int utcp_shutdown(struct utcp_connection *c, int dir) {
852 debug("%p shutdown %d\n", c ? c->utcp : NULL, dir);
859 debug("Error: shutdown() called on closed connection %p\n", c);
871 set_state(c, CLOSED);
876 set_state(c, FIN_WAIT_1);
882 set_state(c, CLOSING);
897 int utcp_close(struct utcp_connection *c) {
898 if(utcp_shutdown(c, SHUT_RDWR))
904 int utcp_abort(struct utcp_connection *c) {
911 debug("Error: abort() called on closed connection %p\n", c);
926 set_state(c, CLOSED);
934 set_state(c, CLOSED);
944 hdr.seq = c->snd.nxt;
949 print_packet(c->utcp, "send", &hdr, sizeof hdr);
950 c->utcp->send(c->utcp, &hdr, sizeof hdr);
954 static void retransmit(struct utcp_connection *c) {
955 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
958 struct utcp *utcp = c->utcp;
965 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
969 pkt->hdr.src = c->src;
970 pkt->hdr.dst = c->dst;
974 // TODO: this should not happen
978 pkt->hdr.seq = c->snd.iss;
980 pkt->hdr.wnd = c->rcv.wnd;
982 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
983 utcp->send(utcp, pkt, sizeof pkt->hdr);
987 pkt->hdr.seq = c->snd.nxt;
988 pkt->hdr.ack = c->rcv.nxt;
989 pkt->hdr.ctl = SYN | ACK;
990 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
991 utcp->send(utcp, pkt, sizeof pkt->hdr);
996 pkt->hdr.seq = c->snd.una;
997 pkt->hdr.ack = c->rcv.nxt;
999 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
1000 if(c->state == FIN_WAIT_1)
1005 if(c->state == FIN_WAIT_1)
1006 pkt->hdr.ctl |= FIN;
1008 memcpy(pkt->data, c->sndbuf, len);
1009 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
1010 utcp->send(utcp, pkt, sizeof pkt->hdr + len);
1022 * One call to this function will loop through all connections,
1023 * checking if something needs to be resent or not.
1024 * The return value is the time to the next timeout in milliseconds,
1025 * or maybe a negative value if the timeout is infinite.
1027 int utcp_timeout(struct utcp *utcp) {
1029 gettimeofday(&now, NULL);
1030 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1032 for(int i = 0; i < utcp->nconnections; i++) {
1033 struct utcp_connection *c = utcp->connections[i];
1037 if(c->state == CLOSED) {
1039 debug("Reaping %p\n", c);
1046 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1050 c->recv(c, NULL, 0);
1054 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1058 if(c->poll && c->sndbufsize < c->maxsndbufsize / 2 && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1059 c->poll(c, c->maxsndbufsize - c->sndbufsize);
1061 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1062 next = c->conn_timeout;
1064 if(c->snd.nxt != c->snd.una) {
1065 c->rtrx_timeout = now;
1066 c->rtrx_timeout.tv_sec++;
1068 timerclear(&c->rtrx_timeout);
1071 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1072 next = c->rtrx_timeout;
1075 struct timeval diff;
1076 timersub(&next, &now, &diff);
1079 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
1082 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1083 struct utcp *utcp = calloc(1, sizeof *utcp);
1092 utcp->accept = accept;
1093 utcp->pre_accept = pre_accept;
1102 void utcp_exit(struct utcp *utcp) {
1105 for(int i = 0; i < utcp->nconnections; i++) {
1106 if(!utcp->connections[i]->reapable)
1107 debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1108 free(utcp->connections[i]->sndbuf);
1109 free(utcp->connections[i]);
1111 free(utcp->connections);
1115 uint16_t utcp_get_mtu(struct utcp *utcp) {
1119 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1120 // TODO: handle overhead of the header
1124 int utcp_get_user_timeout(struct utcp *u) {
1128 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1129 u->timeout = timeout;
1132 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1133 return c->maxsndbufsize;
1136 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1137 return c->maxsndbufsize - c->sndbufsize;
1140 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1141 c->maxsndbufsize = size;
1142 if(c->maxsndbufsize != size)
1143 c->maxsndbufsize = -1;
1146 bool utcp_get_nodelay(struct utcp_connection *c) {
1150 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1151 c->nodelay = nodelay;
1154 bool utcp_get_keepalive(struct utcp_connection *c) {
1155 return c->keepalive;
1158 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1159 c->keepalive = keepalive;
1162 size_t utcp_get_outq(struct utcp_connection *c) {
1163 return seqdiff(c->snd.nxt, c->snd.una);
1166 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1170 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {