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"
34 static void set_state(struct utcp_connection *c, enum state state) {
36 if(state == ESTABLISHED)
37 timerclear(&c->conn_timeout);
38 fprintf(stderr, "%p new state: %s\n", c->utcp, strstate[state]);
41 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
43 if(len < sizeof hdr) {
44 fprintf(stderr, "%p %s: short packet (%zu bytes)\n", utcp, dir, len);
48 memcpy(&hdr, pkt, sizeof hdr);
49 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);
51 fprintf(stderr, "SYN");
53 fprintf(stderr, "RST");
55 fprintf(stderr, "FIN");
57 fprintf(stderr, "ACK");
59 if(len > sizeof hdr) {
60 fprintf(stderr, " data=");
61 for(int i = sizeof hdr; i < len; i++) {
62 const char *data = pkt;
63 fprintf(stderr, "%c", data[i] >= 32 ? data[i] : '.');
67 fprintf(stderr, "\n");
70 static inline void list_connections(struct utcp *utcp) {
71 fprintf(stderr, "%p has %d connections:\n", utcp, utcp->nconnections);
72 for(int i = 0; i < utcp->nconnections; i++)
73 fprintf(stderr, " %u -> %u state %s\n", utcp->connections[i]->src, utcp->connections[i]->dst, strstate[utcp->connections[i]->state]);
76 static int32_t seqdiff(uint32_t a, uint32_t b) {
80 // Connections are stored in a sorted list.
81 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
83 static int compare(const void *va, const void *vb) {
84 const struct utcp_connection *a = *(struct utcp_connection **)va;
85 const struct utcp_connection *b = *(struct utcp_connection **)vb;
86 if(!a->src || !b->src)
88 int c = (int)a->src - (int)b->src;
91 c = (int)a->dst - (int)b->dst;
95 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
96 if(!utcp->nconnections)
98 struct utcp_connection key = {
102 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
103 return match ? *match : NULL;
106 static void free_connection(struct utcp_connection *c) {
107 struct utcp *utcp = c->utcp;
108 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
112 int i = cp - utcp->connections;
113 memmove(cp + i, cp + i + 1, (utcp->nconnections - i - 1) * sizeof *cp);
114 utcp->nconnections--;
119 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
120 // Check whether this combination of src and dst is free
123 if(find_connection(utcp, src, dst)) {
127 } else { // If src == 0, generate a random port number with the high bit set
128 if(utcp->nconnections >= 32767) {
132 src = rand() | 0x8000;
133 while(find_connection(utcp, src, dst))
137 // Allocate memory for the new connection
139 if(utcp->nconnections >= utcp->nallocated) {
140 if(!utcp->nallocated)
141 utcp->nallocated = 4;
143 utcp->nallocated *= 2;
144 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
147 utcp->connections = new_array;
150 struct utcp_connection *c = calloc(1, sizeof *c);
154 c->sndbufsize = DEFAULT_SNDBUFSIZE;
155 c->maxsndbufsize = DEFAULT_MAXSNDBUFSIZE;
156 c->sndbuf = malloc(c->sndbufsize);
162 // Fill in the details
167 c->snd.una = c->snd.iss;
168 c->snd.nxt = c->snd.iss + 1;
169 c->rcv.wnd = utcp->mtu;
172 // Add it to the sorted list of connections
174 utcp->connections[utcp->nconnections++] = c;
175 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
180 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
181 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
191 hdr.seq = c->snd.iss;
194 hdr.wnd = c->rcv.wnd;
196 set_state(c, SYN_SENT);
198 print_packet(utcp, "send", &hdr, sizeof hdr);
199 utcp->send(utcp, &hdr, sizeof hdr);
201 gettimeofday(&c->conn_timeout, NULL);
202 c->conn_timeout.tv_sec += utcp->timeout;
207 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
208 if(c->reapable || c->state != SYN_RECEIVED) {
209 fprintf(stderr, "Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
213 fprintf(stderr, "%p accepted, %p %p\n", c, recv, priv);
216 set_state(c, ESTABLISHED);
219 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
221 fprintf(stderr, "Error: send() called on closed connection %p\n", c);
231 fprintf(stderr, "Error: send() called on unconnected connection %p\n", c);
242 fprintf(stderr, "Error: send() called on closing connection %p\n", c);
247 // Add data to send buffer
257 uint32_t bufused = seqdiff(c->snd.nxt, c->snd.una);
259 /* Check our send buffer.
260 * - If it's big enough, just put the data in there.
261 * - If not, decide whether to enlarge if possible.
262 * - Cap len so it doesn't overflow our buffer.
265 if(len > c->sndbufsize - bufused && c->sndbufsize < c->maxsndbufsize) {
266 if(c->sndbufsize > c->maxsndbufsize / 2)
267 c->sndbufsize = c->maxsndbufsize;
270 c->sndbuf = realloc(c->sndbuf, c->sndbufsize);
273 if(len > c->sndbufsize - bufused)
274 len = c->sndbufsize - bufused;
277 errno == EWOULDBLOCK;
281 memcpy(c->sndbuf + bufused, data, len);
287 char data[c->utcp->mtu];
290 pkt.hdr.src = c->src;
291 pkt.hdr.dst = c->dst;
292 pkt.hdr.ack = c->rcv.nxt;
293 pkt.hdr.wnd = c->snd.wnd;
299 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
300 pkt.hdr.seq = c->snd.nxt;
302 memcpy(pkt.data, data, seglen);
304 c->snd.nxt += seglen;
308 print_packet(c->utcp, "send", &pkt, sizeof pkt.hdr + seglen);
309 c->utcp->send(c->utcp, &pkt, sizeof pkt.hdr + seglen);
312 fprintf(stderr, "len=%zu\n", len);
316 static void swap_ports(struct hdr *hdr) {
317 uint16_t tmp = hdr->src;
322 int utcp_recv(struct utcp *utcp, const void *data, size_t len) {
336 print_packet(utcp, "recv", data, len);
338 // Drop packets smaller than the header
341 if(len < sizeof hdr) {
346 // Make a copy from the potentially unaligned data to a struct hdr
348 memcpy(&hdr, data, sizeof hdr);
352 // Drop packets with an unknown CTL flag
354 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
359 // Try to match the packet to an existing connection
361 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
363 // Is it for a new connection?
366 // Ignore RST packets
371 // Is it a SYN packet and are we LISTENing?
373 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
374 // If we don't want to accept it, send a RST back
375 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
380 // Try to allocate memory, otherwise send a RST back
381 c = allocate_connection(utcp, hdr.dst, hdr.src);
387 // Return SYN+ACK, go to SYN_RECEIVED state
388 c->snd.wnd = hdr.wnd;
389 c->rcv.irs = hdr.seq;
390 c->rcv.nxt = c->rcv.irs + 1;
391 set_state(c, SYN_RECEIVED);
395 hdr.ack = c->rcv.irs + 1;
396 hdr.seq = c->snd.iss;
398 print_packet(c->utcp, "send", &hdr, sizeof hdr);
399 utcp->send(utcp, &hdr, sizeof hdr);
401 // No, we don't want your packets, send a RST back
409 fprintf(stderr, "%p state %s\n", c->utcp, strstate[c->state]);
411 // In case this is for a CLOSED connection, ignore the packet.
412 // TODO: make it so incoming packets can never match a CLOSED connection.
414 if(c->state == CLOSED)
417 // It is for an existing connection.
419 // 1. Drop invalid packets.
421 // 1a. Drop packets that should not happen in our current state.
438 // 1b. Drop packets with a sequence number not in our receive window.
442 if(c->state == SYN_SENT)
445 // TODO: handle packets overlapping c->rcv.nxt.
447 // Only use this when accepting out-of-order packets.
450 acceptable = hdr.seq == c->rcv.nxt;
452 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
455 // We don't accept data when the receive window is zero.
458 // Both start and end of packet must be within the receive window
459 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
460 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
462 if(c->state != SYN_SENT)
463 acceptable = hdr.seq == c->rcv.nxt;
467 fprintf(stderr, "Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
468 // Ignore unacceptable RST packets.
471 // Otherwise, send an ACK back in the hope things improve.
475 c->snd.wnd = hdr.wnd; // TODO: move below
477 // 1c. Drop packets with an invalid ACK.
478 // ackno should not roll back, and it should also not be bigger than snd.nxt.
480 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
481 fprintf(stderr, "Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
482 // Ignore unacceptable RST packets.
488 // 2. Handle RST packets
495 // The peer has refused our connection.
496 set_state(c, CLOSED);
497 errno = ECONNREFUSED;
504 // We haven't told the application about this connection yet. Silently delete.
513 // The peer has aborted our connection.
514 set_state(c, CLOSED);
524 // As far as the application is concerned, the connection has already been closed.
525 // If it has called utcp_close() already, we can immediately free this connection.
530 // Otherwise, immediately move to the CLOSED state.
531 set_state(c, CLOSED);
538 // 3. Advance snd.una
540 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
541 c->snd.una = hdr.ack;
544 fprintf(stderr, "%p advanced %u\n", utcp, advanced);
545 // Make room in the send buffer.
546 // TODO: try to avoid memmoving too much. Circular buffer?
547 uint32_t left = seqdiff(c->snd.nxt, hdr.ack);
549 memmove(c->sndbuf, c->sndbuf + advanced, left);
555 timerclear(&c->conn_timeout); // It should be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
556 if(c->snd.una == c->snd.nxt)
557 timerclear(&c->rtrx_timeout);
560 // 5. Process SYN stuff
565 // This is a SYNACK. It should always have ACKed the SYN.
568 c->rcv.irs = hdr.seq;
569 c->rcv.nxt = hdr.seq;
570 set_state(c, ESTABLISHED);
571 // TODO: notify application of this somehow.
581 // Ehm, no. We should never receive a second SYN.
587 // SYN counts as one sequence number
591 // 6. Process new data
593 if(c->state == SYN_RECEIVED) {
594 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
598 // Are we still LISTENing?
600 utcp->accept(c, c->src);
602 if(c->state != ESTABLISHED) {
603 set_state(c, CLOSED);
613 // This should never happen.
623 // Ehm no, We should never receive more data after a FIN.
632 rxd = c->recv(c, data, len);
636 rxd = len; // Bad application, bad!
644 // 7. Process FIN stuff
650 // This should never happen.
653 set_state(c, CLOSE_WAIT);
656 set_state(c, CLOSING);
659 set_state(c, TIME_WAIT);
665 // Ehm, no. We should never receive a second FIN.
671 // FIN counts as one sequence number
674 // Inform the application that the peer closed the connection.
681 if(!len && !advanced)
684 if(!len && !(hdr.ctl & SYN) && !(hdr.ctl & FIN))
690 hdr.seq = c->snd.nxt;
691 hdr.ack = c->rcv.nxt;
693 print_packet(c->utcp, "send", &hdr, sizeof hdr);
694 utcp->send(utcp, &hdr, sizeof hdr);
704 hdr.ack = hdr.seq + len;
708 print_packet(utcp, "send", &hdr, sizeof hdr);
709 utcp->send(utcp, &hdr, sizeof hdr);
714 int utcp_shutdown(struct utcp_connection *c, int dir) {
715 fprintf(stderr, "%p shutdown %d\n", c->utcp, dir);
722 fprintf(stderr, "Error: shutdown() called on closed connection %p\n", c);
734 set_state(c, CLOSED);
739 set_state(c, FIN_WAIT_1);
745 set_state(c, CLOSING);
760 hdr.seq = c->snd.nxt;
761 hdr.ack = c->rcv.nxt;
762 hdr.wnd = c->snd.wnd;
767 print_packet(c->utcp, "send", &hdr, sizeof hdr);
768 c->utcp->send(c->utcp, &hdr, sizeof hdr);
772 int utcp_close(struct utcp_connection *c) {
773 if(utcp_shutdown(c, SHUT_RDWR))
779 int utcp_abort(struct utcp_connection *c) {
786 fprintf(stderr, "Error: abort() called on closed connection %p\n", c);
801 set_state(c, CLOSED);
809 set_state(c, CLOSED);
819 hdr.seq = c->snd.nxt;
824 print_packet(c->utcp, "send", &hdr, sizeof hdr);
825 c->utcp->send(c->utcp, &hdr, sizeof hdr);
829 static void retransmit(struct utcp_connection *c) {
830 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
833 struct utcp *utcp = c->utcp;
837 char data[c->utcp->mtu];
840 pkt.hdr.src = c->src;
841 pkt.hdr.dst = c->dst;
845 // TODO: this should not happen
849 pkt.hdr.seq = c->snd.iss;
851 pkt.hdr.wnd = c->rcv.wnd;
853 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
854 utcp->send(utcp, &pkt, sizeof pkt.hdr);
858 pkt.hdr.seq = c->snd.nxt;
859 pkt.hdr.ack = c->rcv.nxt;
860 pkt.hdr.ctl = SYN | ACK;
861 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
862 utcp->send(utcp, &pkt, sizeof pkt.hdr);
867 pkt.hdr.seq = c->snd.una;
868 pkt.hdr.ack = c->rcv.nxt;
870 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
871 if(c->state == FIN_WAIT_1)
876 if(c->state == FIN_WAIT_1)
879 memcpy(pkt.data, c->sndbuf, len);
880 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr + len);
881 utcp->send(utcp, &pkt, sizeof pkt.hdr + len);
891 * One call to this function will loop through all connections,
892 * checking if something needs to be resent or not.
893 * The return value is the time to the next timeout in milliseconds,
894 * or maybe a negative value if the timeout is infinite.
896 int utcp_timeout(struct utcp *utcp) {
898 gettimeofday(&now, NULL);
899 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
901 for(int i = 0; i < utcp->nconnections; i++) {
902 struct utcp_connection *c = utcp->connections[i];
906 if(c->state == CLOSED) {
908 fprintf(stderr, "Reaping %p\n", c);
915 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
923 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
927 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
928 next = c->conn_timeout;
930 if(c->snd.nxt != c->snd.una) {
931 c->rtrx_timeout = now;
932 c->rtrx_timeout.tv_sec++;
934 timerclear(&c->rtrx_timeout);
937 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
938 next = c->rtrx_timeout;
942 timersub(&next, &now, &diff);
945 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
948 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
949 struct utcp *utcp = calloc(1, sizeof *utcp);
958 utcp->accept = accept;
959 utcp->pre_accept = pre_accept;
968 void utcp_exit(struct utcp *utcp) {
971 for(int i = 0; i < utcp->nconnections; i++)
972 free_connection(utcp->connections[i]);
976 uint16_t utcp_get_mtu(struct utcp *utcp) {
980 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
981 // TODO: handle overhead of the header
985 int utcp_get_user_timeout(struct utcp *u) {
989 void utcp_set_user_timeout(struct utcp *u, int timeout) {
990 u->timeout = timeout;
993 size_t utcp_get_sndbuf(struct utcp_connection *c) {
994 return c->maxsndbufsize;
997 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
998 c->maxsndbufsize = size;
999 if(c->maxsndbufsize != size)
1000 c->maxsndbufsize = -1;
1003 bool utcp_get_nodelay(struct utcp_connection *c) {
1007 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1008 c->nodelay = nodelay;
1011 bool utcp_get_keepalive(struct utcp_connection *c) {
1012 return c->keepalive;
1015 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1016 c->keepalive = keepalive;
1019 size_t utcp_get_outq(struct utcp_connection *c) {
1020 return seqdiff(c->snd.nxt, c->snd.una);