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.
31 #include <sys/socket.h>
33 #include "utcp_priv.h"
48 #define timersub(a, b, r) do {\
49 (r)->tv_sec = (a)->tv_sec - (b)->tv_sec;\
50 (r)->tv_usec = (a)->tv_usec - (b)->tv_usec;\
52 (r)->tv_sec--, (r)->tv_usec += 1000000;\
57 #define max(a, b) ((a) > (b) ? (a) : (b))
63 static void debug(const char *format, ...) {
66 vfprintf(stderr, format, ap);
70 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
72 if(len < sizeof hdr) {
73 debug("%p %s: short packet (%zu bytes)\n", utcp, dir, len);
77 memcpy(&hdr, pkt, sizeof hdr);
78 fprintf (stderr, "%p %s: len=%zu, src=%u dst=%u seq=%u ack=%u wnd=%u ctl=", utcp, dir, len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd);
88 if(len > sizeof hdr) {
89 uint32_t datalen = len - sizeof hdr;
90 uint8_t *str = malloc((datalen << 1) + 7);
91 memcpy(str, " data=", 6);
92 uint8_t *strptr = str + 6;
93 const uint8_t *data = pkt;
94 const uint8_t *dataend = data + datalen;
96 while(data != dataend) {
97 *strptr = (*data >> 4) > 9? (*data >> 4) + 55 : (*data >> 4) + 48;
99 *strptr = (*data & 0xf) > 9? (*data & 0xf) + 55 : (*data & 0xf) + 48;
113 #define print_packet(...)
116 static void set_state(struct utcp_connection *c, enum state state) {
118 if(state == ESTABLISHED)
119 timerclear(&c->conn_timeout);
120 debug("%p new state: %s\n", c->utcp, strstate[state]);
123 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
124 if(seq != c->snd.last)
136 static inline void list_connections(struct utcp *utcp) {
137 debug("%p has %d connections:\n", utcp, utcp->nconnections);
138 for(int i = 0; i < utcp->nconnections; i++)
139 debug(" %u -> %u state %s\n", utcp->connections[i]->src, utcp->connections[i]->dst, strstate[utcp->connections[i]->state]);
142 static int32_t seqdiff(uint32_t a, uint32_t b) {
147 // TODO: convert to ringbuffers to avoid memmove() operations.
149 // Store data into the buffer
150 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
151 if(buf->maxsize <= buf->used)
154 debug("buffer_put_at %zu %zu %zu\n", buf->used, offset, len);
156 size_t required = offset + len;
157 if(required > buf->maxsize) {
158 if(offset >= buf->maxsize)
161 len = buf->maxsize - offset;
162 required = buf->maxsize;
165 if(required > buf->size) {
166 size_t newsize = buf->size;
172 } while(newsize < buf->used + len);
174 if(newsize > buf->maxsize)
175 newsize = buf->maxsize;
176 char *newdata = realloc(buf->data, newsize);
183 memcpy(buf->data + offset, data, len);
184 if(required > buf->used)
185 buf->used = required;
189 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
190 return buffer_put_at(buf, buf->used, data, len);
193 // Get data from the buffer. data can be NULL.
194 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
198 memcpy(data, buf->data, len);
200 memmove(buf->data, buf->data + len, buf->used - len);
205 // Copy data from the buffer without removing it.
206 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
207 if(offset >= buf->used)
209 if(offset + len > buf->used)
210 len = buf->used - offset;
211 memcpy(data, buf->data + offset, len);
215 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
216 memset(buf, 0, sizeof *buf);
218 buf->data = malloc(len);
223 buf->maxsize = maxlen;
227 static void buffer_exit(struct buffer *buf) {
229 memset(buf, 0, sizeof *buf);
232 static uint32_t buffer_free(const struct buffer *buf) {
233 return buf->maxsize - buf->used;
236 // Connections are stored in a sorted list.
237 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
239 static int compare(const void *va, const void *vb) {
242 const struct utcp_connection *a = *(struct utcp_connection **)va;
243 const struct utcp_connection *b = *(struct utcp_connection **)vb;
246 assert(a->src && b->src);
248 int c = (int)a->src - (int)b->src;
251 c = (int)a->dst - (int)b->dst;
255 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
256 if(!utcp->nconnections)
258 struct utcp_connection key = {
262 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
263 return match ? *match : NULL;
266 static void free_connection(struct utcp_connection *c) {
267 struct utcp *utcp = c->utcp;
268 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
272 int i = cp - utcp->connections;
273 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof *cp);
274 utcp->nconnections--;
276 buffer_exit(&c->sndbuf);
280 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
281 // Check whether this combination of src and dst is free
284 if(find_connection(utcp, src, dst)) {
288 } else { // If src == 0, generate a random port number with the high bit set
289 if(utcp->nconnections >= 32767) {
293 src = rand() | 0x8000;
294 while(find_connection(utcp, src, dst))
298 // Allocate memory for the new connection
300 if(utcp->nconnections >= utcp->nallocated) {
301 if(!utcp->nallocated)
302 utcp->nallocated = 4;
304 utcp->nallocated *= 2;
305 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
308 utcp->connections = new_array;
311 struct utcp_connection *c = calloc(1, sizeof *c);
315 if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
320 if(!buffer_init(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
325 // Fill in the details
334 c->snd.una = c->snd.iss;
335 c->snd.nxt = c->snd.iss + 1;
336 c->rcv.wnd = utcp->mtu;
337 c->snd.last = c->snd.nxt;
338 c->snd.cwnd = utcp->mtu;
341 // Add it to the sorted list of connections
343 utcp->connections[utcp->nconnections++] = c;
344 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
349 // Update RTT variables. See RFC 6298.
350 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
352 debug("invalid rtt\n");
356 struct utcp *utcp = c->utcp;
360 utcp->rttvar = rtt / 2;
361 utcp->rto = rtt + max(2 * rtt, CLOCK_GRANULARITY);
363 utcp->rttvar = (utcp->rttvar * 3 + abs(utcp->srtt - rtt)) / 4;
364 utcp->srtt = (utcp->srtt * 7 + rtt) / 8;
365 utcp->rto = utcp->srtt + max(utcp->rttvar, CLOCK_GRANULARITY);
368 if(utcp->rto > MAX_RTO)
371 debug("rtt %u srtt %u rttvar %u rto %u\n", rtt, utcp->srtt, utcp->rttvar, utcp->rto);
374 static void start_retransmit_timer(struct utcp_connection *c) {
375 gettimeofday(&c->rtrx_timeout, NULL);
376 c->rtrx_timeout.tv_usec += c->utcp->rto;
377 while(c->rtrx_timeout.tv_usec >= 1000000) {
378 c->rtrx_timeout.tv_usec -= 1000000;
379 c->rtrx_timeout.tv_sec++;
381 debug("timeout set to %lu.%06lu (%u)\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_usec, c->utcp->rto);
384 static void stop_retransmit_timer(struct utcp_connection *c) {
385 timerclear(&c->rtrx_timeout);
386 debug("timeout cleared\n");
389 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
390 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
401 hdr.seq = c->snd.iss;
403 hdr.wnd = c->rcv.wnd;
407 set_state(c, SYN_SENT);
409 print_packet(utcp, "send", &hdr, sizeof hdr);
410 utcp->send(utcp, &hdr, sizeof hdr);
412 gettimeofday(&c->conn_timeout, NULL);
413 c->conn_timeout.tv_sec += utcp->timeout;
418 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
419 if(c->reapable || c->state != SYN_RECEIVED) {
420 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
424 debug("%p accepted, %p %p\n", c, recv, priv);
427 set_state(c, ESTABLISHED);
430 static void ack(struct utcp_connection *c, bool sendatleastone) {
431 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
432 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
433 debug("cwndleft = %d\n", cwndleft);
443 if(!left && !sendatleastone)
451 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
455 pkt->hdr.src = c->src;
456 pkt->hdr.dst = c->dst;
457 pkt->hdr.ack = c->rcv.nxt;
458 pkt->hdr.wnd = c->snd.wnd;
463 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
464 pkt->hdr.seq = c->snd.nxt;
466 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
468 c->snd.nxt += seglen;
471 if(seglen && fin_wanted(c, c->snd.nxt)) {
476 if(!c->rtt_start.tv_sec) {
477 // Start RTT measurement
478 gettimeofday(&c->rtt_start, NULL);
479 c->rtt_seq = pkt->hdr.seq + seglen;
480 debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
483 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
484 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
490 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
492 debug("Error: send() called on closed connection %p\n", c);
502 debug("Error: send() called on unconnected connection %p\n", c);
513 debug("Error: send() called on closing connection %p\n", c);
518 // Add data to send buffer
528 len = buffer_put(&c->sndbuf, data, len);
536 if(!timerisset(&c->rtrx_timeout))
537 start_retransmit_timer(c);
541 static void swap_ports(struct hdr *hdr) {
542 uint16_t tmp = hdr->src;
547 static void retransmit(struct utcp_connection *c) {
548 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
551 struct utcp *utcp = c->utcp;
558 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
562 pkt->hdr.src = c->src;
563 pkt->hdr.dst = c->dst;
567 // Send our SYN again
568 pkt->hdr.seq = c->snd.iss;
570 pkt->hdr.wnd = c->rcv.wnd;
572 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
573 utcp->send(utcp, pkt, sizeof pkt->hdr);
578 pkt->hdr.seq = c->snd.nxt;
579 pkt->hdr.ack = c->rcv.nxt;
580 pkt->hdr.ctl = SYN | ACK;
581 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
582 utcp->send(utcp, pkt, sizeof pkt->hdr);
590 // Send unacked data again.
591 pkt->hdr.seq = c->snd.una;
592 pkt->hdr.ack = c->rcv.nxt;
594 uint32_t len = seqdiff(c->snd.last, c->snd.una);
597 if(fin_wanted(c, c->snd.una + len)) {
601 c->snd.nxt = c->snd.una + len;
602 c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
603 buffer_copy(&c->sndbuf, pkt->data, 0, len);
604 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
605 utcp->send(utcp, pkt, sizeof pkt->hdr + len);
612 // We shouldn't need to retransmit anything in this state.
616 stop_retransmit_timer(c);
620 start_retransmit_timer(c);
622 if(utcp->rto > MAX_RTO)
624 c->rtt_start.tv_sec = 0; // invalidate RTT timer
630 // Update receive buffer and SACK entries after consuming data.
631 static void sack_consume(struct utcp_connection *c, size_t len) {
632 debug("sack_consume %zu\n", len);
633 if(len > c->rcvbuf.used)
636 buffer_get(&c->rcvbuf, NULL, len);
638 for(int i = 0; i < NSACKS && c->sacks[i].len; ) {
639 if(len < c->sacks[i].offset) {
640 c->sacks[i].offset -= len;
642 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
643 c->sacks[i].offset = 0;
644 c->sacks[i].len -= len - c->sacks[i].offset;
648 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof c->sacks[i]);
649 c->sacks[i + 1].len = 0;
657 for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
658 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
661 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
662 debug("out of order packet, offset %u\n", offset);
663 // Packet loss or reordering occured. Store the data in the buffer.
664 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
668 // Make note of where we put it.
669 for(int i = 0; i < NSACKS; i++) {
670 if(!c->sacks[i].len) { // nothing to merge, add new entry
671 debug("New SACK entry %d\n", i);
672 c->sacks[i].offset = offset;
673 c->sacks[i].len = rxd;
675 } else if(offset < c->sacks[i].offset) {
676 if(offset + rxd < c->sacks[i].offset) { // insert before
677 if(!c->sacks[NSACKS - 1].len) { // only if room left
678 debug("Insert SACK entry at %d\n", i);
679 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof c->sacks[i]);
680 c->sacks[i].offset = offset;
681 c->sacks[i].len = rxd;
685 debug("Merge with start of SACK entry at %d\n", i);
686 c->sacks[i].offset = offset;
689 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
690 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
691 debug("Merge with end of SACK entry at %d\n", i);
692 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
693 // TODO: handle potential merge with next entry
699 for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
700 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
703 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
704 // Check if we can process out-of-order data now.
705 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
706 debug("incoming packet len %zu connected with SACK at %u\n", len, c->sacks[0].offset);
707 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
708 len = max(len, c->sacks[0].offset + c->sacks[0].len);
709 data = c->rcvbuf.data;
713 ssize_t rxd = c->recv(c, data, len);
715 // TODO: handle the application not accepting all data.
721 sack_consume(c, len);
727 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
728 uint32_t offset = seqdiff(seq, c->rcv.nxt);
729 if(offset + len > c->rcvbuf.maxsize)
733 handle_out_of_order(c, offset, data, len);
735 handle_in_order(c, data, len);
739 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
753 print_packet(utcp, "recv", data, len);
755 // Drop packets smaller than the header
758 if(len < sizeof hdr) {
763 // Make a copy from the potentially unaligned data to a struct hdr
765 memcpy(&hdr, data, sizeof hdr);
769 // Drop packets with an unknown CTL flag
771 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
776 // Try to match the packet to an existing connection
778 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
780 // Is it for a new connection?
783 // Ignore RST packets
788 // Is it a SYN packet and are we LISTENing?
790 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
791 // If we don't want to accept it, send a RST back
792 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
797 // Try to allocate memory, otherwise send a RST back
798 c = allocate_connection(utcp, hdr.dst, hdr.src);
804 // Return SYN+ACK, go to SYN_RECEIVED state
805 c->snd.wnd = hdr.wnd;
806 c->rcv.irs = hdr.seq;
807 c->rcv.nxt = c->rcv.irs + 1;
808 set_state(c, SYN_RECEIVED);
812 hdr.ack = c->rcv.irs + 1;
813 hdr.seq = c->snd.iss;
815 print_packet(c->utcp, "send", &hdr, sizeof hdr);
816 utcp->send(utcp, &hdr, sizeof hdr);
818 // No, we don't want your packets, send a RST back
826 debug("%p state %s\n", c->utcp, strstate[c->state]);
828 // In case this is for a CLOSED connection, ignore the packet.
829 // TODO: make it so incoming packets can never match a CLOSED connection.
831 if(c->state == CLOSED)
834 // It is for an existing connection.
836 uint32_t prevrcvnxt = c->rcv.nxt;
838 // 1. Drop invalid packets.
840 // 1a. Drop packets that should not happen in our current state.
860 // 1b. Drop packets with a sequence number not in our receive window.
864 if(c->state == SYN_SENT)
867 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
869 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
871 // cut already accepted front overlapping
873 acceptable = rcv_offset + len >= 0;
880 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
884 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcvbuf.maxsize);
885 // Ignore unacceptable RST packets.
888 // Otherwise, send an ACK back in the hope things improve.
893 c->snd.wnd = hdr.wnd; // TODO: move below
895 // 1c. Drop packets with an invalid ACK.
896 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
897 // (= snd.una + c->sndbuf.used).
899 if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
900 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
901 // Ignore unacceptable RST packets.
907 // 2. Handle RST packets
914 // The peer has refused our connection.
915 set_state(c, CLOSED);
916 errno = ECONNREFUSED;
923 // We haven't told the application about this connection yet. Silently delete.
932 // The peer has aborted our connection.
933 set_state(c, CLOSED);
943 // As far as the application is concerned, the connection has already been closed.
944 // If it has called utcp_close() already, we can immediately free this connection.
949 // Otherwise, immediately move to the CLOSED state.
950 set_state(c, CLOSED);
960 // 3. Advance snd.una
962 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
963 prevrcvnxt = c->rcv.nxt;
967 if(c->rtt_start.tv_sec) {
968 if(c->rtt_seq == hdr.ack) {
969 struct timeval now, diff;
970 gettimeofday(&now, NULL);
971 timersub(&now, &c->rtt_start, &diff);
972 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
973 c->rtt_start.tv_sec = 0;
974 } else if(c->rtt_seq < hdr.ack) {
975 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
976 c->rtt_start.tv_sec = 0;
980 int32_t data_acked = advanced;
987 // TODO: handle FIN as well.
992 assert(data_acked >= 0);
994 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
995 assert(data_acked <= bufused);
998 buffer_get(&c->sndbuf, NULL, data_acked);
1000 // Also advance snd.nxt if possible
1001 if(seqdiff(c->snd.nxt, hdr.ack) < 0)
1002 c->snd.nxt = hdr.ack;
1004 c->snd.una = hdr.ack;
1007 c->snd.cwnd += utcp->mtu;
1008 if(c->snd.cwnd > c->sndbuf.maxsize)
1009 c->snd.cwnd = c->sndbuf.maxsize;
1011 // Check if we have sent a FIN that is now ACKed.
1014 if(c->snd.una == c->snd.last)
1015 set_state(c, FIN_WAIT_2);
1018 if(c->snd.una == c->snd.last) {
1019 gettimeofday(&c->conn_timeout, NULL);
1020 c->conn_timeout.tv_sec += 60;
1021 set_state(c, TIME_WAIT);
1030 if(c->dupack == 3) {
1031 debug("Triplicate ACK\n");
1032 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1033 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1034 //Reset the congestion window so we wait for ACKs.
1035 c->snd.nxt = c->snd.una;
1036 c->snd.cwnd = utcp->mtu;
1037 start_retransmit_timer(c);
1045 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
1046 if(c->snd.una == c->snd.last)
1047 stop_retransmit_timer(c);
1049 start_retransmit_timer(c);
1052 // 5. Process SYN stuff
1057 // This is a SYNACK. It should always have ACKed the SYN.
1060 c->rcv.irs = hdr.seq;
1061 c->rcv.nxt = hdr.seq;
1062 set_state(c, ESTABLISHED);
1063 // TODO: notify application of this somehow.
1073 // Ehm, no. We should never receive a second SYN.
1082 // SYN counts as one sequence number
1086 // 6. Process new data
1088 if(c->state == SYN_RECEIVED) {
1089 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1093 // Are we still LISTENing?
1095 utcp->accept(c, c->src);
1097 if(c->state != ESTABLISHED) {
1098 set_state(c, CLOSED);
1108 // This should never happen.
1121 // Ehm no, We should never receive more data after a FIN.
1130 handle_incoming_data(c, hdr.seq, data, len);
1133 // 7. Process FIN stuff
1135 if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1139 // This should never happen.
1145 set_state(c, CLOSE_WAIT);
1148 set_state(c, CLOSING);
1151 gettimeofday(&c->conn_timeout, NULL);
1152 c->conn_timeout.tv_sec += 60;
1153 set_state(c, TIME_WAIT);
1159 // Ehm, no. We should never receive a second FIN.
1168 // FIN counts as one sequence number
1172 // Inform the application that the peer closed the connection.
1175 c->recv(c, NULL, 0);
1179 // Now we send something back if:
1180 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1181 // -> sendatleastone = true
1182 // - or we got an ack, so we should maybe send a bit more data
1183 // -> sendatleastone = false
1185 ack(c, len || prevrcvnxt != c->rcv.nxt);
1195 hdr.ack = hdr.seq + len;
1197 hdr.ctl = RST | ACK;
1199 print_packet(utcp, "send", &hdr, sizeof hdr);
1200 utcp->send(utcp, &hdr, sizeof hdr);
1205 int utcp_shutdown(struct utcp_connection *c, int dir) {
1206 debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1213 debug("Error: shutdown() called on closed connection %p\n", c);
1218 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1223 // TCP does not have a provision for stopping incoming packets.
1224 // The best we can do is to just ignore them.
1225 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR)
1228 // The rest of the code deals with shutting down writes.
1229 if(dir == UTCP_SHUT_RD)
1239 set_state(c, CLOSED);
1244 set_state(c, FIN_WAIT_1);
1250 set_state(c, CLOSING);
1265 int utcp_close(struct utcp_connection *c) {
1266 if(utcp_shutdown(c, SHUT_RDWR))
1274 int utcp_abort(struct utcp_connection *c) {
1281 debug("Error: abort() called on closed connection %p\n", c);
1298 set_state(c, CLOSED);
1306 set_state(c, CLOSED);
1316 hdr.seq = c->snd.nxt;
1321 print_packet(c->utcp, "send", &hdr, sizeof hdr);
1322 c->utcp->send(c->utcp, &hdr, sizeof hdr);
1327 * One call to this function will loop through all connections,
1328 * checking if something needs to be resent or not.
1329 * The return value is the time to the next timeout in milliseconds,
1330 * or maybe a negative value if the timeout is infinite.
1332 struct timeval utcp_timeout(struct utcp *utcp) {
1334 gettimeofday(&now, NULL);
1335 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1337 for(int i = 0; i < utcp->nconnections; i++) {
1338 struct utcp_connection *c = utcp->connections[i];
1342 // delete connections that have been utcp_close()d.
1343 if(c->state == CLOSED) {
1345 debug("Reaping %p\n", c);
1352 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1356 c->recv(c, NULL, 0);
1360 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1361 debug("retransmit()\n");
1365 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1366 c->poll(c, buffer_free(&c->sndbuf));
1368 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1369 next = c->conn_timeout;
1371 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1372 next = c->rtrx_timeout;
1375 struct timeval diff;
1376 timersub(&next, &now, &diff);
1380 bool utcp_is_active(struct utcp *utcp) {
1384 for(int i = 0; i < utcp->nconnections; i++)
1385 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT)
1391 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1397 struct utcp *utcp = calloc(1, sizeof *utcp);
1401 utcp->accept = accept;
1402 utcp->pre_accept = pre_accept;
1405 utcp->mtu = DEFAULT_MTU;
1406 utcp->timeout = DEFAULT_USER_TIMEOUT; // s
1407 utcp->rto = START_RTO; // us
1412 void utcp_exit(struct utcp *utcp) {
1415 for(int i = 0; i < utcp->nconnections; i++) {
1416 if(!utcp->connections[i]->reapable)
1417 debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1418 buffer_exit(&utcp->connections[i]->sndbuf);
1419 free(utcp->connections[i]);
1421 free(utcp->connections);
1425 uint16_t utcp_get_mtu(struct utcp *utcp) {
1426 return utcp ? utcp->mtu : 0;
1429 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1430 // TODO: handle overhead of the header
1435 int utcp_get_user_timeout(struct utcp *u) {
1436 return u ? u->timeout : 0;
1439 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1441 u->timeout = timeout;
1444 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1445 return c ? c->sndbuf.maxsize : 0;
1448 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1449 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1450 return buffer_free(&c->sndbuf);
1455 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1458 c->sndbuf.maxsize = size;
1459 if(c->sndbuf.maxsize != size)
1460 c->sndbuf.maxsize = -1;
1463 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1464 return c ? c->rcvbuf.maxsize : 0;
1467 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1468 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1469 return buffer_free(&c->rcvbuf);
1474 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1477 c->rcvbuf.maxsize = size;
1478 if(c->rcvbuf.maxsize != size)
1479 c->rcvbuf.maxsize = -1;
1482 bool utcp_get_nodelay(struct utcp_connection *c) {
1483 return c ? c->nodelay : false;
1486 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1488 c->nodelay = nodelay;
1491 bool utcp_get_keepalive(struct utcp_connection *c) {
1492 return c ? c->keepalive : false;
1495 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1497 c->keepalive = keepalive;
1500 size_t utcp_get_outq(struct utcp_connection *c) {
1501 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1504 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1509 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1514 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
1516 utcp->accept = accept;
1517 utcp->pre_accept = pre_accept;