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;
186 // Add it to the sorted list of connections
188 utcp->connections[utcp->nconnections++] = c;
189 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
194 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
195 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
205 hdr.seq = c->snd.iss;
208 hdr.wnd = c->rcv.wnd;
210 set_state(c, SYN_SENT);
212 print_packet(utcp, "send", &hdr, sizeof hdr);
213 utcp->send(utcp, &hdr, sizeof hdr);
215 gettimeofday(&c->conn_timeout, NULL);
216 c->conn_timeout.tv_sec += utcp->timeout;
221 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
222 if(c->reapable || c->state != SYN_RECEIVED) {
223 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
227 debug("%p accepted, %p %p\n", c, recv, priv);
230 set_state(c, ESTABLISHED);
233 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
235 debug("Error: send() called on closed connection %p\n", c);
245 debug("Error: send() called on unconnected connection %p\n", c);
256 debug("Error: send() called on closing connection %p\n", c);
261 // Add data to send buffer
271 uint32_t bufused = seqdiff(c->snd.nxt, c->snd.una);
273 /* Check our send buffer.
274 * - If it's big enough, just put the data in there.
275 * - If not, decide whether to enlarge if possible.
276 * - Cap len so it doesn't overflow our buffer.
279 if(len > c->sndbufsize - bufused && c->sndbufsize < c->maxsndbufsize) {
280 if(c->sndbufsize > c->maxsndbufsize / 2)
281 c->sndbufsize = c->maxsndbufsize;
284 c->sndbuf = realloc(c->sndbuf, c->sndbufsize);
287 if(len > c->sndbufsize - bufused)
288 len = c->sndbufsize - bufused;
291 errno == EWOULDBLOCK;
295 memcpy(c->sndbuf + bufused, data, len);
301 char data[c->utcp->mtu];
304 pkt.hdr.src = c->src;
305 pkt.hdr.dst = c->dst;
306 pkt.hdr.ack = c->rcv.nxt;
307 pkt.hdr.wnd = c->snd.wnd;
313 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
314 pkt.hdr.seq = c->snd.nxt;
316 memcpy(pkt.data, data, seglen);
318 c->snd.nxt += seglen;
322 print_packet(c->utcp, "send", &pkt, sizeof pkt.hdr + seglen);
323 c->utcp->send(c->utcp, &pkt, sizeof pkt.hdr + seglen);
326 fprintf(stderr, "len=%zu\n", len);
330 static void swap_ports(struct hdr *hdr) {
331 uint16_t tmp = hdr->src;
336 int utcp_recv(struct utcp *utcp, const void *data, size_t len) {
350 print_packet(utcp, "recv", data, len);
352 // Drop packets smaller than the header
355 if(len < sizeof hdr) {
360 // Make a copy from the potentially unaligned data to a struct hdr
362 memcpy(&hdr, data, sizeof hdr);
366 // Drop packets with an unknown CTL flag
368 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
373 // Try to match the packet to an existing connection
375 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
377 // Is it for a new connection?
380 // Ignore RST packets
385 // Is it a SYN packet and are we LISTENing?
387 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
388 // If we don't want to accept it, send a RST back
389 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
394 // Try to allocate memory, otherwise send a RST back
395 c = allocate_connection(utcp, hdr.dst, hdr.src);
401 // Return SYN+ACK, go to SYN_RECEIVED state
402 c->snd.wnd = hdr.wnd;
403 c->rcv.irs = hdr.seq;
404 c->rcv.nxt = c->rcv.irs + 1;
405 set_state(c, SYN_RECEIVED);
409 hdr.ack = c->rcv.irs + 1;
410 hdr.seq = c->snd.iss;
412 print_packet(c->utcp, "send", &hdr, sizeof hdr);
413 utcp->send(utcp, &hdr, sizeof hdr);
415 // No, we don't want your packets, send a RST back
423 debug("%p state %s\n", c->utcp, strstate[c->state]);
425 // In case this is for a CLOSED connection, ignore the packet.
426 // TODO: make it so incoming packets can never match a CLOSED connection.
428 if(c->state == CLOSED)
431 // It is for an existing connection.
433 // 1. Drop invalid packets.
435 // 1a. Drop packets that should not happen in our current state.
452 // 1b. Drop packets with a sequence number not in our receive window.
456 if(c->state == SYN_SENT)
459 // TODO: handle packets overlapping c->rcv.nxt.
461 // Only use this when accepting out-of-order packets.
464 acceptable = hdr.seq == c->rcv.nxt;
466 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
469 // We don't accept data when the receive window is zero.
472 // Both start and end of packet must be within the receive window
473 acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
474 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
476 if(c->state != SYN_SENT)
477 acceptable = hdr.seq == c->rcv.nxt;
481 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
482 // Ignore unacceptable RST packets.
485 // Otherwise, send an ACK back in the hope things improve.
489 c->snd.wnd = hdr.wnd; // TODO: move below
491 // 1c. Drop packets with an invalid ACK.
492 // ackno should not roll back, and it should also not be bigger than snd.nxt.
494 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
495 debug("Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
496 // Ignore unacceptable RST packets.
502 // 2. Handle RST packets
509 // The peer has refused our connection.
510 set_state(c, CLOSED);
511 errno = ECONNREFUSED;
518 // We haven't told the application about this connection yet. Silently delete.
527 // The peer has aborted our connection.
528 set_state(c, CLOSED);
538 // As far as the application is concerned, the connection has already been closed.
539 // If it has called utcp_close() already, we can immediately free this connection.
544 // Otherwise, immediately move to the CLOSED state.
545 set_state(c, CLOSED);
552 // 3. Advance snd.una
554 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
555 c->snd.una = hdr.ack;
558 debug("%p advanced %u\n", utcp, advanced);
559 // Make room in the send buffer.
560 // TODO: try to avoid memmoving too much. Circular buffer?
561 uint32_t left = seqdiff(c->snd.nxt, hdr.ack);
563 memmove(c->sndbuf, c->sndbuf + advanced, left);
569 timerclear(&c->conn_timeout); // It should be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
570 if(c->snd.una == c->snd.nxt)
571 timerclear(&c->rtrx_timeout);
574 // 5. Process SYN stuff
579 // This is a SYNACK. It should always have ACKed the SYN.
582 c->rcv.irs = hdr.seq;
583 c->rcv.nxt = hdr.seq;
584 set_state(c, ESTABLISHED);
585 // TODO: notify application of this somehow.
595 // Ehm, no. We should never receive a second SYN.
601 // SYN counts as one sequence number
605 // 6. Process new data
607 if(c->state == SYN_RECEIVED) {
608 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
612 // Are we still LISTENing?
614 utcp->accept(c, c->src);
616 if(c->state != ESTABLISHED) {
617 set_state(c, CLOSED);
627 // This should never happen.
637 // Ehm no, We should never receive more data after a FIN.
646 rxd = c->recv(c, data, len);
650 rxd = len; // Bad application, bad!
658 // 7. Process FIN stuff
664 // This should never happen.
667 set_state(c, CLOSE_WAIT);
670 set_state(c, CLOSING);
673 set_state(c, TIME_WAIT);
679 // Ehm, no. We should never receive a second FIN.
685 // FIN counts as one sequence number
688 // Inform the application that the peer closed the connection.
695 if(!len && !advanced)
698 if(!len && !(hdr.ctl & SYN) && !(hdr.ctl & FIN))
704 hdr.seq = c->snd.nxt;
705 hdr.ack = c->rcv.nxt;
707 print_packet(c->utcp, "send", &hdr, sizeof hdr);
708 utcp->send(utcp, &hdr, sizeof hdr);
718 hdr.ack = hdr.seq + len;
722 print_packet(utcp, "send", &hdr, sizeof hdr);
723 utcp->send(utcp, &hdr, sizeof hdr);
728 int utcp_shutdown(struct utcp_connection *c, int dir) {
729 debug("%p shutdown %d\n", c->utcp, dir);
736 debug("Error: shutdown() called on closed connection %p\n", c);
748 set_state(c, CLOSED);
753 set_state(c, FIN_WAIT_1);
759 set_state(c, CLOSING);
774 hdr.seq = c->snd.nxt;
775 hdr.ack = c->rcv.nxt;
776 hdr.wnd = c->snd.wnd;
781 print_packet(c->utcp, "send", &hdr, sizeof hdr);
782 c->utcp->send(c->utcp, &hdr, sizeof hdr);
786 int utcp_close(struct utcp_connection *c) {
787 if(utcp_shutdown(c, SHUT_RDWR))
793 int utcp_abort(struct utcp_connection *c) {
800 debug("Error: abort() called on closed connection %p\n", c);
815 set_state(c, CLOSED);
823 set_state(c, CLOSED);
833 hdr.seq = c->snd.nxt;
838 print_packet(c->utcp, "send", &hdr, sizeof hdr);
839 c->utcp->send(c->utcp, &hdr, sizeof hdr);
843 static void retransmit(struct utcp_connection *c) {
844 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
847 struct utcp *utcp = c->utcp;
851 char data[c->utcp->mtu];
854 pkt.hdr.src = c->src;
855 pkt.hdr.dst = c->dst;
859 // TODO: this should not happen
863 pkt.hdr.seq = c->snd.iss;
865 pkt.hdr.wnd = c->rcv.wnd;
867 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
868 utcp->send(utcp, &pkt, sizeof pkt.hdr);
872 pkt.hdr.seq = c->snd.nxt;
873 pkt.hdr.ack = c->rcv.nxt;
874 pkt.hdr.ctl = SYN | ACK;
875 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
876 utcp->send(utcp, &pkt, sizeof pkt.hdr);
881 pkt.hdr.seq = c->snd.una;
882 pkt.hdr.ack = c->rcv.nxt;
884 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
885 if(c->state == FIN_WAIT_1)
890 if(c->state == FIN_WAIT_1)
893 memcpy(pkt.data, c->sndbuf, len);
894 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr + len);
895 utcp->send(utcp, &pkt, sizeof pkt.hdr + len);
905 * One call to this function will loop through all connections,
906 * checking if something needs to be resent or not.
907 * The return value is the time to the next timeout in milliseconds,
908 * or maybe a negative value if the timeout is infinite.
910 int utcp_timeout(struct utcp *utcp) {
912 gettimeofday(&now, NULL);
913 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
915 for(int i = 0; i < utcp->nconnections; i++) {
916 struct utcp_connection *c = utcp->connections[i];
920 if(c->state == CLOSED) {
922 debug("Reaping %p\n", c);
929 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
937 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
941 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
942 next = c->conn_timeout;
944 if(c->snd.nxt != c->snd.una) {
945 c->rtrx_timeout = now;
946 c->rtrx_timeout.tv_sec++;
948 timerclear(&c->rtrx_timeout);
951 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
952 next = c->rtrx_timeout;
956 timersub(&next, &now, &diff);
959 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
962 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
963 struct utcp *utcp = calloc(1, sizeof *utcp);
972 utcp->accept = accept;
973 utcp->pre_accept = pre_accept;
982 void utcp_exit(struct utcp *utcp) {
985 for(int i = 0; i < utcp->nconnections; i++)
986 free_connection(utcp->connections[i]);
990 uint16_t utcp_get_mtu(struct utcp *utcp) {
994 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
995 // TODO: handle overhead of the header
999 int utcp_get_user_timeout(struct utcp *u) {
1003 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1004 u->timeout = timeout;
1007 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1008 return c->maxsndbufsize;
1011 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1012 c->maxsndbufsize = size;
1013 if(c->maxsndbufsize != size)
1014 c->maxsndbufsize = -1;
1017 bool utcp_get_nodelay(struct utcp_connection *c) {
1021 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1022 c->nodelay = nodelay;
1025 bool utcp_get_keepalive(struct utcp_connection *c) {
1026 return c->keepalive;
1029 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1030 c->keepalive = keepalive;
1033 size_t utcp_get_outq(struct utcp_connection *c) {
1034 return seqdiff(c->snd.nxt, c->snd.una);