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>
35 #define PREP(l) char pkt[(l) + sizeof struct hdr]; struct hdr *hdr = &pkt;
43 uint16_t src; // Source port
44 uint16_t dst; // Destination port
45 uint32_t seq; // Sequence number
46 uint32_t ack; // Acknowledgement number
47 uint32_t wnd; // Window size
48 uint16_t ctl; // Flags (SYN, ACK, FIN, RST)
49 uint16_t aux; // other stuff
66 const char *strstate[] = {
80 struct utcp_connection {
89 // The following two structures form the TCB
106 struct timeval conn_timeout;
107 struct timeval rtrx_timeout;
116 utcp_accept_t accept;
117 utcp_pre_accept_t pre_accept;
123 struct utcp_connection **connections;
128 static void set_state(struct utcp_connection *c, enum state state) {
130 if(state == ESTABLISHED)
131 timerclear(&c->conn_timeout);
132 fprintf(stderr, "%p new state: %s\n", c->utcp, strstate[state]);
135 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
137 if(len < sizeof hdr) {
138 fprintf(stderr, "%p %s: short packet (%zu bytes)\n", utcp, dir, len);
142 memcpy(&hdr, pkt, sizeof hdr);
143 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);
145 fprintf(stderr, "SYN");
147 fprintf(stderr, "RST");
149 fprintf(stderr, "FIN");
151 fprintf(stderr, "ACK");
153 if(len > sizeof hdr) {
154 fprintf(stderr, " data=");
155 for(int i = sizeof hdr; i < len; i++) {
156 const char *data = pkt;
157 fprintf(stderr, "%c", data[i] >= 32 ? data[i] : '.');
161 fprintf(stderr, "\n");
164 static inline void list_connections(struct utcp *utcp) {
165 fprintf(stderr, "%p has %d connections:\n", utcp, utcp->nconnections);
166 for(int i = 0; i < utcp->nconnections; i++)
167 fprintf(stderr, " %u -> %u state %s\n", utcp->connections[i]->src, utcp->connections[i]->dst, strstate[utcp->connections[i]->state]);
170 // Connections are stored in a sorted list.
171 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
173 static int compare(const void *va, const void *vb) {
174 const struct utcp_connection *a = *(struct utcp_connection **)va;
175 const struct utcp_connection *b = *(struct utcp_connection **)vb;
176 if(!a->src || !b->src)
178 int c = (int)a->src - (int)b->src;
181 c = (int)a->dst - (int)b->dst;
185 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
186 if(!utcp->nconnections)
188 struct utcp_connection key = {
192 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
193 return match ? *match : NULL;
196 static void free_connection(struct utcp_connection *c) {
197 struct utcp *utcp = c->utcp;
198 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
202 int i = cp - utcp->connections;
203 memmove(cp + i, cp + i + 1, (utcp->nconnections - i - 1) * sizeof *cp);
204 utcp->nconnections--;
209 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
210 // Check whether this combination of src and dst is free
213 if(find_connection(utcp, src, dst)) {
217 } else { // If src == 0, generate a random port number with the high bit set
218 if(utcp->nconnections >= 32767) {
222 src = rand() | 0x8000;
223 while(find_connection(utcp, src, dst))
227 // Allocate memory for the new connection
229 if(utcp->nconnections >= utcp->nallocated) {
230 if(!utcp->nallocated)
231 utcp->nallocated = 4;
233 utcp->nallocated *= 2;
234 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
239 utcp->connections = new_array;
242 struct utcp_connection *c = calloc(1, sizeof *c);
248 // Fill in the details
253 c->snd.una = c->snd.iss;
254 c->snd.nxt = c->snd.iss + 1;
255 c->rcv.wnd = utcp->mtu;
257 c->sndbufsize = 65536;
258 c->sndbuf = malloc(c->sndbufsize);
262 // Add it to the sorted list of connections
264 utcp->connections[utcp->nconnections++] = c;
265 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
270 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
271 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
281 hdr.seq = c->snd.iss;
284 hdr.wnd = c->rcv.wnd;
286 set_state(c, SYN_SENT);
288 print_packet(utcp, "send", &hdr, sizeof hdr);
289 utcp->send(utcp, &hdr, sizeof hdr);
291 gettimeofday(&c->conn_timeout, NULL);
292 c->conn_timeout.tv_sec += utcp->timeout;
297 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
298 if(c->reapable || c->state != SYN_RECEIVED) {
299 fprintf(stderr, "Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
303 fprintf(stderr, "%p accepted, %p %p\n", c, recv, priv);
306 set_state(c, ESTABLISHED);
309 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
311 fprintf(stderr, "Error: send() called on closed connection %p\n", c);
321 fprintf(stderr, "Error: send() called on unconnected connection %p\n", c);
332 fprintf(stderr, "Error: send() called on closing connection %p\n", c);
337 // Add data to send buffer
347 uint32_t bufused = c->snd.nxt - c->snd.una;
349 if(len > c->sndbufsize - bufused)
350 len = c->sndbufsize - bufused;
352 memcpy(c->sndbuf + (c->snd.nxt - c->snd.una), data, len);
358 char data[c->utcp->mtu];
361 pkt.hdr.src = c->src;
362 pkt.hdr.dst = c->dst;
363 pkt.hdr.ack = c->rcv.nxt;
364 pkt.hdr.wnd = c->snd.wnd;
370 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
371 pkt.hdr.seq = c->snd.nxt;
373 memcpy(pkt.data, data, seglen);
375 c->snd.nxt += seglen;
379 print_packet(c->utcp, "send", &pkt, sizeof pkt.hdr + seglen);
380 c->utcp->send(c->utcp, &pkt, sizeof pkt.hdr + seglen);
383 fprintf(stderr, "len=%zu\n", len);
387 static void swap_ports(struct hdr *hdr) {
388 uint16_t tmp = hdr->src;
393 static int32_t seqdiff(uint32_t a, uint32_t b) {
397 int utcp_recv(struct utcp *utcp, const void *data, size_t len) {
411 print_packet(utcp, "recv", data, len);
413 // Drop packets smaller than the header
416 if(len < sizeof hdr) {
421 // Make a copy from the potentially unaligned data to a struct hdr
423 memcpy(&hdr, data, sizeof hdr);
427 // Drop packets with an unknown CTL flag
429 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
434 // Try to match the packet to an existing connection
436 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
438 // Is it for a new connection?
441 // Ignore RST packets
446 // Is it a SYN packet and are we LISTENing?
448 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
449 // If we don't want to accept it, send a RST back
450 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
455 // Try to allocate memory, otherwise send a RST back
456 c = allocate_connection(utcp, hdr.dst, hdr.src);
462 // Return SYN+ACK, go to SYN_RECEIVED state
463 c->snd.wnd = hdr.wnd;
464 c->rcv.irs = hdr.seq;
465 c->rcv.nxt = c->rcv.irs + 1;
466 set_state(c, SYN_RECEIVED);
470 hdr.ack = c->rcv.irs + 1;
471 hdr.seq = c->snd.iss;
473 print_packet(c->utcp, "send", &hdr, sizeof hdr);
474 utcp->send(utcp, &hdr, sizeof hdr);
476 // No, we don't want your packets, send a RST back
484 fprintf(stderr, "%p state %s\n", c->utcp, strstate[c->state]);
486 // In case this is for a CLOSED connection, ignore the packet.
487 // TODO: make it so incoming packets can never match a CLOSED connection.
489 if(c->state == CLOSED)
492 // It is for an existing connection.
494 // 1. Drop invalid packets.
496 // 1a. Drop packets that should not happen in our current state.
513 // 1b. Drop packets with a sequence number not in our receive window.
517 if(c->state == SYN_SENT)
520 // TODO: handle packets overlapping c->rcv.nxt.
522 // Only use this when accepting out-of-order packets.
525 acceptable = hdr.seq == c->rcv.nxt;
527 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
530 // We don't accept data when the receive window is zero.
533 // Both start and end of packet must be within the receive window
534 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
535 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
537 if(c->state != SYN_SENT)
538 acceptable = hdr.seq == c->rcv.nxt;
542 fprintf(stderr, "Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
543 // Ignore unacceptable RST packets.
546 // Otherwise, send an ACK back in the hope things improve.
550 c->snd.wnd = hdr.wnd; // TODO: move below
552 // 1c. Drop packets with an invalid ACK.
553 // ackno should not roll back, and it should also not be bigger than snd.nxt.
555 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
556 fprintf(stderr, "Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
557 // Ignore unacceptable RST packets.
563 // 2. Handle RST packets
570 // The peer has refused our connection.
571 set_state(c, CLOSED);
572 errno = ECONNREFUSED;
579 // We haven't told the application about this connection yet. Silently delete.
588 // The peer has aborted our connection.
589 set_state(c, CLOSED);
599 // As far as the application is concerned, the connection has already been closed.
600 // If it has called utcp_close() already, we can immediately free this connection.
605 // Otherwise, immediately move to the CLOSED state.
606 set_state(c, CLOSED);
613 // 3. Advance snd.una
615 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
616 c->snd.una = hdr.ack;
619 fprintf(stderr, "%p advanced %u\n", utcp, advanced);
620 // Make room in the send buffer.
621 // TODO: try to avoid memmoving too much. Circular buffer?
622 uint32_t left = seqdiff(c->snd.nxt, hdr.ack);
624 memmove(c->sndbuf, c->sndbuf + advanced, left);
630 timerclear(&c->conn_timeout); // It should be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
631 if(c->snd.una == c->snd.nxt)
632 timerclear(&c->rtrx_timeout);
635 // 5. Process SYN stuff
640 // This is a SYNACK. It should always have ACKed the SYN.
643 c->rcv.irs = hdr.seq;
644 c->rcv.nxt = hdr.seq;
645 set_state(c, ESTABLISHED);
646 // TODO: notify application of this somehow.
656 // Ehm, no. We should never receive a second SYN.
662 // SYN counts as one sequence number
666 // 6. Process new data
668 if(c->state == SYN_RECEIVED) {
669 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
673 // Are we still LISTENing?
675 utcp->accept(c, c->src);
677 if(c->state != ESTABLISHED) {
678 set_state(c, CLOSED);
688 // This should never happen.
698 // Ehm no, We should never receive more data after a FIN.
707 rxd = c->recv(c, data, len);
711 rxd = len; // Bad application, bad!
719 // 7. Process FIN stuff
725 // This should never happen.
728 set_state(c, CLOSE_WAIT);
731 set_state(c, CLOSING);
734 set_state(c, TIME_WAIT);
740 // Ehm, no. We should never receive a second FIN.
746 // FIN counts as one sequence number
749 // Inform the application that the peer closed the connection.
756 if(!len && !advanced)
759 if(!len && !(hdr.ctl & SYN) && !(hdr.ctl & FIN))
765 hdr.seq = c->snd.nxt;
766 hdr.ack = c->rcv.nxt;
768 print_packet(c->utcp, "send", &hdr, sizeof hdr);
769 utcp->send(utcp, &hdr, sizeof hdr);
779 hdr.ack = hdr.seq + len;
783 print_packet(utcp, "send", &hdr, sizeof hdr);
784 utcp->send(utcp, &hdr, sizeof hdr);
789 int utcp_shutdown(struct utcp_connection *c, int dir) {
790 fprintf(stderr, "%p shutdown %d\n", c->utcp, dir);
797 fprintf(stderr, "Error: shutdown() called on closed connection %p\n", c);
809 set_state(c, CLOSED);
814 set_state(c, FIN_WAIT_1);
820 set_state(c, CLOSING);
835 hdr.seq = c->snd.nxt;
836 hdr.ack = c->rcv.nxt;
837 hdr.wnd = c->snd.wnd;
842 print_packet(c->utcp, "send", &hdr, sizeof hdr);
843 c->utcp->send(c->utcp, &hdr, sizeof hdr);
847 int utcp_close(struct utcp_connection *c) {
848 if(utcp_shutdown(c, SHUT_RDWR))
854 int utcp_abort(struct utcp_connection *c) {
861 fprintf(stderr, "Error: abort() called on closed connection %p\n", c);
876 set_state(c, CLOSED);
884 set_state(c, CLOSED);
894 hdr.seq = c->snd.nxt;
899 print_packet(c->utcp, "send", &hdr, sizeof hdr);
900 c->utcp->send(c->utcp, &hdr, sizeof hdr);
904 static void retransmit(struct utcp_connection *c) {
905 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
908 struct utcp *utcp = c->utcp;
912 char data[c->utcp->mtu];
915 pkt.hdr.src = c->src;
916 pkt.hdr.dst = c->dst;
920 // TODO: this should not happen
924 pkt.hdr.seq = c->snd.iss;
926 pkt.hdr.wnd = c->rcv.wnd;
928 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
929 utcp->send(utcp, &pkt, sizeof pkt.hdr);
933 pkt.hdr.seq = c->snd.nxt;
934 pkt.hdr.ack = c->rcv.nxt;
935 pkt.hdr.ctl = SYN | ACK;
936 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
937 utcp->send(utcp, &pkt, sizeof pkt.hdr);
941 pkt.hdr.seq = c->snd.una;
942 pkt.hdr.ack = c->rcv.nxt;
944 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
947 memcpy(pkt.data, c->sndbuf, len);
948 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr + len);
949 utcp->send(utcp, &pkt, sizeof pkt.hdr + len);
959 * One call to this function will loop through all connections,
960 * checking if something needs to be resent or not.
961 * The return value is the time to the next timeout in milliseconds,
962 * or maybe a negative value if the timeout is infinite.
964 int utcp_timeout(struct utcp *utcp) {
966 gettimeofday(&now, NULL);
967 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
969 for(int i = 0; i < utcp->nconnections; i++) {
970 struct utcp_connection *c = utcp->connections[i];
974 if(c->state == CLOSED) {
976 fprintf(stderr, "Reaping %p\n", c);
983 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
991 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
995 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
996 next = c->conn_timeout;
998 if(c->snd.nxt != c->snd.una) {
999 c->rtrx_timeout = now;
1000 c->rtrx_timeout.tv_sec++;
1002 timerclear(&c->rtrx_timeout);
1005 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1006 next = c->rtrx_timeout;
1009 struct timeval diff;
1010 timersub(&next, &now, &diff);
1013 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
1016 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1017 struct utcp *utcp = calloc(1, sizeof *utcp);
1026 utcp->accept = accept;
1027 utcp->pre_accept = pre_accept;
1036 void utcp_exit(struct utcp *utcp) {
1039 for(int i = 0; i < utcp->nconnections; i++)
1040 free_connection(utcp->connections[i]);
1044 int utcp_set_connection_timeout(struct utcp *u, int timeout) {
1045 int prev = u->timeout;
1046 u->timeout = timeout;