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(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
141 if(len < sizeof hdr) {
142 fprintf(stderr, "%p %s: short packet (%zu bytes)\n", utcp, dir, len);
146 memcpy(&hdr, pkt, sizeof hdr);
147 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);
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 print_packet(utcp, "send", &hdr, sizeof hdr);
293 utcp->send(utcp, &hdr, sizeof hdr);
295 gettimeofday(&c->conn_timeout, NULL);
296 c->conn_timeout.tv_sec += utcp->timeout;
301 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
302 if(c->reapable || c->state != SYN_RECEIVED) {
303 fprintf(stderr, "Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
307 fprintf(stderr, "%p accepted, %p %p\n", c, recv, priv);
310 set_state(c, ESTABLISHED);
313 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
315 fprintf(stderr, "Error: send() called on closed connection %p\n", c);
325 fprintf(stderr, "Error: send() called on unconnected connection %p\n", c);
336 fprintf(stderr, "Error: send() called on closing connection %p\n", c);
341 // Add data to send buffer
351 uint32_t bufused = c->snd.nxt - c->snd.una;
353 if(len > c->sndbufsize - bufused)
354 len = c->sndbufsize - bufused;
356 memcpy(c->sndbuf + (c->snd.nxt - c->snd.una), data, len);
362 char data[c->utcp->mtu];
365 pkt.hdr.src = c->src;
366 pkt.hdr.dst = c->dst;
367 pkt.hdr.ack = c->rcv.nxt;
368 pkt.hdr.wnd = c->snd.wnd;
374 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
375 pkt.hdr.seq = c->snd.nxt;
377 memcpy(pkt.data, data, seglen);
379 c->snd.nxt += seglen;
383 print_packet(c->utcp, "send", &pkt, sizeof pkt.hdr + seglen);
384 c->utcp->send(c->utcp, &pkt, sizeof pkt.hdr + seglen);
387 fprintf(stderr, "len=%zu\n", len);
391 static void swap_ports(struct hdr *hdr) {
392 uint16_t tmp = hdr->src;
397 static int32_t seqdiff(uint32_t a, uint32_t b) {
401 int utcp_recv(struct utcp *utcp, const void *data, size_t len) {
415 print_packet(utcp, "recv", data, len);
418 if(len < sizeof hdr) {
423 memcpy(&hdr, data, sizeof hdr);
427 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
432 //list_connections(utcp);
434 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
436 // Is it for a new connection?
442 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
444 c->snd.wnd = hdr.wnd;
445 c->rcv.irs = hdr.seq;
446 c->rcv.nxt = c->rcv.irs + 1;
447 set_state(c, SYN_RECEIVED);
451 hdr.ack = c->rcv.irs + 1;
452 hdr.seq = c->snd.iss;
454 print_packet(c->utcp, "send", &hdr, sizeof hdr);
455 utcp->send(utcp, &hdr, sizeof hdr);
463 fprintf(stderr, "%p state %s\n", c->utcp, strstate[c->state]);
465 if(c->state == CLOSED) {
466 fprintf(stderr, "Error: packet recv()d on closed connection %p\n", c);
471 // It is for an existing connection.
473 if(c->state == SYN_SENT) {
475 if(seqdiff(hdr.ack, c->snd.iss) <= 0 || seqdiff(hdr.ack, c->snd.nxt) > 0) {
476 fprintf(stderr, "Invalid ACK, %u %u %u\n", hdr.ack, c->snd.iss, c->snd.nxt);
483 set_state(c, CLOSED);
484 errno = ECONNREFUSED;
491 c->rcv.nxt = hdr.seq + 1;
492 c->rcv.irs = hdr.seq;
493 c->snd.wnd = hdr.wnd;
496 c->snd.una = hdr.ack;
497 if(seqdiff(c->snd.una, c->snd.iss) > 0) {
498 set_state(c, ESTABLISHED);
501 hdr.seq = c->snd.nxt;
502 hdr.ack = c->rcv.nxt;
505 set_state(c, SYN_RECEIVED);
507 hdr.seq = c->snd.iss;
508 hdr.ack = c->rcv.nxt;
511 print_packet(c->utcp, "send", &hdr, sizeof hdr);
512 utcp->send(utcp, &hdr, sizeof hdr);
513 // TODO: queue any data?
523 acceptable = hdr.seq == c->rcv.nxt;
525 acceptable = (hdr.seq >= c->rcv.nxt && hdr.seq < c->rcv.nxt + c->rcv.wnd);
530 acceptable = (hdr.seq >= c->rcv.nxt && hdr.seq < c->rcv.nxt + c->rcv.wnd)
531 || (hdr.seq + len - 1 >= c->rcv.nxt && hdr.seq + len - 1 < c->rcv.nxt + c->rcv.wnd);
534 fprintf(stderr, "Packet not acceptable, %u %u %u %zu\n", hdr.seq, c->rcv.nxt, c->rcv.wnd, len);
540 c->snd.wnd = hdr.wnd;
542 // TODO: check whether segment really starts at rcv.nxt, otherwise trim it.
547 // TODO: delete connection?
553 set_state(c, CLOSED);
561 // TODO: delete connection?
567 set_state(c, CLOSED);
581 set_state(c, CLOSED);
598 if(seqdiff(hdr.ack, c->snd.una) >= 0 && seqdiff(hdr.ack, c->snd.nxt) <= 0)
599 c->utcp->accept(c, hdr.dst);
601 if(c->state != ESTABLISHED)
604 c->snd.una = hdr.ack;
608 if(seqdiff(hdr.ack, c->snd.una) < 0)
610 if(seqdiff(hdr.ack, c->snd.nxt) > 0)
612 if(seqdiff(hdr.ack, c->snd.una) > 0 && seqdiff(hdr.ack, c->snd.nxt) <= 0) {
613 c->snd.una = hdr.ack;
614 if(seqdiff(c->snd.wl1, hdr.seq) < 0 || (c->snd.wl1 == hdr.seq && seqdiff(c->snd.wl2, hdr.ack) <= 0)) {
615 c->snd.wnd = hdr.wnd;
616 c->snd.wl1 = hdr.seq;
617 c->snd.wl2 = hdr.ack;
622 if(hdr.ack == c->snd.nxt)
623 set_state(c, FIN_WAIT_2);
626 // TODO: If nothing left to send, close.
629 if(hdr.ack == c->snd.nxt) {
630 set_state(c, TIME_WAIT);
634 if(hdr.ack == c->snd.nxt) {
635 set_state(c, CLOSED);
639 // TODO: retransmission of remote FIN, ACK and restart 2 MSL timeout
651 // TODO: process the data, see page 74
670 set_state(c, CLOSE_WAIT);
674 set_state(c, CLOSING);
678 set_state(c, TIME_WAIT);
694 c->recv(c, data, len);
708 hdr.ack = hdr.seq + len;
712 print_packet(c->utcp, "send", &hdr, sizeof hdr);
713 utcp->send(utcp, &hdr, sizeof hdr);
718 hdr.seq = c->snd.nxt;
719 hdr.ack = c->rcv.nxt;
721 print_packet(c->utcp, "send", &hdr, sizeof hdr);
722 utcp->send(utcp, &hdr, sizeof hdr);
723 if(c->state == CLOSE_WAIT || c->state == TIME_WAIT) {
731 int utcp_shutdown(struct utcp_connection *c, int dir) {
738 fprintf(stderr, "Error: shutdown() called on closed connection %p\n", c);
750 set_state(c, CLOSED);
755 set_state(c, FIN_WAIT_1);
761 set_state(c, LAST_ACK);
776 hdr.seq = c->snd.nxt;
777 hdr.ack = c->rcv.nxt;
778 hdr.wnd = c->snd.wnd;
783 print_packet(c->utcp, "send", &hdr, sizeof hdr);
784 c->utcp->send(c->utcp, &hdr, sizeof hdr);
788 int utcp_close(struct utcp_connection *c) {
789 if(utcp_shutdown(c, SHUT_RDWR))
795 int utcp_abort(struct utcp_connection *c) {
802 fprintf(stderr, "Error: abort() called on closed connection %p\n", c);
817 set_state(c, CLOSED);
825 set_state(c, CLOSED);
835 hdr.seq = c->snd.nxt;
840 print_packet(c->utcp, "send", &hdr, sizeof hdr);
841 c->utcp->send(c->utcp, &hdr, sizeof hdr);
845 static void retransmit(struct utcp_connection *c) {
846 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
849 struct utcp *utcp = c->utcp;
853 char data[c->utcp->mtu];
856 pkt.hdr.src = c->src;
857 pkt.hdr.dst = c->dst;
861 // TODO: this should not happen
865 pkt.hdr.seq = c->snd.iss;
867 pkt.hdr.wnd = c->rcv.wnd;
869 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
870 utcp->send(utcp, &pkt, sizeof pkt.hdr);
874 pkt.hdr.seq = c->snd.nxt;
875 pkt.hdr.ack = c->rcv.nxt;
876 pkt.hdr.ctl = SYN | ACK;
877 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr);
878 utcp->send(utcp, &pkt, sizeof pkt.hdr);
882 pkt.hdr.seq = c->snd.una;
883 pkt.hdr.ack = c->rcv.nxt;
885 uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
888 memcpy(pkt.data, c->sndbuf, len);
889 print_packet(c->utcp, "rtrx", &pkt, sizeof pkt.hdr + len);
890 utcp->send(utcp, &pkt, sizeof pkt.hdr + len);
900 * One call to this function will loop through all connections,
901 * checking if something needs to be resent or not.
902 * The return value is the time to the next timeout in milliseconds,
903 * or maybe a negative value if the timeout is infinite.
905 int utcp_timeout(struct utcp *utcp) {
907 gettimeofday(&now, NULL);
908 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
910 for(int i = 0; i < utcp->nconnections; i++) {
911 struct utcp_connection *c = utcp->connections[i];
915 if(c->state == CLOSED) {
917 fprintf(stderr, "Reaping %p\n", c);
924 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
932 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
936 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
937 next = c->conn_timeout;
939 if(c->snd.nxt != c->snd.una) {
940 c->rtrx_timeout = now;
941 c->rtrx_timeout.tv_sec++;
943 timerclear(&c->rtrx_timeout);
946 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
947 next = c->rtrx_timeout;
951 timersub(&next, &now, &diff);
954 return diff.tv_sec * 1000 + diff.tv_usec / 1000;
957 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
958 struct utcp *utcp = calloc(1, sizeof *utcp);
967 utcp->accept = accept;
968 utcp->pre_accept = pre_accept;
977 void utcp_exit(struct utcp *utcp) {
980 for(int i = 0; i < utcp->nconnections; i++)
981 free_connection(utcp->connections[i]);
985 int utcp_set_connection_timeout(struct utcp *u, int timeout) {
986 int prev = u->timeout;
987 u->timeout = timeout;