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 // Connections are stored in a sorted list.
77 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
79 static int compare(const void *va, const void *vb) {
80 const struct utcp_connection *a = *(struct utcp_connection **)va;
81 const struct utcp_connection *b = *(struct utcp_connection **)vb;
82 if(!a->src || !b->src)
84 int c = (int)a->src - (int)b->src;
87 c = (int)a->dst - (int)b->dst;
91 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
92 if(!utcp->nconnections)
94 struct utcp_connection key = {
98 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
99 return match ? *match : NULL;
102 static void free_connection(struct utcp_connection *c) {
103 struct utcp *utcp = c->utcp;
104 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
108 int i = cp - utcp->connections;
109 memmove(cp + i, cp + i + 1, (utcp->nconnections - i - 1) * sizeof *cp);
110 utcp->nconnections--;
115 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
116 // Check whether this combination of src and dst is free
119 if(find_connection(utcp, src, dst)) {
123 } else { // If src == 0, generate a random port number with the high bit set
124 if(utcp->nconnections >= 32767) {
128 src = rand() | 0x8000;
129 while(find_connection(utcp, src, dst))
133 // Allocate memory for the new connection
135 if(utcp->nconnections >= utcp->nallocated) {
136 if(!utcp->nallocated)
137 utcp->nallocated = 4;
139 utcp->nallocated *= 2;
140 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
145 utcp->connections = new_array;
148 struct utcp_connection *c = calloc(1, sizeof *c);
154 // Fill in the details
159 c->snd.una = c->snd.iss;
160 c->snd.nxt = c->snd.iss + 1;
161 c->rcv.wnd = utcp->mtu;
163 c->sndbufsize = 65536;
164 c->sndbuf = malloc(c->sndbufsize);
168 // Add it to the sorted list of connections
170 utcp->connections[utcp->nconnections++] = c;
171 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
176 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
177 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
187 hdr.seq = c->snd.iss;
190 hdr.wnd = c->rcv.wnd;
192 set_state(c, SYN_SENT);
194 print_packet(utcp, "send", &hdr, sizeof hdr);
195 utcp->send(utcp, &hdr, sizeof hdr);
197 gettimeofday(&c->conn_timeout, NULL);
198 c->conn_timeout.tv_sec += utcp->timeout;
203 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
204 if(c->reapable || c->state != SYN_RECEIVED) {
205 fprintf(stderr, "Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
209 fprintf(stderr, "%p accepted, %p %p\n", c, recv, priv);
212 set_state(c, ESTABLISHED);
215 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
217 fprintf(stderr, "Error: send() called on closed connection %p\n", c);
227 fprintf(stderr, "Error: send() called on unconnected connection %p\n", c);
238 fprintf(stderr, "Error: send() called on closing connection %p\n", c);
243 // Add data to send buffer
253 uint32_t bufused = c->snd.nxt - c->snd.una;
255 /* Check our send buffer.
256 * - If it's big enough, just put the data in there.
257 * - If not, decide whether to enlarge. (TODO, now we just always enlarge)
258 * - Cap len so it doesn't overflow our buffer.
261 if(len > c->sndbufsize - bufused) {
263 c->sndbuf = realloc(c->sndbuf, c->sndbufsize);
266 if(len > c->sndbufsize - bufused)
267 len = c->sndbufsize - bufused;
270 errno == EWOULDBLOCK;
274 memcpy(c->sndbuf + bufused, data, len);
280 char data[c->utcp->mtu];
283 pkt.hdr.src = c->src;
284 pkt.hdr.dst = c->dst;
285 pkt.hdr.ack = c->rcv.nxt;
286 pkt.hdr.wnd = c->snd.wnd;
292 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
293 pkt.hdr.seq = c->snd.nxt;
295 memcpy(pkt.data, data, seglen);
297 c->snd.nxt += seglen;
301 print_packet(c->utcp, "send", &pkt, sizeof pkt.hdr + seglen);
302 c->utcp->send(c->utcp, &pkt, sizeof pkt.hdr + seglen);
305 fprintf(stderr, "len=%zu\n", len);
309 static void swap_ports(struct hdr *hdr) {
310 uint16_t tmp = hdr->src;
315 static int32_t seqdiff(uint32_t a, uint32_t b) {
319 int utcp_recv(struct utcp *utcp, const void *data, size_t len) {
333 print_packet(utcp, "recv", data, len);
335 // Drop packets smaller than the header
338 if(len < sizeof hdr) {
343 // Make a copy from the potentially unaligned data to a struct hdr
345 memcpy(&hdr, data, sizeof hdr);
349 // Drop packets with an unknown CTL flag
351 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
356 // Try to match the packet to an existing connection
358 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
360 // Is it for a new connection?
363 // Ignore RST packets
368 // Is it a SYN packet and are we LISTENing?
370 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
371 // If we don't want to accept it, send a RST back
372 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
377 // Try to allocate memory, otherwise send a RST back
378 c = allocate_connection(utcp, hdr.dst, hdr.src);
384 // Return SYN+ACK, go to SYN_RECEIVED state
385 c->snd.wnd = hdr.wnd;
386 c->rcv.irs = hdr.seq;
387 c->rcv.nxt = c->rcv.irs + 1;
388 set_state(c, SYN_RECEIVED);
392 hdr.ack = c->rcv.irs + 1;
393 hdr.seq = c->snd.iss;
395 print_packet(c->utcp, "send", &hdr, sizeof hdr);
396 utcp->send(utcp, &hdr, sizeof hdr);
398 // No, we don't want your packets, send a RST back
406 fprintf(stderr, "%p state %s\n", c->utcp, strstate[c->state]);
408 // In case this is for a CLOSED connection, ignore the packet.
409 // TODO: make it so incoming packets can never match a CLOSED connection.
411 if(c->state == CLOSED)
414 // It is for an existing connection.
416 // 1. Drop invalid packets.
418 // 1a. Drop packets that should not happen in our current state.
435 // 1b. Drop packets with a sequence number not in our receive window.
439 if(c->state == SYN_SENT)
442 // TODO: handle packets overlapping c->rcv.nxt.
444 // Only use this when accepting out-of-order packets.
447 acceptable = hdr.seq == c->rcv.nxt;
449 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
452 // We don't accept data when the receive window is zero.
455 // Both start and end of packet must be within the receive window
456 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
457 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
459 if(c->state != SYN_SENT)
460 acceptable = hdr.seq == c->rcv.nxt;
464 fprintf(stderr, "Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
465 // Ignore unacceptable RST packets.
468 // Otherwise, send an ACK back in the hope things improve.
472 c->snd.wnd = hdr.wnd; // TODO: move below
474 // 1c. Drop packets with an invalid ACK.
475 // ackno should not roll back, and it should also not be bigger than snd.nxt.
477 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
478 fprintf(stderr, "Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
479 // Ignore unacceptable RST packets.
485 // 2. Handle RST packets
492 // The peer has refused our connection.
493 set_state(c, CLOSED);
494 errno = ECONNREFUSED;
501 // We haven't told the application about this connection yet. Silently delete.
510 // The peer has aborted our connection.
511 set_state(c, CLOSED);
521 // As far as the application is concerned, the connection has already been closed.
522 // If it has called utcp_close() already, we can immediately free this connection.
527 // Otherwise, immediately move to the CLOSED state.
528 set_state(c, CLOSED);
535 // 3. Advance snd.una
537 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
538 c->snd.una = hdr.ack;
541 fprintf(stderr, "%p advanced %u\n", utcp, advanced);
542 // Make room in the send buffer.
543 // TODO: try to avoid memmoving too much. Circular buffer?
544 uint32_t left = seqdiff(c->snd.nxt, hdr.ack);
546 memmove(c->sndbuf, c->sndbuf + advanced, left);
552 timerclear(&c->conn_timeout); // It should be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
553 if(c->snd.una == c->snd.nxt)
554 timerclear(&c->rtrx_timeout);
557 // 5. Process SYN stuff
562 // This is a SYNACK. It should always have ACKed the SYN.
565 c->rcv.irs = hdr.seq;
566 c->rcv.nxt = hdr.seq;
567 set_state(c, ESTABLISHED);
568 // TODO: notify application of this somehow.
578 // Ehm, no. We should never receive a second SYN.
584 // SYN counts as one sequence number
588 // 6. Process new data
590 if(c->state == SYN_RECEIVED) {
591 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
595 // Are we still LISTENing?
597 utcp->accept(c, c->src);
599 if(c->state != ESTABLISHED) {
600 set_state(c, CLOSED);
610 // This should never happen.
620 // Ehm no, We should never receive more data after a FIN.
629 rxd = c->recv(c, data, len);
633 rxd = len; // Bad application, bad!
641 // 7. Process FIN stuff
647 // This should never happen.
650 set_state(c, CLOSE_WAIT);
653 set_state(c, CLOSING);
656 set_state(c, TIME_WAIT);
662 // Ehm, no. We should never receive a second FIN.
668 // FIN counts as one sequence number
671 // Inform the application that the peer closed the connection.
678 if(!len && !advanced)
681 if(!len && !(hdr.ctl & SYN) && !(hdr.ctl & FIN))
687 hdr.seq = c->snd.nxt;
688 hdr.ack = c->rcv.nxt;
690 print_packet(c->utcp, "send", &hdr, sizeof hdr);
691 utcp->send(utcp, &hdr, sizeof hdr);
701 hdr.ack = hdr.seq + len;
705 print_packet(utcp, "send", &hdr, sizeof hdr);
706 utcp->send(utcp, &hdr, sizeof hdr);
711 int utcp_shutdown(struct utcp_connection *c, int dir) {
712 fprintf(stderr, "%p shutdown %d\n", c->utcp, dir);
719 fprintf(stderr, "Error: shutdown() called on closed connection %p\n", c);
731 set_state(c, CLOSED);
736 set_state(c, FIN_WAIT_1);
742 set_state(c, CLOSING);
757 hdr.seq = c->snd.nxt;
758 hdr.ack = c->rcv.nxt;
759 hdr.wnd = c->snd.wnd;
764 print_packet(c->utcp, "send", &hdr, sizeof hdr);
765 c->utcp->send(c->utcp, &hdr, sizeof hdr);
769 int utcp_close(struct utcp_connection *c) {
770 if(utcp_shutdown(c, SHUT_RDWR))
776 int utcp_abort(struct utcp_connection *c) {
783 fprintf(stderr, "Error: abort() called on closed connection %p\n", c);
798 set_state(c, CLOSED);
806 set_state(c, CLOSED);
816 hdr.seq = c->snd.nxt;
821 print_packet(c->utcp, "send", &hdr, sizeof hdr);
822 c->utcp->send(c->utcp, &hdr, sizeof hdr);
826 static void retransmit(struct utcp_connection *c) {
827 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
830 struct utcp *utcp = c->utcp;
834 char data[c->utcp->mtu];
837 pkt.hdr.src = c->src;
838 pkt.hdr.dst = c->dst;
842 // TODO: this should not happen
846 pkt.hdr.seq = c->snd.iss;
848 pkt.hdr.wnd = c->rcv.wnd;
850 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
851 utcp->send(utcp, &pkt, sizeof pkt.hdr);
855 pkt.hdr.seq = c->snd.nxt;
856 pkt.hdr.ack = c->rcv.nxt;
857 pkt.hdr.ctl = SYN | ACK;
858 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
859 utcp->send(utcp, &pkt, sizeof pkt.hdr);
864 pkt.hdr.seq = c->snd.una;
865 pkt.hdr.ack = c->rcv.nxt;
867 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
868 if(c->state == FIN_WAIT_1)
873 if(c->state == FIN_WAIT_1)
876 memcpy(pkt.data, c->sndbuf, len);
877 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr + len);
878 utcp->send(utcp, &pkt, sizeof pkt.hdr + len);
888 * One call to this function will loop through all connections,
889 * checking if something needs to be resent or not.
890 * The return value is the time to the next timeout in milliseconds,
891 * or maybe a negative value if the timeout is infinite.
893 int utcp_timeout(struct utcp *utcp) {
895 gettimeofday(&now, NULL);
896 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
898 for(int i = 0; i < utcp->nconnections; i++) {
899 struct utcp_connection *c = utcp->connections[i];
903 if(c->state == CLOSED) {
905 fprintf(stderr, "Reaping %p\n", c);
912 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
920 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
924 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
925 next = c->conn_timeout;
927 if(c->snd.nxt != c->snd.una) {
928 c->rtrx_timeout = now;
929 c->rtrx_timeout.tv_sec++;
931 timerclear(&c->rtrx_timeout);
934 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
935 next = c->rtrx_timeout;
939 timersub(&next, &now, &diff);
942 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
945 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
946 struct utcp *utcp = calloc(1, sizeof *utcp);
955 utcp->accept = accept;
956 utcp->pre_accept = pre_accept;
965 void utcp_exit(struct utcp *utcp) {
968 for(int i = 0; i < utcp->nconnections; i++)
969 free_connection(utcp->connections[i]);
973 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
974 // TODO: handle overhead of the header
978 int utcp_set_connection_timeout(struct utcp *u, int timeout) {
979 int prev = u->timeout;
980 u->timeout = timeout;