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) {
90 for(int i = sizeof hdr; i < len; i++) {
91 const char *data = pkt;
92 debug("%c", data[i] >= 32 ? data[i] : '.');
100 #define print_packet(...)
103 static void set_state(struct utcp_connection *c, enum state state) {
105 if(state == ESTABLISHED)
106 timerclear(&c->conn_timeout);
107 debug("%p new state: %s\n", c->utcp, strstate[state]);
110 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
111 if(seq != c->snd.last)
123 static inline void list_connections(struct utcp *utcp) {
124 debug("%p has %d connections:\n", utcp, utcp->nconnections);
125 for(int i = 0; i < utcp->nconnections; i++)
126 debug(" %u -> %u state %s\n", utcp->connections[i]->src, utcp->connections[i]->dst, strstate[utcp->connections[i]->state]);
129 static int32_t seqdiff(uint32_t a, uint32_t b) {
134 // TODO: convert to ringbuffers to avoid memmove() operations.
136 // Store data into the buffer
137 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
138 if(buf->maxsize <= buf->used)
141 debug("buffer_put_at %zu %zu %zu\n", buf->used, offset, len);
143 size_t required = offset + len;
144 if(required > buf->maxsize) {
145 if(offset >= buf->maxsize)
148 len = buf->maxsize - offset;
149 required = buf->maxsize;
152 if(required > buf->size) {
153 size_t newsize = buf->size;
159 } while(newsize < buf->used + len);
161 if(newsize > buf->maxsize)
162 newsize = buf->maxsize;
163 char *newdata = realloc(buf->data, newsize);
170 memcpy(buf->data + offset, data, len);
171 if(required > buf->used)
172 buf->used = required;
176 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
177 return buffer_put_at(buf, buf->used, data, len);
180 // Get data from the buffer. data can be NULL.
181 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
185 memcpy(data, buf->data, len);
187 memmove(buf->data, buf->data + len, buf->used - len);
192 // Copy data from the buffer without removing it.
193 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
194 if(offset >= buf->used)
196 if(offset + len > buf->used)
197 len = buf->used - offset;
198 memcpy(data, buf->data + offset, len);
202 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
203 memset(buf, 0, sizeof *buf);
205 buf->data = malloc(len);
210 buf->maxsize = maxlen;
214 static void buffer_exit(struct buffer *buf) {
216 memset(buf, 0, sizeof *buf);
219 static uint32_t buffer_free(const struct buffer *buf) {
220 return buf->maxsize - buf->used;
223 // Connections are stored in a sorted list.
224 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
226 static int compare(const void *va, const void *vb) {
229 const struct utcp_connection *a = *(struct utcp_connection **)va;
230 const struct utcp_connection *b = *(struct utcp_connection **)vb;
233 assert(a->src && b->src);
235 int c = (int)a->src - (int)b->src;
238 c = (int)a->dst - (int)b->dst;
242 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
243 if(!utcp->nconnections)
245 struct utcp_connection key = {
249 struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
250 return match ? *match : NULL;
253 static void free_connection(struct utcp_connection *c) {
254 struct utcp *utcp = c->utcp;
255 struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
259 int i = cp - utcp->connections;
260 memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof *cp);
261 utcp->nconnections--;
263 buffer_exit(&c->sndbuf);
267 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
268 // Check whether this combination of src and dst is free
271 if(find_connection(utcp, src, dst)) {
275 } else { // If src == 0, generate a random port number with the high bit set
276 if(utcp->nconnections >= 32767) {
280 src = rand() | 0x8000;
281 while(find_connection(utcp, src, dst))
285 // Allocate memory for the new connection
287 if(utcp->nconnections >= utcp->nallocated) {
288 if(!utcp->nallocated)
289 utcp->nallocated = 4;
291 utcp->nallocated *= 2;
292 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
295 utcp->connections = new_array;
298 struct utcp_connection *c = calloc(1, sizeof *c);
302 if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
307 if(!buffer_init(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
312 // Fill in the details
322 c->snd.una = c->snd.iss;
323 c->snd.nxt = c->snd.iss + 1;
324 c->rcv.wnd = utcp->mtu;
325 c->snd.last = c->snd.nxt;
326 c->snd.cwnd = utcp->mtu;
329 // Add it to the sorted list of connections
331 utcp->connections[utcp->nconnections++] = c;
332 qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
337 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
338 struct utcp_connection *c = allocate_connection(utcp, 0, dst);
349 hdr.seq = c->snd.iss;
351 hdr.wnd = c->rcv.wnd;
355 set_state(c, SYN_SENT);
357 print_packet(utcp, "send", &hdr, sizeof hdr);
358 utcp->send(utcp, &hdr, sizeof hdr);
360 gettimeofday(&c->conn_timeout, NULL);
361 c->conn_timeout.tv_sec += utcp->timeout;
366 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
367 if(c->reapable || c->state != SYN_RECEIVED) {
368 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
372 debug("%p accepted, %p %p\n", c, recv, priv);
375 set_state(c, ESTABLISHED);
378 static void ack(struct utcp_connection *c, bool sendatleastone) {
379 int32_t left = seqdiff(c->snd.last, c->snd.nxt);
380 int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
381 debug("cwndleft = %d\n", cwndleft);
391 if(!left && !sendatleastone)
399 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
403 pkt->hdr.src = c->src;
404 pkt->hdr.dst = c->dst;
405 pkt->hdr.ack = c->rcv.nxt;
406 pkt->hdr.wnd = c->snd.wnd;
411 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
412 pkt->hdr.seq = c->snd.nxt;
414 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
416 c->snd.nxt += seglen;
419 if(seglen && fin_wanted(c, c->snd.nxt)) {
424 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
425 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
431 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
433 debug("Error: send() called on closed connection %p\n", c);
443 debug("Error: send() called on unconnected connection %p\n", c);
454 debug("Error: send() called on closing connection %p\n", c);
459 // Add data to send buffer
469 len = buffer_put(&c->sndbuf, data, len);
480 static void swap_ports(struct hdr *hdr) {
481 uint16_t tmp = hdr->src;
486 static void retransmit(struct utcp_connection *c) {
487 if(c->state == CLOSED || c->snd.nxt == c->snd.una)
490 struct utcp *utcp = c->utcp;
497 pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
501 pkt->hdr.src = c->src;
502 pkt->hdr.dst = c->dst;
506 // Send our SYN again
507 pkt->hdr.seq = c->snd.iss;
509 pkt->hdr.wnd = c->rcv.wnd;
511 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
512 utcp->send(utcp, pkt, sizeof pkt->hdr);
517 pkt->hdr.seq = c->snd.nxt;
518 pkt->hdr.ack = c->rcv.nxt;
519 pkt->hdr.ctl = SYN | ACK;
520 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
521 utcp->send(utcp, pkt, sizeof pkt->hdr);
529 // Send unacked data again.
530 pkt->hdr.seq = c->snd.una;
531 pkt->hdr.ack = c->rcv.nxt;
533 uint32_t len = seqdiff(c->snd.last, c->snd.una);
536 if(fin_wanted(c, c->snd.una + len)) {
540 c->snd.nxt = c->snd.una + len;
541 c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
542 buffer_copy(&c->sndbuf, pkt->data, 0, len);
543 print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
544 utcp->send(utcp, pkt, sizeof pkt->hdr + len);
551 // We shouldn't need to retransmit anything in this state.
555 timerclear(&c->rtrx_timeout);
562 // Update receive buffer and SACK entries after consuming data.
563 static void sack_consume(struct utcp_connection *c, size_t len) {
564 debug("sack_consume %zu\n", len);
565 if(len > c->rcvbuf.used)
568 buffer_get(&c->rcvbuf, NULL, len);
570 for(int i = 0; i < NSACKS && c->sacks[i].len; ) {
571 if(len < c->sacks[i].offset) {
572 c->sacks[i].offset -= len;
574 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
575 c->sacks[i].offset = 0;
576 c->sacks[i].len -= len - c->sacks[i].offset;
580 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof c->sacks[i]);
581 c->sacks[i + 1].len = 0;
589 for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
590 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
593 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
594 debug("out of order packet, offset %u\n", offset);
595 // Packet loss or reordering occured. Store the data in the buffer.
596 ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
600 // Make note of where we put it.
601 for(int i = 0; i < NSACKS; i++) {
602 if(!c->sacks[i].len) { // nothing to merge, add new entry
603 debug("New SACK entry %d\n", i);
604 c->sacks[i].offset = offset;
605 c->sacks[i].len = rxd;
607 } else if(offset < c->sacks[i].offset) {
608 if(offset + rxd < c->sacks[i].offset) { // insert before
609 if(!c->sacks[NSACKS - 1].len) { // only if room left
610 debug("Insert SACK entry at %d\n", i);
611 memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof c->sacks[i]);
612 c->sacks[i].offset = offset;
613 c->sacks[i].len = rxd;
617 debug("Merge with start of SACK entry at %d\n", i);
618 c->sacks[i].offset = offset;
621 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
622 if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
623 debug("Merge with end of SACK entry at %d\n", i);
624 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
625 // TODO: handle potential merge with next entry
631 for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
632 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
635 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
636 // Check if we can process out-of-order data now.
637 if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
638 debug("incoming packet len %zu connected with SACK at %u\n", len, c->sacks[0].offset);
639 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
640 len = max(len, c->sacks[0].offset + c->sacks[0].len);
641 data = c->rcvbuf.data;
645 ssize_t rxd = c->recv(c, data, len);
647 // TODO: handle the application not accepting all data.
653 sack_consume(c, len);
659 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
660 uint32_t offset = seqdiff(seq, c->rcv.nxt);
661 if(offset + len > c->rcvbuf.maxsize)
665 handle_out_of_order(c, offset, data, len);
667 handle_in_order(c, data, len);
671 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
685 print_packet(utcp, "recv", data, len);
687 // Drop packets smaller than the header
690 if(len < sizeof hdr) {
695 // Make a copy from the potentially unaligned data to a struct hdr
697 memcpy(&hdr, data, sizeof hdr);
701 // Drop packets with an unknown CTL flag
703 if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
708 // Try to match the packet to an existing connection
710 struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
712 // Is it for a new connection?
715 // Ignore RST packets
720 // Is it a SYN packet and are we LISTENing?
722 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
723 // If we don't want to accept it, send a RST back
724 if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
729 // Try to allocate memory, otherwise send a RST back
730 c = allocate_connection(utcp, hdr.dst, hdr.src);
736 // Return SYN+ACK, go to SYN_RECEIVED state
737 c->snd.wnd = hdr.wnd;
738 c->rcv.irs = hdr.seq;
739 c->rcv.nxt = c->rcv.irs + 1;
740 set_state(c, SYN_RECEIVED);
744 hdr.ack = c->rcv.irs + 1;
745 hdr.seq = c->snd.iss;
747 print_packet(c->utcp, "send", &hdr, sizeof hdr);
748 utcp->send(utcp, &hdr, sizeof hdr);
750 // No, we don't want your packets, send a RST back
758 debug("%p state %s\n", c->utcp, strstate[c->state]);
760 // In case this is for a CLOSED connection, ignore the packet.
761 // TODO: make it so incoming packets can never match a CLOSED connection.
763 if(c->state == CLOSED)
766 // It is for an existing connection.
768 uint32_t prevrcvnxt = c->rcv.nxt;
770 // 1. Drop invalid packets.
772 // 1a. Drop packets that should not happen in our current state.
792 // 1b. Drop packets with a sequence number not in our receive window.
796 if(c->state == SYN_SENT)
799 // TODO: handle packets overlapping c->rcv.nxt.
801 // Only use this when accepting out-of-order packets.
803 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
805 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
807 if(c->state != SYN_SENT)
808 acceptable = hdr.seq == c->rcv.nxt;
812 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcvbuf.maxsize);
813 // Ignore unacceptable RST packets.
816 // Otherwise, send an ACK back in the hope things improve.
821 c->snd.wnd = hdr.wnd; // TODO: move below
823 // 1c. Drop packets with an invalid ACK.
824 // ackno should not roll back, and it should also not be bigger than what we ever could have sent
825 // (= snd.una + c->sndbuf.used).
828 ((seqdiff(hdr.ack, c->snd.una + c->sndbuf.used) > 0 &&
829 seqdiff(hdr.ack, c->snd.nxt) > 0) // TODO: simplify this if
830 || seqdiff(hdr.ack, c->snd.una) < 0)) {
831 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
832 // Ignore unacceptable RST packets.
838 // 2. Handle RST packets
845 // The peer has refused our connection.
846 set_state(c, CLOSED);
847 errno = ECONNREFUSED;
854 // We haven't told the application about this connection yet. Silently delete.
863 // The peer has aborted our connection.
864 set_state(c, CLOSED);
874 // As far as the application is concerned, the connection has already been closed.
875 // If it has called utcp_close() already, we can immediately free this connection.
880 // Otherwise, immediately move to the CLOSED state.
881 set_state(c, CLOSED);
891 // 3. Advance snd.una
893 uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
894 prevrcvnxt = c->rcv.nxt;
897 int32_t data_acked = advanced;
904 // TODO: handle FIN as well.
909 assert(data_acked >= 0);
911 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
912 assert(data_acked <= bufused);
915 buffer_get(&c->sndbuf, NULL, data_acked);
917 // Also advance snd.nxt if possible
918 if(seqdiff(c->snd.nxt, hdr.ack) < 0)
919 c->snd.nxt = hdr.ack;
921 c->snd.una = hdr.ack;
924 c->snd.cwnd += utcp->mtu;
925 if(c->snd.cwnd > c->sndbuf.maxsize)
926 c->snd.cwnd = c->sndbuf.maxsize;
928 // Check if we have sent a FIN that is now ACKed.
931 if(c->snd.una == c->snd.last)
932 set_state(c, FIN_WAIT_2);
935 if(c->snd.una == c->snd.last) {
936 gettimeofday(&c->conn_timeout, NULL);
937 c->conn_timeout.tv_sec += 60;
938 set_state(c, TIME_WAIT);
948 debug("Triplicate ACK\n");
949 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
950 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
951 //Reset the congestion window so we wait for ACKs.
952 c->snd.nxt = c->snd.una;
953 c->snd.cwnd = utcp->mtu;
961 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
962 if(c->snd.una == c->snd.nxt)
963 timerclear(&c->rtrx_timeout);
966 // 5. Process SYN stuff
971 // This is a SYNACK. It should always have ACKed the SYN.
974 c->rcv.irs = hdr.seq;
975 c->rcv.nxt = hdr.seq;
976 set_state(c, ESTABLISHED);
977 // TODO: notify application of this somehow.
987 // Ehm, no. We should never receive a second SYN.
996 // SYN counts as one sequence number
1000 // 6. Process new data
1002 if(c->state == SYN_RECEIVED) {
1003 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1007 // Are we still LISTENing?
1009 utcp->accept(c, c->src);
1011 if(c->state != ESTABLISHED) {
1012 set_state(c, CLOSED);
1022 // This should never happen.
1035 // Ehm no, We should never receive more data after a FIN.
1044 handle_incoming_data(c, hdr.seq, data, len);
1047 // 7. Process FIN stuff
1049 if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1053 // This should never happen.
1059 set_state(c, CLOSE_WAIT);
1062 set_state(c, CLOSING);
1065 gettimeofday(&c->conn_timeout, NULL);
1066 c->conn_timeout.tv_sec += 60;
1067 set_state(c, TIME_WAIT);
1073 // Ehm, no. We should never receive a second FIN.
1082 // FIN counts as one sequence number
1086 // Inform the application that the peer closed the connection.
1089 c->recv(c, NULL, 0);
1093 // Now we send something back if:
1094 // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1095 // -> sendatleastone = true
1096 // - or we got an ack, so we should maybe send a bit more data
1097 // -> sendatleastone = false
1100 ack(c, prevrcvnxt != c->rcv.nxt);
1110 hdr.ack = hdr.seq + len;
1112 hdr.ctl = RST | ACK;
1114 print_packet(utcp, "send", &hdr, sizeof hdr);
1115 utcp->send(utcp, &hdr, sizeof hdr);
1120 int utcp_shutdown(struct utcp_connection *c, int dir) {
1121 debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1128 debug("Error: shutdown() called on closed connection %p\n", c);
1133 if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1138 // TCP does not have a provision for stopping incoming packets.
1139 // The best we can do is to just ignore them.
1140 if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR)
1143 // The rest of the code deals with shutting down writes.
1144 if(dir == UTCP_SHUT_RD)
1154 set_state(c, CLOSED);
1159 set_state(c, FIN_WAIT_1);
1165 set_state(c, CLOSING);
1180 int utcp_close(struct utcp_connection *c) {
1181 if(utcp_shutdown(c, SHUT_RDWR))
1189 int utcp_abort(struct utcp_connection *c) {
1196 debug("Error: abort() called on closed connection %p\n", c);
1213 set_state(c, CLOSED);
1221 set_state(c, CLOSED);
1231 hdr.seq = c->snd.nxt;
1236 print_packet(c->utcp, "send", &hdr, sizeof hdr);
1237 c->utcp->send(c->utcp, &hdr, sizeof hdr);
1242 * One call to this function will loop through all connections,
1243 * checking if something needs to be resent or not.
1244 * The return value is the time to the next timeout in milliseconds,
1245 * or maybe a negative value if the timeout is infinite.
1247 struct timeval utcp_timeout(struct utcp *utcp) {
1249 gettimeofday(&now, NULL);
1250 struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1252 for(int i = 0; i < utcp->nconnections; i++) {
1253 struct utcp_connection *c = utcp->connections[i];
1257 if(c->state == CLOSED) {
1259 debug("Reaping %p\n", c);
1266 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1270 c->recv(c, NULL, 0);
1274 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1278 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1279 c->poll(c, buffer_free(&c->sndbuf));
1281 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1282 next = c->conn_timeout;
1284 if(c->snd.nxt != c->snd.una) {
1285 c->rtrx_timeout = now;
1286 c->rtrx_timeout.tv_sec++;
1288 timerclear(&c->rtrx_timeout);
1291 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1292 next = c->rtrx_timeout;
1295 struct timeval diff;
1296 timersub(&next, &now, &diff);
1300 bool utcp_is_active(struct utcp *utcp) {
1304 for(int i = 0; i < utcp->nconnections; i++)
1305 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT)
1311 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1317 struct utcp *utcp = calloc(1, sizeof *utcp);
1321 utcp->accept = accept;
1322 utcp->pre_accept = pre_accept;
1331 void utcp_exit(struct utcp *utcp) {
1334 for(int i = 0; i < utcp->nconnections; i++) {
1335 if(!utcp->connections[i]->reapable)
1336 debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1337 buffer_exit(&utcp->connections[i]->sndbuf);
1338 free(utcp->connections[i]);
1340 free(utcp->connections);
1344 uint16_t utcp_get_mtu(struct utcp *utcp) {
1345 return utcp ? utcp->mtu : 0;
1348 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1349 // TODO: handle overhead of the header
1354 int utcp_get_user_timeout(struct utcp *u) {
1355 return u ? u->timeout : 0;
1358 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1360 u->timeout = timeout;
1363 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1364 return c ? c->sndbuf.maxsize : 0;
1367 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1368 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1369 return buffer_free(&c->sndbuf);
1374 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1377 c->sndbuf.maxsize = size;
1378 if(c->sndbuf.maxsize != size)
1379 c->sndbuf.maxsize = -1;
1382 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1383 return c ? c->rcvbuf.maxsize : 0;
1386 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1387 if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1388 return buffer_free(&c->rcvbuf);
1393 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1396 c->rcvbuf.maxsize = size;
1397 if(c->rcvbuf.maxsize != size)
1398 c->rcvbuf.maxsize = -1;
1401 bool utcp_get_nodelay(struct utcp_connection *c) {
1402 return c ? c->nodelay : false;
1405 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1407 c->nodelay = nodelay;
1410 bool utcp_get_keepalive(struct utcp_connection *c) {
1411 return c ? c->keepalive : false;
1414 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1416 c->keepalive = keepalive;
1419 size_t utcp_get_outq(struct utcp_connection *c) {
1420 return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1423 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1428 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1433 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
1435 utcp->accept = accept;
1436 utcp->pre_accept = pre_accept;