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);
133 fprintf(stderr, "%p = realloc(%p, %zu)\n", newdata, buf->data, newsize);
139 fprintf(stderr, "memcpy(%p, %p, %zu)\n", buf->data + buf->used, data, len);
140 memcpy(buf->data + buf->used, data, len);
145 // Get data from the buffer. data can be NULL.
146 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
150 memcpy(data, buf->data, len);
152 memmove(buf->data, buf->data + len, buf->used - len);
157 // Copy data from the buffer without removing it.
158 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
159 if(offset >= buf->used)
161 if(offset + len > buf->used)
162 len = buf->used - offset;
163 memcpy(data, buf->data + offset, len);
167 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
168 memset(buf, 0, sizeof *buf);
169 buf->data = malloc(len);
173 buf->maxsize = maxlen;
177 static void buffer_exit(struct buffer *buf) {
179 memset(buf, 0, sizeof *buf);
182 static uint32_t buffer_free(const struct buffer *buf) {
183 return buf->maxsize - buf->used;
186 // Connections are stored in a sorted list.
187 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
189 static int compare(const void *va, const void *vb) {
192 const struct utcp_connection *a = *(struct utcp_connection **)va;
193 const struct utcp_connection *b = *(struct utcp_connection **)vb;
196 assert(a->src && b->src);
198 int c = (int)a->src - (int)b->src;
201 c = (int)a->dst - (int)b->dst;
205 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
206 if(!utcp->nconnections)
208 struct utcp_connection key = {
212 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
213 return match ? *match : NULL;
216 static void free_connection(struct utcp_connection *c) {
217 struct utcp *utcp = c->utcp;
218 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
222 int i = cp - utcp->connections;
223 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof *cp);
224 utcp->nconnections--;
226 buffer_exit(&c->sndbuf);
230 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
231 // Check whether this combination of src and dst is free
234 if(find_connection(utcp, src, dst)) {
238 } else { // If src == 0, generate a random port number with the high bit set
239 if(utcp->nconnections >= 32767) {
243 src = rand() | 0x8000;
244 while(find_connection(utcp, src, dst))
248 // Allocate memory for the new connection
250 if(utcp->nconnections >= utcp->nallocated) {
251 if(!utcp->nallocated)
252 utcp->nallocated = 4;
254 utcp->nallocated *= 2;
255 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
258 utcp->connections = new_array;
261 struct utcp_connection *c = calloc(1, sizeof *c);
265 if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
270 // Fill in the details
275 c->snd.una = c->snd.iss;
276 c->snd.nxt = c->snd.iss + 1;
277 c->rcv.wnd = utcp->mtu;
278 c->snd.last = c->snd.nxt;
279 c->snd.cwnd = utcp->mtu;
282 // Add it to the sorted list of connections
284 utcp->connections[utcp->nconnections++] = c;
285 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
290 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
291 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
302 hdr.seq = c->snd.iss;
304 hdr.wnd = c->rcv.wnd;
308 set_state(c, SYN_SENT);
310 print_packet(utcp, "send", &hdr, sizeof hdr);
311 utcp->send(utcp, &hdr, sizeof hdr);
313 gettimeofday(&c->conn_timeout, NULL);
314 c->conn_timeout.tv_sec += utcp->timeout;
319 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
320 if(c->reapable || c->state != SYN_RECEIVED) {
321 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
325 debug("%p accepted, %p %p\n", c, recv, priv);
328 set_state(c, ESTABLISHED);
331 static void ack(struct utcp_connection *c, bool sendatleastone) {
332 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
333 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
343 if(!left && !sendatleastone)
351 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
355 pkt->hdr.src = c->src;
356 pkt->hdr.dst = c->dst;
357 pkt->hdr.ack = c->rcv.nxt;
358 pkt->hdr.wnd = c->snd.wnd;
363 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
364 pkt->hdr.seq = c->snd.nxt;
366 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
368 c->snd.nxt += seglen;
371 if(c->state != ESTABLISHED && !left && seglen) {
383 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
384 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
390 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
392 debug("Error: send() called on closed connection %p\n", c);
402 debug("Error: send() called on unconnected connection %p\n", c);
413 debug("Error: send() called on closing connection %p\n", c);
418 // Add data to send buffer
428 len = buffer_put(&c->sndbuf, data, len);
439 static void swap_ports(struct hdr *hdr) {
440 uint16_t tmp = hdr->src;
445 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
459 print_packet(utcp, "recv", data, len);
461 // Drop packets smaller than the header
464 if(len < sizeof hdr) {
469 // Make a copy from the potentially unaligned data to a struct hdr
471 memcpy(&hdr, data, sizeof hdr);
475 // Drop packets with an unknown CTL flag
477 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
482 // Try to match the packet to an existing connection
484 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
486 // Is it for a new connection?
489 // Ignore RST packets
494 // Is it a SYN packet and are we LISTENing?
496 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
497 // If we don't want to accept it, send a RST back
498 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
503 // Try to allocate memory, otherwise send a RST back
504 c = allocate_connection(utcp, hdr.dst, hdr.src);
510 // Return SYN+ACK, go to SYN_RECEIVED state
511 c->snd.wnd = hdr.wnd;
512 c->rcv.irs = hdr.seq;
513 c->rcv.nxt = c->rcv.irs + 1;
514 set_state(c, SYN_RECEIVED);
518 hdr.ack = c->rcv.irs + 1;
519 hdr.seq = c->snd.iss;
521 print_packet(c->utcp, "send", &hdr, sizeof hdr);
522 utcp->send(utcp, &hdr, sizeof hdr);
524 // No, we don't want your packets, send a RST back
532 debug("%p state %s\n", c->utcp, strstate[c->state]);
534 // In case this is for a CLOSED connection, ignore the packet.
535 // TODO: make it so incoming packets can never match a CLOSED connection.
537 if(c->state == CLOSED)
540 // It is for an existing connection.
542 uint32_t prevrcvnxt = c->rcv.nxt;
544 // 1. Drop invalid packets.
546 // 1a. Drop packets that should not happen in our current state.
563 // 1b. Drop packets with a sequence number not in our receive window.
567 if(c->state == SYN_SENT)
570 // TODO: handle packets overlapping c->rcv.nxt.
572 // Only use this when accepting out-of-order packets.
575 acceptable = hdr.seq == c->rcv.nxt;
577 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
580 // We don't accept data when the receive window is zero.
583 // Both start and end of packet must be within the receive window
584 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
585 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
587 if(c->state != SYN_SENT)
588 acceptable = hdr.seq == c->rcv.nxt;
592 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
593 // Ignore unacceptable RST packets.
596 // Otherwise, send an ACK back in the hope things improve.
600 c->snd.wnd = hdr.wnd; // TODO: move below
602 // 1c. Drop packets with an invalid ACK.
603 // ackno should not roll back, and it should also not be bigger than snd.nxt.
605 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
606 debug("Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
607 // Ignore unacceptable RST packets.
613 // 2. Handle RST packets
620 // The peer has refused our connection.
621 set_state(c, CLOSED);
622 errno = ECONNREFUSED;
629 // We haven't told the application about this connection yet. Silently delete.
638 // The peer has aborted our connection.
639 set_state(c, CLOSED);
649 // As far as the application is concerned, the connection has already been closed.
650 // If it has called utcp_close() already, we can immediately free this connection.
655 // Otherwise, immediately move to the CLOSED state.
656 set_state(c, CLOSED);
663 // 3. Advance snd.una
665 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
666 prevrcvnxt = c->rcv.nxt;
669 int32_t data_acked = advanced;
676 // TODO: handle FIN as well.
681 assert(data_acked >= 0);
683 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
684 assert(data_acked <= bufused);
687 buffer_get(&c->sndbuf, NULL, data_acked);
689 c->snd.una = hdr.ack;
692 c->snd.cwnd += utcp->mtu;
693 if(c->snd.cwnd > c->sndbuf.maxsize)
694 c->snd.cwnd = c->sndbuf.maxsize;
696 // Check if we have sent a FIN that is now ACKed.
699 if(c->snd.una == c->snd.last)
700 set_state(c, FIN_WAIT_2);
703 if(c->snd.una == c->snd.last) {
704 gettimeofday(&c->conn_timeout, NULL);
705 c->conn_timeout.tv_sec += 60;
706 set_state(c, TIME_WAIT);
716 debug("Triplicate ACK\n");
717 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
726 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
727 if(c->snd.una == c->snd.nxt)
728 timerclear(&c->rtrx_timeout);
731 // 5. Process SYN stuff
736 // This is a SYNACK. It should always have ACKed the SYN.
739 c->rcv.irs = hdr.seq;
740 c->rcv.nxt = hdr.seq;
741 set_state(c, ESTABLISHED);
742 // TODO: notify application of this somehow.
752 // Ehm, no. We should never receive a second SYN.
758 // SYN counts as one sequence number
762 // 6. Process new data
764 if(c->state == SYN_RECEIVED) {
765 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
769 // Are we still LISTENing?
771 utcp->accept(c, c->src);
773 if(c->state != ESTABLISHED) {
774 set_state(c, CLOSED);
784 // This should never happen.
794 // Ehm no, We should never receive more data after a FIN.
803 rxd = c->recv(c, data, len);
805 // TODO: once we have a receive buffer, handle the application not accepting all data.
806 fprintf(stderr, "c->recv(%p, %p, %zu) returned %zd\n", c, data, len, rxd);
812 rxd = len; // Bad application, bad!
820 // 7. Process FIN stuff
826 // This should never happen.
829 set_state(c, CLOSE_WAIT);
832 set_state(c, CLOSING);
835 gettimeofday(&c->conn_timeout, NULL);
836 c->conn_timeout.tv_sec += 60;
837 set_state(c, TIME_WAIT);
843 // Ehm, no. We should never receive a second FIN.
849 // FIN counts as one sequence number
853 // Inform the application that the peer closed the connection.
860 // Now we send something back if:
861 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
862 // -> sendatleastone = true
863 // - or we got an ack, so we should maybe send a bit more data
864 // -> sendatleastone = false
867 ack(c, prevrcvnxt != c->rcv.nxt);
877 hdr.ack = hdr.seq + len;
881 print_packet(utcp, "send", &hdr, sizeof hdr);
882 utcp->send(utcp, &hdr, sizeof hdr);
887 int utcp_shutdown(struct utcp_connection *c, int dir) {
888 debug("%p shutdown %d\n", c ? c->utcp : NULL, dir);
895 debug("Error: shutdown() called on closed connection %p\n", c);
907 set_state(c, CLOSED);
912 set_state(c, FIN_WAIT_1);
918 set_state(c, CLOSING);
933 int utcp_close(struct utcp_connection *c) {
934 if(utcp_shutdown(c, SHUT_RDWR))
940 int utcp_abort(struct utcp_connection *c) {
947 debug("Error: abort() called on closed connection %p\n", c);
962 set_state(c, CLOSED);
970 set_state(c, CLOSED);
980 hdr.seq = c->snd.nxt;
985 print_packet(c->utcp, "send", &hdr, sizeof hdr);
986 c->utcp->send(c->utcp, &hdr, sizeof hdr);
990 static void retransmit(struct utcp_connection *c) {
991 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
994 struct utcp *utcp = c->utcp;
1001 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
1005 pkt->hdr.src = c->src;
1006 pkt->hdr.dst = c->dst;
1010 // TODO: this should not happen
1014 pkt->hdr.seq = c->snd.iss;
1016 pkt->hdr.wnd = c->rcv.wnd;
1018 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
1019 utcp->send(utcp, pkt, sizeof pkt->hdr);
1023 pkt->hdr.seq = c->snd.nxt;
1024 pkt->hdr.ack = c->rcv.nxt;
1025 pkt->hdr.ctl = SYN | ACK;
1026 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
1027 utcp->send(utcp, pkt, sizeof pkt->hdr);
1032 pkt->hdr.seq = c->snd.una;
1033 pkt->hdr.ack = c->rcv.nxt;
1035 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
1036 if(c->state == FIN_WAIT_1)
1041 if(c->state == FIN_WAIT_1)
1042 pkt->hdr.ctl |= FIN;
1044 buffer_copy(&c->sndbuf, pkt->data, 0, len);
1045 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
1046 utcp->send(utcp, pkt, sizeof pkt->hdr + len);
1058 * One call to this function will loop through all connections,
1059 * checking if something needs to be resent or not.
1060 * The return value is the time to the next timeout in milliseconds,
1061 * or maybe a negative value if the timeout is infinite.
1063 int utcp_timeout(struct utcp *utcp) {
1065 gettimeofday(&now, NULL);
1066 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1068 for(int i = 0; i < utcp->nconnections; i++) {
1069 struct utcp_connection *c = utcp->connections[i];
1073 if(c->state == CLOSED) {
1075 debug("Reaping %p\n", c);
1082 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1086 c->recv(c, NULL, 0);
1090 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1094 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1095 c->poll(c, buffer_free(&c->sndbuf));
1097 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1098 next = c->conn_timeout;
1100 if(c->snd.nxt != c->snd.una) {
1101 c->rtrx_timeout = now;
1102 c->rtrx_timeout.tv_sec++;
1104 timerclear(&c->rtrx_timeout);
1107 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1108 next = c->rtrx_timeout;
1111 struct timeval diff;
1112 timersub(&next, &now, &diff);
1115 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
1118 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1119 struct utcp *utcp = calloc(1, sizeof *utcp);
1128 utcp->accept = accept;
1129 utcp->pre_accept = pre_accept;
1138 void utcp_exit(struct utcp *utcp) {
1141 for(int i = 0; i < utcp->nconnections; i++) {
1142 if(!utcp->connections[i]->reapable)
1143 debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1144 buffer_exit(&utcp->connections[i]->sndbuf);
1145 free(utcp->connections[i]);
1147 free(utcp->connections);
1151 uint16_t utcp_get_mtu(struct utcp *utcp) {
1155 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1156 // TODO: handle overhead of the header
1160 int utcp_get_user_timeout(struct utcp *u) {
1164 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1165 u->timeout = timeout;
1168 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1169 return c->sndbuf.maxsize;
1172 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1173 return buffer_free(&c->sndbuf);
1176 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1177 c->sndbuf.maxsize = size;
1178 if(c->sndbuf.maxsize != size)
1179 c->sndbuf.maxsize = -1;
1182 bool utcp_get_nodelay(struct utcp_connection *c) {
1186 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1187 c->nodelay = nodelay;
1190 bool utcp_get_keepalive(struct utcp_connection *c) {
1191 return c->keepalive;
1194 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1195 c->keepalive = keepalive;
1198 size_t utcp_get_outq(struct utcp_connection *c) {
1199 return seqdiff(c->snd.nxt, c->snd.una);
1202 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1206 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {