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)
279 char data[c->utcp->mtu];
282 pkt.hdr.src = c->src;
283 pkt.hdr.dst = c->dst;
284 pkt.hdr.ack = c->rcv.nxt;
285 pkt.hdr.wnd = c->snd.wnd;
290 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
291 pkt.hdr.seq = c->snd.nxt;
293 memcpy(pkt.data, data, seglen);
295 c->snd.nxt += seglen;
299 if(c->state != ESTABLISHED && !left && seglen) {
311 print_packet(c->utcp, "send", &pkt, sizeof pkt.hdr + seglen);
312 c->utcp->send(c->utcp, &pkt, sizeof pkt.hdr + seglen);
316 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
318 debug("Error: send() called on closed connection %p\n", c);
328 debug("Error: send() called on unconnected connection %p\n", c);
339 debug("Error: send() called on closing connection %p\n", c);
344 // Add data to send buffer
354 uint32_t bufused = seqdiff(c->snd.nxt, c->snd.una);
356 /* Check our send buffer.
357 * - If it's big enough, just put the data in there.
358 * - If not, decide whether to enlarge if possible.
359 * - Cap len so it doesn't overflow our buffer.
362 if(len > c->sndbufsize - bufused && c->sndbufsize < c->maxsndbufsize) {
364 if(c->sndbufsize > c->maxsndbufsize / 2)
365 newbufsize = c->maxsndbufsize;
367 newbufsize = c->sndbufsize * 2;
368 if(bufused + len > newbufsize) {
369 if(bufused + len > c->maxsndbufsize)
370 newbufsize = c->maxsndbufsize;
372 newbufsize = bufused + len;
374 char *newbuf = realloc(c->sndbuf, newbufsize);
377 c->sndbufsize = newbufsize;
381 if(len > c->sndbufsize - bufused)
382 len = c->sndbufsize - bufused;
385 errno == EWOULDBLOCK;
389 memcpy(c->sndbuf + bufused, data, len);
396 static void swap_ports(struct hdr *hdr) {
397 uint16_t tmp = hdr->src;
402 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
416 print_packet(utcp, "recv", data, len);
418 // Drop packets smaller than the header
421 if(len < sizeof hdr) {
426 // Make a copy from the potentially unaligned data to a struct hdr
428 memcpy(&hdr, data, sizeof hdr);
432 // Drop packets with an unknown CTL flag
434 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
439 // Try to match the packet to an existing connection
441 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
443 // Is it for a new connection?
446 // Ignore RST packets
451 // Is it a SYN packet and are we LISTENing?
453 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
454 // If we don't want to accept it, send a RST back
455 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
460 // Try to allocate memory, otherwise send a RST back
461 c = allocate_connection(utcp, hdr.dst, hdr.src);
467 // Return SYN+ACK, go to SYN_RECEIVED state
468 c->snd.wnd = hdr.wnd;
469 c->rcv.irs = hdr.seq;
470 c->rcv.nxt = c->rcv.irs + 1;
471 set_state(c, SYN_RECEIVED);
475 hdr.ack = c->rcv.irs + 1;
476 hdr.seq = c->snd.iss;
478 print_packet(c->utcp, "send", &hdr, sizeof hdr);
479 utcp->send(utcp, &hdr, sizeof hdr);
481 // No, we don't want your packets, send a RST back
489 debug("%p state %s\n", c->utcp, strstate[c->state]);
491 // In case this is for a CLOSED connection, ignore the packet.
492 // TODO: make it so incoming packets can never match a CLOSED connection.
494 if(c->state == CLOSED)
497 // It is for an existing connection.
499 // 1. Drop invalid packets.
501 // 1a. Drop packets that should not happen in our current state.
518 // 1b. Drop packets with a sequence number not in our receive window.
522 if(c->state == SYN_SENT)
525 // TODO: handle packets overlapping c->rcv.nxt.
527 // Only use this when accepting out-of-order packets.
530 acceptable = hdr.seq == c->rcv.nxt;
532 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
535 // We don't accept data when the receive window is zero.
538 // Both start and end of packet must be within the receive window
539 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
540 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
542 if(c->state != SYN_SENT)
543 acceptable = hdr.seq == c->rcv.nxt;
547 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
548 // Ignore unacceptable RST packets.
551 // Otherwise, send an ACK back in the hope things improve.
555 c->snd.wnd = hdr.wnd; // TODO: move below
557 // 1c. Drop packets with an invalid ACK.
558 // ackno should not roll back, and it should also not be bigger than snd.nxt.
560 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
561 debug("Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
562 // Ignore unacceptable RST packets.
568 // 2. Handle RST packets
575 // The peer has refused our connection.
576 set_state(c, CLOSED);
577 errno = ECONNREFUSED;
584 // We haven't told the application about this connection yet. Silently delete.
593 // The peer has aborted our connection.
594 set_state(c, CLOSED);
604 // As far as the application is concerned, the connection has already been closed.
605 // If it has called utcp_close() already, we can immediately free this connection.
610 // Otherwise, immediately move to the CLOSED state.
611 set_state(c, CLOSED);
618 // 3. Advance snd.una
620 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
621 uint32_t prevrcvnxt = c->rcv.nxt;
624 int32_t data_acked = advanced;
631 // TODO: handle FIN as well.
636 assert(data_acked >= 0);
638 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
639 assert(data_acked <= bufused);
641 // Make room in the send buffer.
642 // TODO: try to avoid memmoving too much. Circular buffer?
643 uint32_t left = bufused - data_acked;
644 if(data_acked && left)
645 memmove(c->sndbuf, c->sndbuf + data_acked, left);
647 c->snd.una = hdr.ack;
650 c->snd.cwnd += utcp->mtu;
651 if(c->snd.cwnd > c->maxsndbufsize)
652 c->snd.cwnd = c->maxsndbufsize;
654 // Check if we have sent a FIN that is now ACKed.
657 if(c->snd.una == c->snd.last)
658 set_state(c, FIN_WAIT_2);
661 if(c->snd.una == c->snd.last) {
662 gettimeofday(&c->conn_timeout, NULL);
663 c->conn_timeout.tv_sec += 60;
664 set_state(c, TIME_WAIT);
674 debug("Triplicate ACK\n");
675 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
684 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
685 if(c->snd.una == c->snd.nxt)
686 timerclear(&c->rtrx_timeout);
689 // 5. Process SYN stuff
694 // This is a SYNACK. It should always have ACKed the SYN.
697 c->rcv.irs = hdr.seq;
698 c->rcv.nxt = hdr.seq;
699 set_state(c, ESTABLISHED);
700 // TODO: notify application of this somehow.
710 // Ehm, no. We should never receive a second SYN.
716 // SYN counts as one sequence number
720 // 6. Process new data
722 if(c->state == SYN_RECEIVED) {
723 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
727 // Are we still LISTENing?
729 utcp->accept(c, c->src);
731 if(c->state != ESTABLISHED) {
732 set_state(c, CLOSED);
742 // This should never happen.
752 // Ehm no, We should never receive more data after a FIN.
761 rxd = c->recv(c, data, len);
763 // TODO: once we have a receive buffer, handle the application not accepting all data.
764 fprintf(stderr, "c->recv(%p, %p, %zu) returned %zd\n", c, data, len, rxd);
770 rxd = len; // Bad application, bad!
778 // 7. Process FIN stuff
784 // This should never happen.
787 set_state(c, CLOSE_WAIT);
790 set_state(c, CLOSING);
793 gettimeofday(&c->conn_timeout, NULL);
794 c->conn_timeout.tv_sec += 60;
795 set_state(c, TIME_WAIT);
801 // Ehm, no. We should never receive a second FIN.
807 // FIN counts as one sequence number
811 // Inform the application that the peer closed the connection.
818 // Now we send something back if:
819 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
820 // -> sendatleastone = true
821 // - or we got an ack, so we should maybe send a bit more data
822 // -> sendatleastone = false
825 ack(c, prevrcvnxt != c->rcv.nxt);
835 hdr.ack = hdr.seq + len;
839 print_packet(utcp, "send", &hdr, sizeof hdr);
840 utcp->send(utcp, &hdr, sizeof hdr);
845 int utcp_shutdown(struct utcp_connection *c, int dir) {
846 debug("%p shutdown %d\n", c ? c->utcp : NULL, dir);
853 debug("Error: shutdown() called on closed connection %p\n", c);
865 set_state(c, CLOSED);
870 set_state(c, FIN_WAIT_1);
876 set_state(c, CLOSING);
891 int utcp_close(struct utcp_connection *c) {
892 if(utcp_shutdown(c, SHUT_RDWR))
898 int utcp_abort(struct utcp_connection *c) {
905 debug("Error: abort() called on closed connection %p\n", c);
920 set_state(c, CLOSED);
928 set_state(c, CLOSED);
938 hdr.seq = c->snd.nxt;
943 print_packet(c->utcp, "send", &hdr, sizeof hdr);
944 c->utcp->send(c->utcp, &hdr, sizeof hdr);
948 static void retransmit(struct utcp_connection *c) {
949 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
952 struct utcp *utcp = c->utcp;
956 char data[c->utcp->mtu];
959 pkt.hdr.src = c->src;
960 pkt.hdr.dst = c->dst;
964 // TODO: this should not happen
968 pkt.hdr.seq = c->snd.iss;
970 pkt.hdr.wnd = c->rcv.wnd;
972 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
973 utcp->send(utcp, &pkt, sizeof pkt.hdr);
977 pkt.hdr.seq = c->snd.nxt;
978 pkt.hdr.ack = c->rcv.nxt;
979 pkt.hdr.ctl = SYN | ACK;
980 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
981 utcp->send(utcp, &pkt, sizeof pkt.hdr);
986 pkt.hdr.seq = c->snd.una;
987 pkt.hdr.ack = c->rcv.nxt;
989 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
990 if(c->state == FIN_WAIT_1)
995 if(c->state == FIN_WAIT_1)
998 memcpy(pkt.data, c->sndbuf, len);
999 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr + len);
1000 utcp->send(utcp, &pkt, sizeof pkt.hdr + len);
1010 * One call to this function will loop through all connections,
1011 * checking if something needs to be resent or not.
1012 * The return value is the time to the next timeout in milliseconds,
1013 * or maybe a negative value if the timeout is infinite.
1015 int utcp_timeout(struct utcp *utcp) {
1017 gettimeofday(&now, NULL);
1018 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1020 for(int i = 0; i < utcp->nconnections; i++) {
1021 struct utcp_connection *c = utcp->connections[i];
1025 if(c->state == CLOSED) {
1027 debug("Reaping %p\n", c);
1034 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1038 c->recv(c, NULL, 0);
1042 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1046 if(c->poll && c->sndbufsize < c->maxsndbufsize / 2)
1047 c->poll(c, c->maxsndbufsize - c->sndbufsize);
1049 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1050 next = c->conn_timeout;
1052 if(c->snd.nxt != c->snd.una) {
1053 c->rtrx_timeout = now;
1054 c->rtrx_timeout.tv_sec++;
1056 timerclear(&c->rtrx_timeout);
1059 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1060 next = c->rtrx_timeout;
1063 struct timeval diff;
1064 timersub(&next, &now, &diff);
1067 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
1070 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1071 struct utcp *utcp = calloc(1, sizeof *utcp);
1080 utcp->accept = accept;
1081 utcp->pre_accept = pre_accept;
1090 void utcp_exit(struct utcp *utcp) {
1093 for(int i = 0; i < utcp->nconnections; i++) {
1094 if(!utcp->connections[i]->reapable)
1095 debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1096 free(utcp->connections[i]->sndbuf);
1097 free(utcp->connections[i]);
1099 free(utcp->connections);
1103 uint16_t utcp_get_mtu(struct utcp *utcp) {
1107 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1108 // TODO: handle overhead of the header
1112 int utcp_get_user_timeout(struct utcp *u) {
1116 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1117 u->timeout = timeout;
1120 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1121 return c->maxsndbufsize;
1124 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1125 return c->maxsndbufsize - c->sndbufsize;
1128 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1129 c->maxsndbufsize = size;
1130 if(c->maxsndbufsize != size)
1131 c->maxsndbufsize = -1;
1134 bool utcp_get_nodelay(struct utcp_connection *c) {
1138 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1139 c->nodelay = nodelay;
1142 bool utcp_get_keepalive(struct utcp_connection *c) {
1143 return c->keepalive;
1146 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1147 c->keepalive = keepalive;
1150 size_t utcp_get_outq(struct utcp_connection *c) {
1151 return seqdiff(c->snd.nxt, c->snd.una);
1154 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1158 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {