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 /* Check our send buffer.
350 * - If it's big enough, just put the data in there.
351 * - If not, decide whether to enlarge. (TODO, now we just always enlarge)
352 * - Cap len so it doesn't overflow our buffer.
355 if(len > c->sndbufsize - bufused) {
357 c->sndbuf = realloc(c->sndbuf, c->sndbufsize);
360 if(len > c->sndbufsize - bufused)
361 len = c->sndbufsize - bufused;
364 errno == EWOULDBLOCK;
368 memcpy(c->sndbuf + bufused, data, len);
374 char data[c->utcp->mtu];
377 pkt.hdr.src = c->src;
378 pkt.hdr.dst = c->dst;
379 pkt.hdr.ack = c->rcv.nxt;
380 pkt.hdr.wnd = c->snd.wnd;
386 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
387 pkt.hdr.seq = c->snd.nxt;
389 memcpy(pkt.data, data, seglen);
391 c->snd.nxt += seglen;
395 print_packet(c->utcp, "send", &pkt, sizeof pkt.hdr + seglen);
396 c->utcp->send(c->utcp, &pkt, sizeof pkt.hdr + seglen);
399 fprintf(stderr, "len=%zu\n", len);
403 static void swap_ports(struct hdr *hdr) {
404 uint16_t tmp = hdr->src;
409 static int32_t seqdiff(uint32_t a, uint32_t b) {
413 int utcp_recv(struct utcp *utcp, const void *data, size_t len) {
427 print_packet(utcp, "recv", data, len);
429 // Drop packets smaller than the header
432 if(len < sizeof hdr) {
437 // Make a copy from the potentially unaligned data to a struct hdr
439 memcpy(&hdr, data, sizeof hdr);
443 // Drop packets with an unknown CTL flag
445 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
450 // Try to match the packet to an existing connection
452 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
454 // Is it for a new connection?
457 // Ignore RST packets
462 // Is it a SYN packet and are we LISTENing?
464 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
465 // If we don't want to accept it, send a RST back
466 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
471 // Try to allocate memory, otherwise send a RST back
472 c = allocate_connection(utcp, hdr.dst, hdr.src);
478 // Return SYN+ACK, go to SYN_RECEIVED state
479 c->snd.wnd = hdr.wnd;
480 c->rcv.irs = hdr.seq;
481 c->rcv.nxt = c->rcv.irs + 1;
482 set_state(c, SYN_RECEIVED);
486 hdr.ack = c->rcv.irs + 1;
487 hdr.seq = c->snd.iss;
489 print_packet(c->utcp, "send", &hdr, sizeof hdr);
490 utcp->send(utcp, &hdr, sizeof hdr);
492 // No, we don't want your packets, send a RST back
500 fprintf(stderr, "%p state %s\n", c->utcp, strstate[c->state]);
502 // In case this is for a CLOSED connection, ignore the packet.
503 // TODO: make it so incoming packets can never match a CLOSED connection.
505 if(c->state == CLOSED)
508 // It is for an existing connection.
510 // 1. Drop invalid packets.
512 // 1a. Drop packets that should not happen in our current state.
529 // 1b. Drop packets with a sequence number not in our receive window.
533 if(c->state == SYN_SENT)
536 // TODO: handle packets overlapping c->rcv.nxt.
538 // Only use this when accepting out-of-order packets.
541 acceptable = hdr.seq == c->rcv.nxt;
543 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
546 // We don't accept data when the receive window is zero.
549 // Both start and end of packet must be within the receive window
550 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
551 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
553 if(c->state != SYN_SENT)
554 acceptable = hdr.seq == c->rcv.nxt;
558 fprintf(stderr, "Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
559 // Ignore unacceptable RST packets.
562 // Otherwise, send an ACK back in the hope things improve.
566 c->snd.wnd = hdr.wnd; // TODO: move below
568 // 1c. Drop packets with an invalid ACK.
569 // ackno should not roll back, and it should also not be bigger than snd.nxt.
571 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
572 fprintf(stderr, "Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
573 // Ignore unacceptable RST packets.
579 // 2. Handle RST packets
586 // The peer has refused our connection.
587 set_state(c, CLOSED);
588 errno = ECONNREFUSED;
595 // We haven't told the application about this connection yet. Silently delete.
604 // The peer has aborted our connection.
605 set_state(c, CLOSED);
615 // As far as the application is concerned, the connection has already been closed.
616 // If it has called utcp_close() already, we can immediately free this connection.
621 // Otherwise, immediately move to the CLOSED state.
622 set_state(c, CLOSED);
629 // 3. Advance snd.una
631 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
632 c->snd.una = hdr.ack;
635 fprintf(stderr, "%p advanced %u\n", utcp, advanced);
636 // Make room in the send buffer.
637 // TODO: try to avoid memmoving too much. Circular buffer?
638 uint32_t left = seqdiff(c->snd.nxt, hdr.ack);
640 memmove(c->sndbuf, c->sndbuf + advanced, left);
646 timerclear(&c->conn_timeout); // It should be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
647 if(c->snd.una == c->snd.nxt)
648 timerclear(&c->rtrx_timeout);
651 // 5. Process SYN stuff
656 // This is a SYNACK. It should always have ACKed the SYN.
659 c->rcv.irs = hdr.seq;
660 c->rcv.nxt = hdr.seq;
661 set_state(c, ESTABLISHED);
662 // TODO: notify application of this somehow.
672 // Ehm, no. We should never receive a second SYN.
678 // SYN counts as one sequence number
682 // 6. Process new data
684 if(c->state == SYN_RECEIVED) {
685 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
689 // Are we still LISTENing?
691 utcp->accept(c, c->src);
693 if(c->state != ESTABLISHED) {
694 set_state(c, CLOSED);
704 // This should never happen.
714 // Ehm no, We should never receive more data after a FIN.
723 rxd = c->recv(c, data, len);
727 rxd = len; // Bad application, bad!
735 // 7. Process FIN stuff
741 // This should never happen.
744 set_state(c, CLOSE_WAIT);
747 set_state(c, CLOSING);
750 set_state(c, TIME_WAIT);
756 // Ehm, no. We should never receive a second FIN.
762 // FIN counts as one sequence number
765 // Inform the application that the peer closed the connection.
772 if(!len && !advanced)
775 if(!len && !(hdr.ctl & SYN) && !(hdr.ctl & FIN))
781 hdr.seq = c->snd.nxt;
782 hdr.ack = c->rcv.nxt;
784 print_packet(c->utcp, "send", &hdr, sizeof hdr);
785 utcp->send(utcp, &hdr, sizeof hdr);
795 hdr.ack = hdr.seq + len;
799 print_packet(utcp, "send", &hdr, sizeof hdr);
800 utcp->send(utcp, &hdr, sizeof hdr);
805 int utcp_shutdown(struct utcp_connection *c, int dir) {
806 fprintf(stderr, "%p shutdown %d\n", c->utcp, dir);
813 fprintf(stderr, "Error: shutdown() called on closed connection %p\n", c);
825 set_state(c, CLOSED);
830 set_state(c, FIN_WAIT_1);
836 set_state(c, CLOSING);
851 hdr.seq = c->snd.nxt;
852 hdr.ack = c->rcv.nxt;
853 hdr.wnd = c->snd.wnd;
858 print_packet(c->utcp, "send", &hdr, sizeof hdr);
859 c->utcp->send(c->utcp, &hdr, sizeof hdr);
863 int utcp_close(struct utcp_connection *c) {
864 if(utcp_shutdown(c, SHUT_RDWR))
870 int utcp_abort(struct utcp_connection *c) {
877 fprintf(stderr, "Error: abort() called on closed connection %p\n", c);
892 set_state(c, CLOSED);
900 set_state(c, CLOSED);
910 hdr.seq = c->snd.nxt;
915 print_packet(c->utcp, "send", &hdr, sizeof hdr);
916 c->utcp->send(c->utcp, &hdr, sizeof hdr);
920 static void retransmit(struct utcp_connection *c) {
921 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
924 struct utcp *utcp = c->utcp;
928 char data[c->utcp->mtu];
931 pkt.hdr.src = c->src;
932 pkt.hdr.dst = c->dst;
936 // TODO: this should not happen
940 pkt.hdr.seq = c->snd.iss;
942 pkt.hdr.wnd = c->rcv.wnd;
944 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
945 utcp->send(utcp, &pkt, sizeof pkt.hdr);
949 pkt.hdr.seq = c->snd.nxt;
950 pkt.hdr.ack = c->rcv.nxt;
951 pkt.hdr.ctl = SYN | ACK;
952 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
953 utcp->send(utcp, &pkt, sizeof pkt.hdr);
958 pkt.hdr.seq = c->snd.una;
959 pkt.hdr.ack = c->rcv.nxt;
961 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
962 if(c->state == FIN_WAIT_1)
967 if(c->state == FIN_WAIT_1)
970 memcpy(pkt.data, c->sndbuf, len);
971 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr + len);
972 utcp->send(utcp, &pkt, sizeof pkt.hdr + len);
982 * One call to this function will loop through all connections,
983 * checking if something needs to be resent or not.
984 * The return value is the time to the next timeout in milliseconds,
985 * or maybe a negative value if the timeout is infinite.
987 int utcp_timeout(struct utcp *utcp) {
989 gettimeofday(&now, NULL);
990 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
992 for(int i = 0; i < utcp->nconnections; i++) {
993 struct utcp_connection *c = utcp->connections[i];
997 if(c->state == CLOSED) {
999 fprintf(stderr, "Reaping %p\n", c);
1006 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1010 c->recv(c, NULL, 0);
1014 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1018 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1019 next = c->conn_timeout;
1021 if(c->snd.nxt != c->snd.una) {
1022 c->rtrx_timeout = now;
1023 c->rtrx_timeout.tv_sec++;
1025 timerclear(&c->rtrx_timeout);
1028 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1029 next = c->rtrx_timeout;
1032 struct timeval diff;
1033 timersub(&next, &now, &diff);
1036 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
1039 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1040 struct utcp *utcp = calloc(1, sizeof *utcp);
1049 utcp->accept = accept;
1050 utcp->pre_accept = pre_accept;
1059 void utcp_exit(struct utcp *utcp) {
1062 for(int i = 0; i < utcp->nconnections; i++)
1063 free_connection(utcp->connections[i]);
1067 int utcp_set_connection_timeout(struct utcp *u, int timeout) {
1068 int prev = u->timeout;
1069 u->timeout = timeout;