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.
30 #include <sys/socket.h>
32 #include "utcp_priv.h"
37 static void debug(const char *format, ...) {
40 vfprintf(stderr, format, ap);
44 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
46 if(len < sizeof hdr) {
47 debug("%p %s: short packet (%zu bytes)\n", utcp, dir, len);
51 memcpy(&hdr, pkt, sizeof hdr);
52 fprintf (stderr, "%p %s: src=%u dst=%u seq=%u ack=%u wnd=%u ctl=", utcp, dir, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd);
62 if(len > sizeof hdr) {
64 for(int i = sizeof hdr; i < len; i++) {
65 const char *data = pkt;
66 debug("%c", data[i] >= 32 ? data[i] : '.');
74 #define print_packet(...)
77 static void set_state(struct utcp_connection *c, enum state state) {
79 if(state == ESTABLISHED)
80 timerclear(&c->conn_timeout);
81 debug("%p new state: %s\n", c->utcp, strstate[state]);
84 static inline void list_connections(struct utcp *utcp) {
85 debug("%p has %d connections:\n", utcp, utcp->nconnections);
86 for(int i = 0; i < utcp->nconnections; i++)
87 debug(" %u -> %u state %s\n", utcp->connections[i]->src, utcp->connections[i]->dst, strstate[utcp->connections[i]->state]);
90 static int32_t seqdiff(uint32_t a, uint32_t b) {
94 // Connections are stored in a sorted list.
95 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
97 static int compare(const void *va, const void *vb) {
98 const struct utcp_connection *a = *(struct utcp_connection **)va;
99 const struct utcp_connection *b = *(struct utcp_connection **)vb;
100 if(!a->src || !b->src)
102 int c = (int)a->src - (int)b->src;
105 c = (int)a->dst - (int)b->dst;
109 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
110 if(!utcp->nconnections)
112 struct utcp_connection key = {
116 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
117 return match ? *match : NULL;
120 static void free_connection(struct utcp_connection *c) {
121 struct utcp *utcp = c->utcp;
122 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
126 int i = cp - utcp->connections;
127 memmove(cp + i, cp + i + 1, (utcp->nconnections - i - 1) * sizeof *cp);
128 utcp->nconnections--;
133 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
134 // Check whether this combination of src and dst is free
137 if(find_connection(utcp, src, dst)) {
141 } else { // If src == 0, generate a random port number with the high bit set
142 if(utcp->nconnections >= 32767) {
146 src = rand() | 0x8000;
147 while(find_connection(utcp, src, dst))
151 // Allocate memory for the new connection
153 if(utcp->nconnections >= utcp->nallocated) {
154 if(!utcp->nallocated)
155 utcp->nallocated = 4;
157 utcp->nallocated *= 2;
158 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
161 utcp->connections = new_array;
164 struct utcp_connection *c = calloc(1, sizeof *c);
168 c->sndbufsize = DEFAULT_SNDBUFSIZE;
169 c->maxsndbufsize = DEFAULT_MAXSNDBUFSIZE;
170 c->sndbuf = malloc(c->sndbufsize);
176 // Fill in the details
181 c->snd.una = c->snd.iss;
182 c->snd.nxt = c->snd.iss + 1;
183 c->rcv.wnd = utcp->mtu;
184 c->snd.last = c->snd.nxt;
185 c->snd.cwnd = utcp->mtu;
188 // Add it to the sorted list of connections
190 utcp->connections[utcp->nconnections++] = c;
191 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
196 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
197 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
207 hdr.seq = c->snd.iss;
210 hdr.wnd = c->rcv.wnd;
212 set_state(c, SYN_SENT);
214 print_packet(utcp, "send", &hdr, sizeof hdr);
215 utcp->send(utcp, &hdr, sizeof hdr);
217 gettimeofday(&c->conn_timeout, NULL);
218 c->conn_timeout.tv_sec += utcp->timeout;
223 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
224 if(c->reapable || c->state != SYN_RECEIVED) {
225 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
229 debug("%p accepted, %p %p\n", c, recv, priv);
232 set_state(c, ESTABLISHED);
235 static void ack(struct utcp_connection *c, bool sendatleastone) {
236 uint32_t left = seqdiff(c->snd.last, c->snd.nxt);
237 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
238 char *data = c->sndbuf + seqdiff(c->snd.nxt, c->snd.una);
246 if(!left && !sendatleastone)
251 char data[c->utcp->mtu];
254 pkt.hdr.src = c->src;
255 pkt.hdr.dst = c->dst;
256 pkt.hdr.ack = c->rcv.nxt;
257 pkt.hdr.wnd = c->snd.wnd;
261 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
262 pkt.hdr.seq = c->snd.nxt;
264 memcpy(pkt.data, data, seglen);
266 c->snd.nxt += seglen;
270 print_packet(c->utcp, "send", &pkt, sizeof pkt.hdr + seglen);
271 c->utcp->send(c->utcp, &pkt, sizeof pkt.hdr + seglen);
275 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
277 debug("Error: send() called on closed connection %p\n", c);
287 debug("Error: send() called on unconnected connection %p\n", c);
298 debug("Error: send() called on closing connection %p\n", c);
303 // Add data to send buffer
313 uint32_t bufused = seqdiff(c->snd.nxt, c->snd.una);
315 /* Check our send buffer.
316 * - If it's big enough, just put the data in there.
317 * - If not, decide whether to enlarge if possible.
318 * - Cap len so it doesn't overflow our buffer.
321 if(len > c->sndbufsize - bufused && c->sndbufsize < c->maxsndbufsize) {
323 if(c->sndbufsize > c->maxsndbufsize / 2)
324 newbufsize = c->maxsndbufsize;
326 newbufsize = c->sndbufsize * 2;
327 char *newbuf = realloc(c->sndbuf, newbufsize);
330 c->sndbufsize = newbufsize;
334 if(len > c->sndbufsize - bufused)
335 len = c->sndbufsize - bufused;
338 errno == EWOULDBLOCK;
342 memcpy(c->sndbuf + bufused, data, len);
349 static void swap_ports(struct hdr *hdr) {
350 uint16_t tmp = hdr->src;
355 int utcp_recv(struct utcp *utcp, const void *data, size_t len) {
369 print_packet(utcp, "recv", data, len);
371 // Drop packets smaller than the header
374 if(len < sizeof hdr) {
379 // Make a copy from the potentially unaligned data to a struct hdr
381 memcpy(&hdr, data, sizeof hdr);
385 // Drop packets with an unknown CTL flag
387 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
392 // Try to match the packet to an existing connection
394 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
396 // Is it for a new connection?
399 // Ignore RST packets
404 // Is it a SYN packet and are we LISTENing?
406 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
407 // If we don't want to accept it, send a RST back
408 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
413 // Try to allocate memory, otherwise send a RST back
414 c = allocate_connection(utcp, hdr.dst, hdr.src);
420 // Return SYN+ACK, go to SYN_RECEIVED state
421 c->snd.wnd = hdr.wnd;
422 c->rcv.irs = hdr.seq;
423 c->rcv.nxt = c->rcv.irs + 1;
424 set_state(c, SYN_RECEIVED);
428 hdr.ack = c->rcv.irs + 1;
429 hdr.seq = c->snd.iss;
431 print_packet(c->utcp, "send", &hdr, sizeof hdr);
432 utcp->send(utcp, &hdr, sizeof hdr);
434 // No, we don't want your packets, send a RST back
442 debug("%p state %s\n", c->utcp, strstate[c->state]);
444 // In case this is for a CLOSED connection, ignore the packet.
445 // TODO: make it so incoming packets can never match a CLOSED connection.
447 if(c->state == CLOSED)
450 // It is for an existing connection.
452 // 1. Drop invalid packets.
454 // 1a. Drop packets that should not happen in our current state.
471 // 1b. Drop packets with a sequence number not in our receive window.
475 if(c->state == SYN_SENT)
478 // TODO: handle packets overlapping c->rcv.nxt.
480 // Only use this when accepting out-of-order packets.
483 acceptable = hdr.seq == c->rcv.nxt;
485 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
488 // We don't accept data when the receive window is zero.
491 // Both start and end of packet must be within the receive window
492 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
493 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
495 if(c->state != SYN_SENT)
496 acceptable = hdr.seq == c->rcv.nxt;
500 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
501 // Ignore unacceptable RST packets.
504 // Otherwise, send an ACK back in the hope things improve.
508 c->snd.wnd = hdr.wnd; // TODO: move below
510 // 1c. Drop packets with an invalid ACK.
511 // ackno should not roll back, and it should also not be bigger than snd.nxt.
513 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
514 debug("Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
515 // Ignore unacceptable RST packets.
521 // 2. Handle RST packets
528 // The peer has refused our connection.
529 set_state(c, CLOSED);
530 errno = ECONNREFUSED;
537 // We haven't told the application about this connection yet. Silently delete.
546 // The peer has aborted our connection.
547 set_state(c, CLOSED);
557 // As far as the application is concerned, the connection has already been closed.
558 // If it has called utcp_close() already, we can immediately free this connection.
563 // Otherwise, immediately move to the CLOSED state.
564 set_state(c, CLOSED);
571 // 3. Advance snd.una
573 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
574 c->snd.una = hdr.ack;
577 debug("%p advanced %u\n", utcp, advanced);
578 // Make room in the send buffer.
579 // TODO: try to avoid memmoving too much. Circular buffer?
580 uint32_t left = seqdiff(c->snd.nxt, hdr.ack);
582 memmove(c->sndbuf, c->sndbuf + advanced, left);
584 c->snd.cwnd += utcp->mtu;
585 if(c->snd.cwnd > c->maxsndbufsize)
586 c->snd.cwnd = c->maxsndbufsize;
591 debug("Triplicate ACK\n");
600 timerclear(&c->conn_timeout); // It should be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
601 if(c->snd.una == c->snd.nxt)
602 timerclear(&c->rtrx_timeout);
605 // 5. Process SYN stuff
610 // This is a SYNACK. It should always have ACKed the SYN.
613 c->rcv.irs = hdr.seq;
614 c->rcv.nxt = hdr.seq;
615 set_state(c, ESTABLISHED);
616 // TODO: notify application of this somehow.
626 // Ehm, no. We should never receive a second SYN.
632 // SYN counts as one sequence number
636 // 6. Process new data
638 if(c->state == SYN_RECEIVED) {
639 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
643 // Are we still LISTENing?
645 utcp->accept(c, c->src);
647 if(c->state != ESTABLISHED) {
648 set_state(c, CLOSED);
658 // This should never happen.
668 // Ehm no, We should never receive more data after a FIN.
677 rxd = c->recv(c, data, len);
681 rxd = len; // Bad application, bad!
689 // 7. Process FIN stuff
695 // This should never happen.
698 set_state(c, CLOSE_WAIT);
701 set_state(c, CLOSING);
704 set_state(c, TIME_WAIT);
710 // Ehm, no. We should never receive a second FIN.
716 // FIN counts as one sequence number
719 // Inform the application that the peer closed the connection.
726 if(!len && !advanced)
729 if(!len && !(hdr.ctl & SYN) && !(hdr.ctl & FIN))
743 hdr.ack = hdr.seq + len;
747 print_packet(utcp, "send", &hdr, sizeof hdr);
748 utcp->send(utcp, &hdr, sizeof hdr);
753 int utcp_shutdown(struct utcp_connection *c, int dir) {
754 debug("%p shutdown %d\n", c->utcp, dir);
761 debug("Error: shutdown() called on closed connection %p\n", c);
773 set_state(c, CLOSED);
778 set_state(c, FIN_WAIT_1);
784 set_state(c, CLOSING);
799 hdr.seq = c->snd.nxt;
800 hdr.ack = c->rcv.nxt;
801 hdr.wnd = c->snd.wnd;
806 print_packet(c->utcp, "send", &hdr, sizeof hdr);
807 c->utcp->send(c->utcp, &hdr, sizeof hdr);
811 int utcp_close(struct utcp_connection *c) {
812 if(utcp_shutdown(c, SHUT_RDWR))
818 int utcp_abort(struct utcp_connection *c) {
825 debug("Error: abort() called on closed connection %p\n", c);
840 set_state(c, CLOSED);
848 set_state(c, CLOSED);
858 hdr.seq = c->snd.nxt;
863 print_packet(c->utcp, "send", &hdr, sizeof hdr);
864 c->utcp->send(c->utcp, &hdr, sizeof hdr);
868 static void retransmit(struct utcp_connection *c) {
869 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
872 struct utcp *utcp = c->utcp;
876 char data[c->utcp->mtu];
879 pkt.hdr.src = c->src;
880 pkt.hdr.dst = c->dst;
884 // TODO: this should not happen
888 pkt.hdr.seq = c->snd.iss;
890 pkt.hdr.wnd = c->rcv.wnd;
892 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
893 utcp->send(utcp, &pkt, sizeof pkt.hdr);
897 pkt.hdr.seq = c->snd.nxt;
898 pkt.hdr.ack = c->rcv.nxt;
899 pkt.hdr.ctl = SYN | ACK;
900 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
901 utcp->send(utcp, &pkt, sizeof pkt.hdr);
906 pkt.hdr.seq = c->snd.una;
907 pkt.hdr.ack = c->rcv.nxt;
909 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
910 if(c->state == FIN_WAIT_1)
915 if(c->state == FIN_WAIT_1)
918 memcpy(pkt.data, c->sndbuf, len);
919 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr + len);
920 utcp->send(utcp, &pkt, sizeof pkt.hdr + len);
930 * One call to this function will loop through all connections,
931 * checking if something needs to be resent or not.
932 * The return value is the time to the next timeout in milliseconds,
933 * or maybe a negative value if the timeout is infinite.
935 int utcp_timeout(struct utcp *utcp) {
937 gettimeofday(&now, NULL);
938 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
940 for(int i = 0; i < utcp->nconnections; i++) {
941 struct utcp_connection *c = utcp->connections[i];
945 if(c->state == CLOSED) {
947 debug("Reaping %p\n", c);
954 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
962 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
966 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
967 next = c->conn_timeout;
969 if(c->snd.nxt != c->snd.una) {
970 c->rtrx_timeout = now;
971 c->rtrx_timeout.tv_sec++;
973 timerclear(&c->rtrx_timeout);
976 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
977 next = c->rtrx_timeout;
981 timersub(&next, &now, &diff);
984 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
987 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
988 struct utcp *utcp = calloc(1, sizeof *utcp);
997 utcp->accept = accept;
998 utcp->pre_accept = pre_accept;
1007 void utcp_exit(struct utcp *utcp) {
1010 for(int i = 0; i < utcp->nconnections; i++)
1011 free_connection(utcp->connections[i]);
1015 uint16_t utcp_get_mtu(struct utcp *utcp) {
1019 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1020 // TODO: handle overhead of the header
1024 int utcp_get_user_timeout(struct utcp *u) {
1028 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1029 u->timeout = timeout;
1032 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1033 return c->maxsndbufsize;
1036 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1037 c->maxsndbufsize = size;
1038 if(c->maxsndbufsize != size)
1039 c->maxsndbufsize = -1;
1042 bool utcp_get_nodelay(struct utcp_connection *c) {
1046 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1047 c->nodelay = nodelay;
1050 bool utcp_get_keepalive(struct utcp_connection *c) {
1051 return c->keepalive;
1054 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1055 c->keepalive = keepalive;
1058 size_t utcp_get_outq(struct utcp_connection *c) {
1059 return seqdiff(c->snd.nxt, c->snd.una);