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
110 struct timeval conn_timeout;
111 struct timeval rtrx_timeout;
120 utcp_accept_t accept;
121 utcp_pre_accept_t pre_accept;
127 struct utcp_connection **connections;
132 static void set_state(struct utcp_connection *c, enum state state) {
134 if(state == ESTABLISHED)
135 timerclear(&c->conn_timeout);
136 fprintf(stderr, "%p new state: %s\n", c->utcp, strstate[state]);
139 static void print_packet(const void *pkt, size_t len) {
141 if(len < sizeof hdr) {
142 fprintf(stderr, "short packet (%zu bytes)\n", len);
146 memcpy(&hdr, pkt, sizeof hdr);
147 fprintf (stderr, "src=%u dst=%u seq=%u ack=%u wnd=%u ctl=", hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd);
149 fprintf(stderr, "SYN");
151 fprintf(stderr, "RST");
153 fprintf(stderr, "FIN");
155 fprintf(stderr, "ACK");
157 if(len > sizeof hdr) {
158 fprintf(stderr, " data=");
159 for(int i = sizeof hdr; i < len; i++) {
160 const char *data = pkt;
161 fprintf(stderr, "%c", data[i] >= 32 ? data[i] : '.');
165 fprintf(stderr, "\n");
168 static inline void list_connections(struct utcp *utcp) {
169 fprintf(stderr, "%p has %d connections:\n", utcp, utcp->nconnections);
170 for(int i = 0; i < utcp->nconnections; i++)
171 fprintf(stderr, " %u -> %u state %s\n", utcp->connections[i]->src, utcp->connections[i]->dst, strstate[utcp->connections[i]->state]);
174 // Connections are stored in a sorted list.
175 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
177 static int compare(const void *va, const void *vb) {
178 const struct utcp_connection *a = *(struct utcp_connection **)va;
179 const struct utcp_connection *b = *(struct utcp_connection **)vb;
180 if(!a->src || !b->src)
182 int c = (int)a->src - (int)b->src;
185 c = (int)a->dst - (int)b->dst;
189 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
190 if(!utcp->nconnections)
192 struct utcp_connection key = {
196 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
197 return match ? *match : NULL;
200 static void free_connection(struct utcp_connection *c) {
201 struct utcp *utcp = c->utcp;
202 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
206 int i = cp - utcp->connections;
207 memmove(cp + i, cp + i + 1, (utcp->nconnections - i - 1) * sizeof *cp);
208 utcp->nconnections--;
213 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
214 // Check whether this combination of src and dst is free
217 if(find_connection(utcp, src, dst)) {
221 } else { // If src == 0, generate a random port number with the high bit set
222 if(utcp->nconnections >= 32767) {
226 src = rand() | 0x8000;
227 while(find_connection(utcp, src, dst))
231 // Allocate memory for the new connection
233 if(utcp->nconnections >= utcp->nallocated) {
234 if(!utcp->nallocated)
235 utcp->nallocated = 4;
237 utcp->nallocated *= 2;
238 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
243 utcp->connections = new_array;
246 struct utcp_connection *c = calloc(1, sizeof *c);
252 // Fill in the details
257 c->snd.una = c->snd.iss;
258 c->snd.nxt = c->snd.iss + 1;
259 c->rcv.wnd = utcp->mtu;
261 c->sndbufsize = 65536;
262 c->sndbuf = malloc(c->sndbufsize);
266 // Add it to the sorted list of connections
268 utcp->connections[utcp->nconnections++] = c;
269 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
274 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
275 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
285 hdr.seq = c->snd.iss;
288 hdr.wnd = c->rcv.wnd;
290 set_state(c, SYN_SENT);
292 utcp->send(utcp, &hdr, sizeof hdr);
294 gettimeofday(&c->conn_timeout, NULL);
295 c->conn_timeout.tv_sec += utcp->timeout;
300 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
301 if(c->reapable || c->state != SYN_RECEIVED) {
302 fprintf(stderr, "Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
306 fprintf(stderr, "%p accepted, %p %p\n", c, recv, priv);
309 set_state(c, ESTABLISHED);
312 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
314 fprintf(stderr, "Error: send() called on closed connection %p\n", c);
324 fprintf(stderr, "Error: send() called on unconnected connection %p\n", c);
335 fprintf(stderr, "Error: send() called on closing connection %p\n", c);
340 // Add data to send buffer
350 uint32_t bufused = c->snd.nxt - c->snd.una;
352 if(len > c->sndbufsize - bufused)
353 len = c->sndbufsize - bufused;
355 memcpy(c->sndbuf + (c->snd.nxt - c->snd.una), data, len);
361 char data[c->utcp->mtu];
364 pkt.hdr.src = c->src;
365 pkt.hdr.dst = c->dst;
366 pkt.hdr.ack = c->rcv.nxt;
367 pkt.hdr.wnd = c->snd.wnd;
373 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
374 pkt.hdr.seq = c->snd.nxt;
376 memcpy(pkt.data, data, seglen);
378 c->snd.nxt += seglen;
382 c->utcp->send(c->utcp, &pkt, sizeof pkt.hdr + seglen);
385 fprintf(stderr, "len=%zu\n", len);
389 static void swap_ports(struct hdr *hdr) {
390 uint16_t tmp = hdr->src;
395 static int32_t seqdiff(uint32_t a, uint32_t b) {
399 int utcp_recv(struct utcp *utcp, const void *data, size_t len) {
413 fprintf(stderr, "%p got: ", utcp);
414 print_packet(data, len);
417 if(len < sizeof hdr) {
422 memcpy(&hdr, data, sizeof hdr);
426 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
431 //list_connections(utcp);
433 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
435 // Is it for a new connection?
441 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept && (!utcp->pre_accept || utcp->pre_accept(utcp, hdr.dst)) && (c = allocate_connection(utcp, hdr.dst, hdr.src))) { // LISTEN
443 c->snd.wnd = hdr.wnd;
444 c->rcv.irs = hdr.seq;
445 c->rcv.nxt = c->rcv.irs + 1;
446 set_state(c, SYN_RECEIVED);
450 hdr.ack = c->rcv.irs + 1;
451 hdr.seq = c->snd.iss;
453 utcp->send(utcp, &hdr, sizeof hdr);
461 fprintf(stderr, "%p state %s\n", c->utcp, strstate[c->state]);
463 if(c->state == CLOSED) {
464 fprintf(stderr, "Error: packet recv()d on closed connection %p\n", c);
469 // It is for an existing connection.
471 if(c->state == SYN_SENT) {
473 if(seqdiff(hdr.ack, c->snd.iss) <= 0 || seqdiff(hdr.ack, c->snd.nxt) > 0) {
474 fprintf(stderr, "Invalid ACK, %u %u %u\n", hdr.ack, c->snd.iss, c->snd.nxt);
481 set_state(c, CLOSED);
482 errno = ECONNREFUSED;
489 c->rcv.nxt = hdr.seq + 1;
490 c->rcv.irs = hdr.seq;
491 c->snd.wnd = hdr.wnd;
494 c->snd.una = hdr.ack;
495 if(seqdiff(c->snd.una, c->snd.iss) > 0) {
496 set_state(c, ESTABLISHED);
499 hdr.seq = c->snd.nxt;
500 hdr.ack = c->rcv.nxt;
503 set_state(c, SYN_RECEIVED);
505 hdr.seq = c->snd.iss;
506 hdr.ack = c->rcv.nxt;
509 utcp->send(utcp, &hdr, sizeof hdr);
510 // TODO: queue any data?
520 acceptable = hdr.seq == c->rcv.nxt;
522 acceptable = (hdr.seq >= c->rcv.nxt && hdr.seq < c->rcv.nxt + c->rcv.wnd);
527 acceptable = (hdr.seq >= c->rcv.nxt && hdr.seq < c->rcv.nxt + c->rcv.wnd)
528 || (hdr.seq + len - 1 >= c->rcv.nxt && hdr.seq + len - 1 < c->rcv.nxt + c->rcv.wnd);
531 fprintf(stderr, "Packet not acceptable, %u %u %u %zu\n", hdr.seq, c->rcv.nxt, c->rcv.wnd, len);
537 c->snd.wnd = hdr.wnd;
539 // TODO: check whether segment really starts at rcv.nxt, otherwise trim it.
544 // TODO: delete connection?
550 set_state(c, CLOSED);
558 // TODO: delete connection?
564 set_state(c, CLOSED);
578 set_state(c, CLOSED);
595 if(seqdiff(hdr.ack, c->snd.una) >= 0 && seqdiff(hdr.ack, c->snd.nxt) <= 0)
596 c->utcp->accept(c, hdr.dst);
598 if(c->state != ESTABLISHED)
603 if(seqdiff(hdr.ack, c->snd.una) < 0)
605 if(seqdiff(hdr.ack, c->snd.nxt) > 0)
607 if(seqdiff(hdr.ack, c->snd.una) > 0 && seqdiff(hdr.ack, c->snd.nxt) <= 0) {
608 c->snd.una = hdr.ack;
609 if(seqdiff(c->snd.wl1, hdr.seq) < 0 || (c->snd.wl1 == hdr.seq && seqdiff(c->snd.wl2, hdr.ack) <= 0)) {
610 c->snd.wnd = hdr.wnd;
611 c->snd.wl1 = hdr.seq;
612 c->snd.wl2 = hdr.ack;
617 if(hdr.ack == c->snd.nxt)
618 set_state(c, FIN_WAIT_2);
621 // TODO: If nothing left to send, close.
624 if(hdr.ack == c->snd.nxt) {
625 set_state(c, TIME_WAIT);
629 if(hdr.ack == c->snd.nxt) {
630 set_state(c, CLOSED);
634 // TODO: retransmission of remote FIN, ACK and restart 2 MSL timeout
646 // TODO: process the data, see page 74
665 set_state(c, CLOSE_WAIT);
669 set_state(c, CLOSING);
673 set_state(c, TIME_WAIT);
689 c->recv(c, data, len);
703 hdr.ack = hdr.seq + len;
707 utcp->send(utcp, &hdr, sizeof hdr);
712 hdr.seq = c->snd.nxt;
713 hdr.ack = c->rcv.nxt;
715 utcp->send(utcp, &hdr, sizeof hdr);
716 if(c->state == CLOSE_WAIT || c->state == TIME_WAIT) {
724 int utcp_shutdown(struct utcp_connection *c, int dir) {
731 fprintf(stderr, "Error: shutdown() called on closed connection %p\n", c);
743 set_state(c, CLOSED);
748 set_state(c, FIN_WAIT_1);
754 set_state(c, LAST_ACK);
769 hdr.seq = c->snd.nxt;
770 hdr.ack = c->rcv.nxt;
771 hdr.wnd = c->snd.wnd;
776 c->utcp->send(c->utcp, &hdr, sizeof hdr);
780 int utcp_close(struct utcp_connection *c) {
781 if(utcp_shutdown(c, SHUT_RDWR))
787 int utcp_abort(struct utcp_connection *c) {
794 fprintf(stderr, "Error: abort() called on closed connection %p\n", c);
809 set_state(c, CLOSED);
817 set_state(c, CLOSED);
827 hdr.seq = c->snd.nxt;
832 c->utcp->send(c->utcp, &hdr, sizeof hdr);
836 static void retransmit(struct utcp_connection *c) {
837 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
840 struct utcp *utcp = c->utcp;
844 char data[c->utcp->mtu];
847 pkt.hdr.src = c->src;
848 pkt.hdr.dst = c->dst;
852 // TODO: this should not happen
856 pkt.hdr.seq = c->snd.iss;
858 pkt.hdr.wnd = c->rcv.wnd;
860 utcp->send(utcp, &pkt, sizeof pkt.hdr);
864 pkt.hdr.seq = c->snd.nxt;
865 pkt.hdr.ack = c->rcv.nxt;
866 pkt.hdr.ctl = SYN | ACK;
867 utcp->send(utcp, &pkt, sizeof pkt.hdr);
871 pkt.hdr.seq = c->snd.una;
872 pkt.hdr.ack = c->rcv.nxt;
874 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
877 memcpy(pkt.data, c->sndbuf, 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 int utcp_set_connection_timeout(struct utcp *u, int timeout) {
974 int prev = u->timeout;
975 u->timeout = timeout;