]> git.meshlink.io Git - utcp/blob - utcp.c
Log when we start retransmission.
[utcp] / utcp.c
1 /*
2     utcp.c -- Userspace TCP
3     Copyright (C) 2014 Guus Sliepen <guus@tinc-vpn.org>
4
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.
9
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.
14
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.
18 */
19
20 #define _GNU_SOURCE
21
22 #include <assert.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdint.h>
27 #include <stdbool.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <sys/time.h>
31 #include <sys/socket.h>
32
33 #include "utcp_priv.h"
34
35 #ifndef EBADMSG
36 #define EBADMSG         104
37 #endif
38
39 #ifndef SHUT_RDWR
40 #define SHUT_RDWR 2
41 #endif
42
43 #ifdef poll
44 #undef poll
45 #endif
46
47 #ifndef timersub
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;\
51         if((r)->tv_usec < 0)\
52                 (r)->tv_sec--, (r)->tv_usec += 1000000;\
53 } while (0)
54 #endif
55
56 #ifndef max
57 #define max(a, b) ((a) > (b) ? (a) : (b))
58 #endif
59
60 #ifdef UTCP_DEBUG
61 #include <stdarg.h>
62
63 static void debug(const char *format, ...) {
64         va_list ap;
65         va_start(ap, format);
66         vfprintf(stderr, format, ap);
67         va_end(ap);
68 }
69
70 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
71         struct hdr hdr;
72         if(len < sizeof hdr) {
73                 debug("%p %s: short packet (%zu bytes)\n", utcp, dir, len);
74                 return;
75         }
76
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);
79         if(hdr.ctl & SYN)
80                 debug("SYN");
81         if(hdr.ctl & RST)
82                 debug("RST");
83         if(hdr.ctl & FIN)
84                 debug("FIN");
85         if(hdr.ctl & ACK)
86                 debug("ACK");
87
88         if(len > sizeof hdr) {
89                 debug(" data=");
90                 for(int i = sizeof hdr; i < len; i++) {
91                         const char *data = pkt;
92                         debug("%c", data[i] >= 32 ? data[i] : '.');
93                 }
94         }
95
96         debug("\n");
97 }
98 #else
99 #define debug(...)
100 #define print_packet(...)
101 #endif
102
103 static void set_state(struct utcp_connection *c, enum state state) {
104         c->state = state;
105         if(state == ESTABLISHED)
106                 timerclear(&c->conn_timeout);
107         debug("%p new state: %s\n", c->utcp, strstate[state]);
108 }
109
110 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
111         if(seq != c->snd.last)
112                 return false;
113         switch(c->state) {
114         case FIN_WAIT_1:
115         case CLOSING:
116         case LAST_ACK:
117                 return true;
118         default:
119                 return false;
120         }
121 }
122
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]);
127 }
128
129 static int32_t seqdiff(uint32_t a, uint32_t b) {
130         return a - b;
131 }
132
133 // Buffer functions
134 // TODO: convert to ringbuffers to avoid memmove() operations.
135
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)
139                 return 0;
140
141         debug("buffer_put_at %zu %zu %zu\n", buf->used, offset, len);
142
143         size_t required = offset + len;
144         if(required > buf->maxsize) {
145                 if(offset >= buf->maxsize)
146                         return 0;
147                 abort();
148                 len = buf->maxsize - offset;
149                 required = buf->maxsize;
150         }
151
152         if(required > buf->size) {
153                 size_t newsize = buf->size;
154                 if(!newsize) {
155                         newsize = required;
156                 } else {
157                         do {
158                                 newsize *= 2;
159                         } while(newsize < buf->used + len);
160                 }
161                 if(newsize > buf->maxsize)
162                         newsize = buf->maxsize;
163                 char *newdata = realloc(buf->data, newsize);
164                 if(!newdata)
165                         return -1;
166                 buf->data = newdata;
167                 buf->size = newsize;
168         }
169
170         memcpy(buf->data + offset, data, len);
171         if(required > buf->used)
172                 buf->used = required;
173         return len;
174 }
175
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);
178 }
179
180 // Get data from the buffer. data can be NULL.
181 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
182         if(len > buf->used)
183                 len = buf->used;
184         if(data)
185                 memcpy(data, buf->data, len);
186         if(len < buf->used)
187                 memmove(buf->data, buf->data + len, buf->used - len);
188         buf->used -= len;
189         return len;
190 }
191
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)
195                 return 0;
196         if(offset + len > buf->used)
197                 len = buf->used - offset;
198         memcpy(data, buf->data + offset, len);
199         return len;
200 }
201
202 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
203         memset(buf, 0, sizeof *buf);
204         if(len) {
205                 buf->data = malloc(len);
206                 if(!buf->data)
207                         return false;
208         }
209         buf->size = len;
210         buf->maxsize = maxlen;
211         return true;
212 }
213
214 static void buffer_exit(struct buffer *buf) {
215         free(buf->data);
216         memset(buf, 0, sizeof *buf);
217 }
218
219 static uint32_t buffer_free(const struct buffer *buf) {
220         return buf->maxsize - buf->used;
221 }
222
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.
225
226 static int compare(const void *va, const void *vb) {
227         assert(va && vb);
228
229         const struct utcp_connection *a = *(struct utcp_connection **)va;
230         const struct utcp_connection *b = *(struct utcp_connection **)vb;
231
232         assert(a && b);
233         assert(a->src && b->src);
234
235         int c = (int)a->src - (int)b->src;
236         if(c)
237                 return c;
238         c = (int)a->dst - (int)b->dst;
239         return c;
240 }
241
242 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
243         if(!utcp->nconnections)
244                 return NULL;
245         struct utcp_connection key = {
246                 .src = src,
247                 .dst = dst,
248         }, *keyp = &key;
249         struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
250         return match ? *match : NULL;
251 }
252
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);
256
257         assert(cp);
258
259         int i = cp - utcp->connections;
260         memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof *cp);
261         utcp->nconnections--;
262
263         buffer_exit(&c->sndbuf);
264         free(c);
265 }
266
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
269
270         if(src) {
271                 if(find_connection(utcp, src, dst)) {
272                         errno = EADDRINUSE;
273                         return NULL;
274                 }
275         } else { // If src == 0, generate a random port number with the high bit set
276                 if(utcp->nconnections >= 32767) {
277                         errno = ENOMEM;
278                         return NULL;
279                 }
280                 src = rand() | 0x8000;
281                 while(find_connection(utcp, src, dst))
282                         src++;
283         }
284
285         // Allocate memory for the new connection
286
287         if(utcp->nconnections >= utcp->nallocated) {
288                 if(!utcp->nallocated)
289                         utcp->nallocated = 4;
290                 else
291                         utcp->nallocated *= 2;
292                 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
293                 if(!new_array)
294                         return NULL;
295                 utcp->connections = new_array;
296         }
297
298         struct utcp_connection *c = calloc(1, sizeof *c);
299         if(!c)
300                 return NULL;
301
302         if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
303                 free(c);
304                 return NULL;
305         }
306
307         if(!buffer_init(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
308                 free(c);
309                 return NULL;
310         }
311
312         // Fill in the details
313
314         c->src = src;
315         c->dst = dst;
316 #ifdef UTCP_DEBUG
317         c->snd.iss = 0;
318 #else
319         c->snd.iss = rand();
320 #endif
321         c->snd.una = c->snd.iss;
322         c->snd.nxt = c->snd.iss + 1;
323         c->rcv.wnd = utcp->mtu;
324         c->snd.last = c->snd.nxt;
325         c->snd.cwnd = utcp->mtu;
326         c->utcp = utcp;
327
328         // Add it to the sorted list of connections
329
330         utcp->connections[utcp->nconnections++] = c;
331         qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
332
333         return c;
334 }
335
336 // Update RTT variables. See RFC 6298.
337 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
338         if(!rtt) {
339                 debug("invalid rtt\n");
340                 return;
341         }
342
343         struct utcp *utcp = c->utcp;
344
345         if(!utcp->srtt) {
346                 utcp->srtt = rtt;
347                 utcp->rttvar = rtt / 2;
348                 utcp->rto = rtt + max(2 * rtt, CLOCK_GRANULARITY);
349         } else {
350                 utcp->rttvar = (utcp->rttvar * 3 + abs(utcp->srtt - rtt)) / 4;
351                 utcp->srtt = (utcp->srtt * 7 + rtt) / 8;
352                 utcp->rto = utcp->srtt + max(utcp->rttvar, CLOCK_GRANULARITY);
353         }
354
355         if(utcp->rto > MAX_RTO)
356                 utcp->rto = MAX_RTO;
357
358         debug("rtt %u srtt %u rttvar %u rto %u\n", rtt, utcp->srtt, utcp->rttvar, utcp->rto);
359 }
360
361 static void start_retransmit_timer(struct utcp_connection *c) {
362         gettimeofday(&c->rtrx_timeout, NULL);
363         c->rtrx_timeout.tv_usec += c->utcp->rto;
364         while(c->rtrx_timeout.tv_usec >= 1000000) {
365                 c->rtrx_timeout.tv_usec -= 1000000;
366                 c->rtrx_timeout.tv_sec++;
367         }
368         debug("timeout set to %lu.%06lu (%u)\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_usec, c->utcp->rto);
369 }
370
371 static void stop_retransmit_timer(struct utcp_connection *c) {
372         timerclear(&c->rtrx_timeout);
373         debug("timeout cleared\n");
374 }
375
376 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
377         struct utcp_connection *c = allocate_connection(utcp, 0, dst);
378         if(!c)
379                 return NULL;
380
381         c->recv = recv;
382         c->priv = priv;
383
384         struct hdr hdr;
385
386         hdr.src = c->src;
387         hdr.dst = c->dst;
388         hdr.seq = c->snd.iss;
389         hdr.ack = 0;
390         hdr.wnd = c->rcv.wnd;
391         hdr.ctl = SYN;
392         hdr.aux = 0;
393
394         set_state(c, SYN_SENT);
395
396         print_packet(utcp, "send", &hdr, sizeof hdr);
397         utcp->send(utcp, &hdr, sizeof hdr);
398
399         gettimeofday(&c->conn_timeout, NULL);
400         c->conn_timeout.tv_sec += utcp->timeout;
401
402         return c;
403 }
404
405 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
406         if(c->reapable || c->state != SYN_RECEIVED) {
407                 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
408                 return;
409         }
410
411         debug("%p accepted, %p %p\n", c, recv, priv);
412         c->recv = recv;
413         c->priv = priv;
414         set_state(c, ESTABLISHED);
415 }
416
417 static void ack(struct utcp_connection *c, bool sendatleastone) {
418         int32_t left = seqdiff(c->snd.last, c->snd.nxt);
419         int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
420         debug("cwndleft = %d\n", cwndleft);
421
422         assert(left >= 0);
423
424         if(cwndleft <= 0)
425                 cwndleft = 0;
426
427         if(cwndleft < left)
428                 left = cwndleft;
429
430         if(!left && !sendatleastone)
431                 return;
432
433         struct {
434                 struct hdr hdr;
435                 char data[];
436         } *pkt;
437
438         pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
439         if(!pkt)
440                 return;
441
442         pkt->hdr.src = c->src;
443         pkt->hdr.dst = c->dst;
444         pkt->hdr.ack = c->rcv.nxt;
445         pkt->hdr.wnd = c->snd.wnd;
446         pkt->hdr.ctl = ACK;
447         pkt->hdr.aux = 0;
448
449         do {
450                 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
451                 pkt->hdr.seq = c->snd.nxt;
452
453                 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
454
455                 c->snd.nxt += seglen;
456                 left -= seglen;
457
458                 if(seglen && fin_wanted(c, c->snd.nxt)) {
459                         seglen--;
460                         pkt->hdr.ctl |= FIN;
461                 }
462
463                 if(!c->rtt_start.tv_sec) {
464                         // Start RTT measurement
465                         gettimeofday(&c->rtt_start, NULL);
466                         c->rtt_seq = pkt->hdr.seq + seglen;
467                         debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
468                 }
469
470                 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
471                 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
472         } while(left);
473
474         free(pkt);
475 }
476
477 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
478         if(c->reapable) {
479                 debug("Error: send() called on closed connection %p\n", c);
480                 errno = EBADF;
481                 return -1;
482         }
483
484         switch(c->state) {
485         case CLOSED:
486         case LISTEN:
487         case SYN_SENT:
488         case SYN_RECEIVED:
489                 debug("Error: send() called on unconnected connection %p\n", c);
490                 errno = ENOTCONN;
491                 return -1;
492         case ESTABLISHED:
493         case CLOSE_WAIT:
494                 break;
495         case FIN_WAIT_1:
496         case FIN_WAIT_2:
497         case CLOSING:
498         case LAST_ACK:
499         case TIME_WAIT:
500                 debug("Error: send() called on closing connection %p\n", c);
501                 errno = EPIPE;
502                 return -1;
503         }
504
505         // Add data to send buffer
506
507         if(!len)
508                 return 0;
509
510         if(!data) {
511                 errno = EFAULT;
512                 return -1;
513         }
514
515         len = buffer_put(&c->sndbuf, data, len);
516         if(len <= 0) {
517                 errno = EWOULDBLOCK;
518                 return 0;
519         }
520
521         c->snd.last += len;
522         ack(c, false);
523         if(!timerisset(&c->rtrx_timeout))
524                 start_retransmit_timer(c);
525         return len;
526 }
527
528 static void swap_ports(struct hdr *hdr) {
529         uint16_t tmp = hdr->src;
530         hdr->src = hdr->dst;
531         hdr->dst = tmp;
532 }
533
534 static void retransmit(struct utcp_connection *c) {
535         if(c->state == CLOSED || c->snd.nxt == c->snd.una)
536                 return;
537
538         struct utcp *utcp = c->utcp;
539
540         struct {
541                 struct hdr hdr;
542                 char data[];
543         } *pkt;
544
545         pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
546         if(!pkt)
547                 return;
548
549         pkt->hdr.src = c->src;
550         pkt->hdr.dst = c->dst;
551
552         switch(c->state) {
553                 case SYN_SENT:
554                         // Send our SYN again
555                         pkt->hdr.seq = c->snd.iss;
556                         pkt->hdr.ack = 0;
557                         pkt->hdr.wnd = c->rcv.wnd;
558                         pkt->hdr.ctl = SYN;
559                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
560                         utcp->send(utcp, pkt, sizeof pkt->hdr);
561                         break;
562
563                 case SYN_RECEIVED:
564                         // Send SYNACK again
565                         pkt->hdr.seq = c->snd.nxt;
566                         pkt->hdr.ack = c->rcv.nxt;
567                         pkt->hdr.ctl = SYN | ACK;
568                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
569                         utcp->send(utcp, pkt, sizeof pkt->hdr);
570                         break;
571
572                 case ESTABLISHED:
573                 case FIN_WAIT_1:
574                 case CLOSE_WAIT:
575                 case CLOSING:
576                 case LAST_ACK:
577                         // Send unacked data again.
578                         pkt->hdr.seq = c->snd.una;
579                         pkt->hdr.ack = c->rcv.nxt;
580                         pkt->hdr.ctl = ACK;
581                         uint32_t len = seqdiff(c->snd.last, c->snd.una);
582                         if(len > utcp->mtu)
583                                 len = utcp->mtu;
584                         if(fin_wanted(c, c->snd.una + len)) {
585                                 len--;
586                                 pkt->hdr.ctl |= FIN;
587                         }
588                         c->snd.nxt = c->snd.una + len;
589                         c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
590                         buffer_copy(&c->sndbuf, pkt->data, 0, len);
591                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
592                         utcp->send(utcp, pkt, sizeof pkt->hdr + len);
593                         break;
594
595                 case CLOSED:
596                 case LISTEN:
597                 case TIME_WAIT:
598                 case FIN_WAIT_2:
599                         // We shouldn't need to retransmit anything in this state.
600 #ifdef UTCP_DEBUG
601                         abort();
602 #endif
603                         stop_retransmit_timer(c);
604                         goto cleanup;
605         }
606
607         start_retransmit_timer(c);
608         utcp->rto *= 2;
609         if(utcp->rto > MAX_RTO)
610                 utcp->rto = MAX_RTO;
611         c->rtt_start.tv_sec = 0; // invalidate RTT timer
612
613 cleanup:
614         free(pkt);
615 }
616
617 // Update receive buffer and SACK entries after consuming data.
618 static void sack_consume(struct utcp_connection *c, size_t len) {
619         debug("sack_consume %zu\n", len);
620         if(len > c->rcvbuf.used)
621                 abort();
622
623         buffer_get(&c->rcvbuf, NULL, len);
624
625         for(int i = 0; i < NSACKS && c->sacks[i].len; ) {
626                 if(len < c->sacks[i].offset) {
627                         c->sacks[i].offset -= len;
628                         i++;
629                 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
630                         c->sacks[i].offset = 0;
631                         c->sacks[i].len -= len - c->sacks[i].offset;
632                         i++;
633                 } else {
634                         if(i < NSACKS - 1) {
635                                 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof c->sacks[i]);
636                                 c->sacks[i + 1].len = 0;
637                         } else {
638                                 c->sacks[i].len = 0;
639                                 break;
640                         }
641                 }
642         }
643
644         for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
645                 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
646 }
647
648 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
649         debug("out of order packet, offset %u\n", offset);
650         // Packet loss or reordering occured. Store the data in the buffer.
651         ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
652         if(rxd < len)
653                 abort();
654
655         // Make note of where we put it.
656         for(int i = 0; i < NSACKS; i++) {
657                 if(!c->sacks[i].len) { // nothing to merge, add new entry
658                         debug("New SACK entry %d\n", i);
659                         c->sacks[i].offset = offset;
660                         c->sacks[i].len = rxd;
661                         break;
662                 } else if(offset < c->sacks[i].offset) {
663                         if(offset + rxd < c->sacks[i].offset) { // insert before
664                                 if(!c->sacks[NSACKS - 1].len) { // only if room left
665                                         debug("Insert SACK entry at %d\n", i);
666                                         memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof c->sacks[i]);
667                                         c->sacks[i].offset = offset;
668                                         c->sacks[i].len = rxd;
669                                 }
670                                 break;
671                         } else { // merge
672                                 debug("Merge with start of SACK entry at %d\n", i);
673                                 c->sacks[i].offset = offset;
674                                 break;
675                         }
676                 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
677                         if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
678                                 debug("Merge with end of SACK entry at %d\n", i);
679                                 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
680                                 // TODO: handle potential merge with next entry
681                         }
682                         break;
683                 }
684         }
685
686         for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
687                 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
688 }
689
690 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
691         // Check if we can process out-of-order data now.
692         if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
693                 debug("incoming packet len %zu connected with SACK at %u\n", len, c->sacks[0].offset);
694                 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
695                 len = max(len, c->sacks[0].offset + c->sacks[0].len);
696                 data = c->rcvbuf.data;
697         }
698
699         if(c->recv) {
700                 ssize_t rxd = c->recv(c, data, len);
701                 if(rxd != len) {
702                         // TODO: handle the application not accepting all data.
703                         abort();
704                 }
705         }
706
707         if(c->rcvbuf.used)
708                 sack_consume(c, len);
709
710         c->rcv.nxt += len;
711 }
712
713
714 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
715         uint32_t offset = seqdiff(seq, c->rcv.nxt);
716         if(offset + len > c->rcvbuf.maxsize)
717                 abort();
718
719         if(offset)
720                 handle_out_of_order(c, offset, data, len);
721         else
722                 handle_in_order(c, data, len);
723 }
724
725
726 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
727         if(!utcp) {
728                 errno = EFAULT;
729                 return -1;
730         }
731
732         if(!len)
733                 return 0;
734
735         if(!data) {
736                 errno = EFAULT;
737                 return -1;
738         }
739
740         print_packet(utcp, "recv", data, len);
741
742         // Drop packets smaller than the header
743
744         struct hdr hdr;
745         if(len < sizeof hdr) {
746                 errno = EBADMSG;
747                 return -1;
748         }
749
750         // Make a copy from the potentially unaligned data to a struct hdr
751
752         memcpy(&hdr, data, sizeof hdr);
753         data += sizeof hdr;
754         len -= sizeof hdr;
755
756         // Drop packets with an unknown CTL flag
757
758         if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
759                 errno = EBADMSG;
760                 return -1;
761         }
762
763         // Try to match the packet to an existing connection
764
765         struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
766
767         // Is it for a new connection?
768
769         if(!c) {
770                 // Ignore RST packets
771
772                 if(hdr.ctl & RST)
773                         return 0;
774
775                 // Is it a SYN packet and are we LISTENing?
776
777                 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
778                         // If we don't want to accept it, send a RST back
779                         if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
780                                 len = 1;
781                                 goto reset;
782                         }
783
784                         // Try to allocate memory, otherwise send a RST back
785                         c = allocate_connection(utcp, hdr.dst, hdr.src);
786                         if(!c) {
787                                 len = 1;
788                                 goto reset;
789                         }
790
791                         // Return SYN+ACK, go to SYN_RECEIVED state
792                         c->snd.wnd = hdr.wnd;
793                         c->rcv.irs = hdr.seq;
794                         c->rcv.nxt = c->rcv.irs + 1;
795                         set_state(c, SYN_RECEIVED);
796
797                         hdr.dst = c->dst;
798                         hdr.src = c->src;
799                         hdr.ack = c->rcv.irs + 1;
800                         hdr.seq = c->snd.iss;
801                         hdr.ctl = SYN | ACK;
802                         print_packet(c->utcp, "send", &hdr, sizeof hdr);
803                         utcp->send(utcp, &hdr, sizeof hdr);
804                 } else {
805                         // No, we don't want your packets, send a RST back
806                         len = 1;
807                         goto reset;
808                 }
809
810                 return 0;
811         }
812
813         debug("%p state %s\n", c->utcp, strstate[c->state]);
814
815         // In case this is for a CLOSED connection, ignore the packet.
816         // TODO: make it so incoming packets can never match a CLOSED connection.
817
818         if(c->state == CLOSED)
819                 return 0;
820
821         // It is for an existing connection.
822
823         uint32_t prevrcvnxt = c->rcv.nxt;
824
825         // 1. Drop invalid packets.
826
827         // 1a. Drop packets that should not happen in our current state.
828
829         switch(c->state) {
830         case SYN_SENT:
831         case SYN_RECEIVED:
832         case ESTABLISHED:
833         case FIN_WAIT_1:
834         case FIN_WAIT_2:
835         case CLOSE_WAIT:
836         case CLOSING:
837         case LAST_ACK:
838         case TIME_WAIT:
839                 break;
840         default:
841 #ifdef UTCP_DEBUG
842                 abort();
843 #endif
844                 break;
845         }
846
847         // 1b. Drop packets with a sequence number not in our receive window.
848
849         bool acceptable;
850
851         if(c->state == SYN_SENT)
852                 acceptable = true;
853
854         // TODO: handle packets overlapping c->rcv.nxt.
855 #if 1
856         // Only use this when accepting out-of-order packets.
857         else if(len == 0)
858                 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
859         else
860                 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
861 #else
862         if(c->state != SYN_SENT)
863                 acceptable = hdr.seq == c->rcv.nxt;
864 #endif
865
866         if(!acceptable) {
867                 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcvbuf.maxsize);
868                 // Ignore unacceptable RST packets.
869                 if(hdr.ctl & RST)
870                         return 0;
871                 // Otherwise, send an ACK back in the hope things improve.
872                 ack(c, true);
873                 return 0;
874         }
875
876         c->snd.wnd = hdr.wnd; // TODO: move below
877
878         // 1c. Drop packets with an invalid ACK.
879         // ackno should not roll back, and it should also not be bigger than what we ever could have sent
880         // (= snd.una + c->sndbuf.used).
881
882         if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
883                 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
884                 // Ignore unacceptable RST packets.
885                 if(hdr.ctl & RST)
886                         return 0;
887                 goto reset;
888         }
889
890         // 2. Handle RST packets
891
892         if(hdr.ctl & RST) {
893                 switch(c->state) {
894                 case SYN_SENT:
895                         if(!(hdr.ctl & ACK))
896                                 return 0;
897                         // The peer has refused our connection.
898                         set_state(c, CLOSED);
899                         errno = ECONNREFUSED;
900                         if(c->recv)
901                                 c->recv(c, NULL, 0);
902                         return 0;
903                 case SYN_RECEIVED:
904                         if(hdr.ctl & ACK)
905                                 return 0;
906                         // We haven't told the application about this connection yet. Silently delete.
907                         free_connection(c);
908                         return 0;
909                 case ESTABLISHED:
910                 case FIN_WAIT_1:
911                 case FIN_WAIT_2:
912                 case CLOSE_WAIT:
913                         if(hdr.ctl & ACK)
914                                 return 0;
915                         // The peer has aborted our connection.
916                         set_state(c, CLOSED);
917                         errno = ECONNRESET;
918                         if(c->recv)
919                                 c->recv(c, NULL, 0);
920                         return 0;
921                 case CLOSING:
922                 case LAST_ACK:
923                 case TIME_WAIT:
924                         if(hdr.ctl & ACK)
925                                 return 0;
926                         // As far as the application is concerned, the connection has already been closed.
927                         // If it has called utcp_close() already, we can immediately free this connection.
928                         if(c->reapable) {
929                                 free_connection(c);
930                                 return 0;
931                         }
932                         // Otherwise, immediately move to the CLOSED state.
933                         set_state(c, CLOSED);
934                         return 0;
935                 default:
936 #ifdef UTCP_DEBUG
937                         abort();
938 #endif
939                         break;
940                 }
941         }
942
943         // 3. Advance snd.una
944
945         uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
946         prevrcvnxt = c->rcv.nxt;
947
948         if(advanced) {
949                 // RTT measurement
950                 if(c->rtt_start.tv_sec) {
951                         if(c->rtt_seq == hdr.ack) {
952                                 struct timeval now, diff;
953                                 gettimeofday(&now, NULL);
954                                 timersub(&now, &c->rtt_start, &diff);
955                                 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
956                                 c->rtt_start.tv_sec = 0;
957                         } else if(c->rtt_seq < hdr.ack) {
958                                 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
959                                 c->rtt_start.tv_sec = 0;
960                         }
961                 }
962
963                 int32_t data_acked = advanced;
964
965                 switch(c->state) {
966                         case SYN_SENT:
967                         case SYN_RECEIVED:
968                                 data_acked--;
969                                 break;
970                         // TODO: handle FIN as well.
971                         default:
972                                 break;
973                 }
974
975                 assert(data_acked >= 0);
976
977                 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
978                 assert(data_acked <= bufused);
979
980                 if(data_acked)
981                         buffer_get(&c->sndbuf, NULL, data_acked);
982
983                 // Also advance snd.nxt if possible
984                 if(seqdiff(c->snd.nxt, hdr.ack) < 0)
985                         c->snd.nxt = hdr.ack;
986
987                 c->snd.una = hdr.ack;
988
989                 c->dupack = 0;
990                 c->snd.cwnd += utcp->mtu;
991                 if(c->snd.cwnd > c->sndbuf.maxsize)
992                         c->snd.cwnd = c->sndbuf.maxsize;
993
994                 // Check if we have sent a FIN that is now ACKed.
995                 switch(c->state) {
996                 case FIN_WAIT_1:
997                         if(c->snd.una == c->snd.last)
998                                 set_state(c, FIN_WAIT_2);
999                         break;
1000                 case CLOSING:
1001                         if(c->snd.una == c->snd.last) {
1002                                 gettimeofday(&c->conn_timeout, NULL);
1003                                 c->conn_timeout.tv_sec += 60;
1004                                 set_state(c, TIME_WAIT);
1005                         }
1006                         break;
1007                 default:
1008                         break;
1009                 }
1010         } else {
1011                 if(!len) {
1012                         c->dupack++;
1013                         if(c->dupack == 3) {
1014                                 debug("Triplicate ACK\n");
1015                                 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1016                                 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1017                                 //Reset the congestion window so we wait for ACKs.
1018                                 c->snd.nxt = c->snd.una;
1019                                 c->snd.cwnd = utcp->mtu;
1020                         }
1021                 }
1022         }
1023
1024         // 4. Update timers
1025
1026         if(advanced) {
1027                 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
1028                 if(c->snd.una == c->snd.last)
1029                         stop_retransmit_timer(c);
1030                 else
1031                         start_retransmit_timer(c);
1032         }
1033
1034         // 5. Process SYN stuff
1035
1036         if(hdr.ctl & SYN) {
1037                 switch(c->state) {
1038                 case SYN_SENT:
1039                         // This is a SYNACK. It should always have ACKed the SYN.
1040                         if(!advanced)
1041                                 goto reset;
1042                         c->rcv.irs = hdr.seq;
1043                         c->rcv.nxt = hdr.seq;
1044                         set_state(c, ESTABLISHED);
1045                         // TODO: notify application of this somehow.
1046                         break;
1047                 case SYN_RECEIVED:
1048                 case ESTABLISHED:
1049                 case FIN_WAIT_1:
1050                 case FIN_WAIT_2:
1051                 case CLOSE_WAIT:
1052                 case CLOSING:
1053                 case LAST_ACK:
1054                 case TIME_WAIT:
1055                         // Ehm, no. We should never receive a second SYN.
1056                         goto reset;
1057                 default:
1058 #ifdef UTCP_DEBUG
1059                         abort();
1060 #endif
1061                         return 0;
1062                 }
1063
1064                 // SYN counts as one sequence number
1065                 c->rcv.nxt++;
1066         }
1067
1068         // 6. Process new data
1069
1070         if(c->state == SYN_RECEIVED) {
1071                 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1072                 if(!advanced)
1073                         goto reset;
1074
1075                 // Are we still LISTENing?
1076                 if(utcp->accept)
1077                         utcp->accept(c, c->src);
1078
1079                 if(c->state != ESTABLISHED) {
1080                         set_state(c, CLOSED);
1081                         c->reapable = true;
1082                         goto reset;
1083                 }
1084         }
1085
1086         if(len) {
1087                 switch(c->state) {
1088                 case SYN_SENT:
1089                 case SYN_RECEIVED:
1090                         // This should never happen.
1091 #ifdef UTCP_DEBUG
1092                         abort();
1093 #endif
1094                         return 0;
1095                 case ESTABLISHED:
1096                 case FIN_WAIT_1:
1097                 case FIN_WAIT_2:
1098                         break;
1099                 case CLOSE_WAIT:
1100                 case CLOSING:
1101                 case LAST_ACK:
1102                 case TIME_WAIT:
1103                         // Ehm no, We should never receive more data after a FIN.
1104                         goto reset;
1105                 default:
1106 #ifdef UTCP_DEBUG
1107                         abort();
1108 #endif
1109                         return 0;
1110                 }
1111
1112                 handle_incoming_data(c, hdr.seq, data, len);
1113         }
1114
1115         // 7. Process FIN stuff
1116
1117         if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1118                 switch(c->state) {
1119                 case SYN_SENT:
1120                 case SYN_RECEIVED:
1121                         // This should never happen.
1122 #ifdef UTCP_DEBUG
1123                         abort();
1124 #endif
1125                         break;
1126                 case ESTABLISHED:
1127                         set_state(c, CLOSE_WAIT);
1128                         break;
1129                 case FIN_WAIT_1:
1130                         set_state(c, CLOSING);
1131                         break;
1132                 case FIN_WAIT_2:
1133                         gettimeofday(&c->conn_timeout, NULL);
1134                         c->conn_timeout.tv_sec += 60;
1135                         set_state(c, TIME_WAIT);
1136                         break;
1137                 case CLOSE_WAIT:
1138                 case CLOSING:
1139                 case LAST_ACK:
1140                 case TIME_WAIT:
1141                         // Ehm, no. We should never receive a second FIN.
1142                         goto reset;
1143                 default:
1144 #ifdef UTCP_DEBUG
1145                         abort();
1146 #endif
1147                         break;
1148                 }
1149
1150                 // FIN counts as one sequence number
1151                 c->rcv.nxt++;
1152                 len++;
1153
1154                 // Inform the application that the peer closed the connection.
1155                 if(c->recv) {
1156                         errno = 0;
1157                         c->recv(c, NULL, 0);
1158                 }
1159         }
1160
1161         // Now we send something back if:
1162         // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1163         //   -> sendatleastone = true
1164         // - or we got an ack, so we should maybe send a bit more data
1165         //   -> sendatleastone = false
1166
1167         ack(c, prevrcvnxt != c->rcv.nxt);
1168         return 0;
1169
1170 reset:
1171         swap_ports(&hdr);
1172         hdr.wnd = 0;
1173         if(hdr.ctl & ACK) {
1174                 hdr.seq = hdr.ack;
1175                 hdr.ctl = RST;
1176         } else {
1177                 hdr.ack = hdr.seq + len;
1178                 hdr.seq = 0;
1179                 hdr.ctl = RST | ACK;
1180         }
1181         print_packet(utcp, "send", &hdr, sizeof hdr);
1182         utcp->send(utcp, &hdr, sizeof hdr);
1183         return 0;
1184
1185 }
1186
1187 int utcp_shutdown(struct utcp_connection *c, int dir) {
1188         debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1189         if(!c) {
1190                 errno = EFAULT;
1191                 return -1;
1192         }
1193
1194         if(c->reapable) {
1195                 debug("Error: shutdown() called on closed connection %p\n", c);
1196                 errno = EBADF;
1197                 return -1;
1198         }
1199
1200         if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1201                 errno = EINVAL;
1202                 return -1;
1203         }
1204
1205         // TCP does not have a provision for stopping incoming packets.
1206         // The best we can do is to just ignore them.
1207         if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR)
1208                 c->recv = NULL;
1209
1210         // The rest of the code deals with shutting down writes.
1211         if(dir == UTCP_SHUT_RD)
1212                 return 0;
1213
1214         switch(c->state) {
1215         case CLOSED:
1216         case LISTEN:
1217                 errno = ENOTCONN;
1218                 return -1;
1219
1220         case SYN_SENT:
1221                 set_state(c, CLOSED);
1222                 return 0;
1223
1224         case SYN_RECEIVED:
1225         case ESTABLISHED:
1226                 set_state(c, FIN_WAIT_1);
1227                 break;
1228         case FIN_WAIT_1:
1229         case FIN_WAIT_2:
1230                 return 0;
1231         case CLOSE_WAIT:
1232                 set_state(c, CLOSING);
1233                 break;
1234
1235         case CLOSING:
1236         case LAST_ACK:
1237         case TIME_WAIT:
1238                 return 0;
1239         }
1240
1241         c->snd.last++;
1242
1243         ack(c, false);
1244         return 0;
1245 }
1246
1247 int utcp_close(struct utcp_connection *c) {
1248         if(utcp_shutdown(c, SHUT_RDWR))
1249                 return -1;
1250         c->recv = NULL;
1251         c->poll = NULL;
1252         c->reapable = true;
1253         return 0;
1254 }
1255
1256 int utcp_abort(struct utcp_connection *c) {
1257         if(!c) {
1258                 errno = EFAULT;
1259                 return -1;
1260         }
1261
1262         if(c->reapable) {
1263                 debug("Error: abort() called on closed connection %p\n", c);
1264                 errno = EBADF;
1265                 return -1;
1266         }
1267
1268         c->recv = NULL;
1269         c->poll = NULL;
1270         c->reapable = true;
1271
1272         switch(c->state) {
1273         case CLOSED:
1274                 return 0;
1275         case LISTEN:
1276         case SYN_SENT:
1277         case CLOSING:
1278         case LAST_ACK:
1279         case TIME_WAIT:
1280                 set_state(c, CLOSED);
1281                 return 0;
1282
1283         case SYN_RECEIVED:
1284         case ESTABLISHED:
1285         case FIN_WAIT_1:
1286         case FIN_WAIT_2:
1287         case CLOSE_WAIT:
1288                 set_state(c, CLOSED);
1289                 break;
1290         }
1291
1292         // Send RST
1293
1294         struct hdr hdr;
1295
1296         hdr.src = c->src;
1297         hdr.dst = c->dst;
1298         hdr.seq = c->snd.nxt;
1299         hdr.ack = 0;
1300         hdr.wnd = 0;
1301         hdr.ctl = RST;
1302
1303         print_packet(c->utcp, "send", &hdr, sizeof hdr);
1304         c->utcp->send(c->utcp, &hdr, sizeof hdr);
1305         return 0;
1306 }
1307
1308 /* Handle timeouts.
1309  * One call to this function will loop through all connections,
1310  * checking if something needs to be resent or not.
1311  * The return value is the time to the next timeout in milliseconds,
1312  * or maybe a negative value if the timeout is infinite.
1313  */
1314 struct timeval utcp_timeout(struct utcp *utcp) {
1315         struct timeval now;
1316         gettimeofday(&now, NULL);
1317         struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1318
1319         for(int i = 0; i < utcp->nconnections; i++) {
1320                 struct utcp_connection *c = utcp->connections[i];
1321                 if(!c)
1322                         continue;
1323
1324                 // delete connections that have been utcp_close()d.
1325                 if(c->state == CLOSED) {
1326                         if(c->reapable) {
1327                                 debug("Reaping %p\n", c);
1328                                 free_connection(c);
1329                                 i--;
1330                         }
1331                         continue;
1332                 }
1333
1334                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1335                         errno = ETIMEDOUT;
1336                         c->state = CLOSED;
1337                         if(c->recv)
1338                                 c->recv(c, NULL, 0);
1339                         continue;
1340                 }
1341
1342                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1343                         debug("retransmit()\n");
1344                         retransmit(c);
1345                 }
1346
1347                 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1348                         c->poll(c, buffer_free(&c->sndbuf));
1349
1350                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1351                         next = c->conn_timeout;
1352
1353                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1354                         next = c->rtrx_timeout;
1355         }
1356
1357         struct timeval diff;
1358         timersub(&next, &now, &diff);
1359         return diff;
1360 }
1361
1362 bool utcp_is_active(struct utcp *utcp) {
1363         if(!utcp)
1364                 return false;
1365
1366         for(int i = 0; i < utcp->nconnections; i++)
1367                 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT)
1368                         return true;
1369
1370         return false;
1371 }
1372
1373 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1374         if(!send) {
1375                 errno = EFAULT;
1376                 return NULL;
1377         }
1378
1379         struct utcp *utcp = calloc(1, sizeof *utcp);
1380         if(!utcp)
1381                 return NULL;
1382
1383         utcp->accept = accept;
1384         utcp->pre_accept = pre_accept;
1385         utcp->send = send;
1386         utcp->priv = priv;
1387         utcp->mtu = DEFAULT_MTU;
1388         utcp->timeout = DEFAULT_USER_TIMEOUT; // s
1389         utcp->rto = START_RTO; // us
1390
1391         return utcp;
1392 }
1393
1394 void utcp_exit(struct utcp *utcp) {
1395         if(!utcp)
1396                 return;
1397         for(int i = 0; i < utcp->nconnections; i++) {
1398                 if(!utcp->connections[i]->reapable)
1399                         debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1400                 buffer_exit(&utcp->connections[i]->sndbuf);
1401                 free(utcp->connections[i]);
1402         }
1403         free(utcp->connections);
1404         free(utcp);
1405 }
1406
1407 uint16_t utcp_get_mtu(struct utcp *utcp) {
1408         return utcp ? utcp->mtu : 0;
1409 }
1410
1411 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1412         // TODO: handle overhead of the header
1413         if(utcp)
1414                 utcp->mtu = mtu;
1415 }
1416
1417 int utcp_get_user_timeout(struct utcp *u) {
1418         return u ? u->timeout : 0;
1419 }
1420
1421 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1422         if(u)
1423                 u->timeout = timeout;
1424 }
1425
1426 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1427         return c ? c->sndbuf.maxsize : 0;
1428 }
1429
1430 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1431         if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1432                 return buffer_free(&c->sndbuf);
1433         else
1434                 return 0;
1435 }
1436
1437 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1438         if(!c)
1439                 return;
1440         c->sndbuf.maxsize = size;
1441         if(c->sndbuf.maxsize != size)
1442                 c->sndbuf.maxsize = -1;
1443 }
1444
1445 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1446         return c ? c->rcvbuf.maxsize : 0;
1447 }
1448
1449 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1450         if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1451                 return buffer_free(&c->rcvbuf);
1452         else
1453                 return 0;
1454 }
1455
1456 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1457         if(!c)
1458                 return;
1459         c->rcvbuf.maxsize = size;
1460         if(c->rcvbuf.maxsize != size)
1461                 c->rcvbuf.maxsize = -1;
1462 }
1463
1464 bool utcp_get_nodelay(struct utcp_connection *c) {
1465         return c ? c->nodelay : false;
1466 }
1467
1468 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1469         if(c)
1470                 c->nodelay = nodelay;
1471 }
1472
1473 bool utcp_get_keepalive(struct utcp_connection *c) {
1474         return c ? c->keepalive : false;
1475 }
1476
1477 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1478         if(c)
1479                 c->keepalive = keepalive;
1480 }
1481
1482 size_t utcp_get_outq(struct utcp_connection *c) {
1483         return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1484 }
1485
1486 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1487         if(c)
1488                 c->recv = recv;
1489 }
1490
1491 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1492         if(c)
1493                 c->poll = poll;
1494 }
1495
1496 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
1497         if(utcp) {
1498                 utcp->accept = accept;
1499                 utcp->pre_accept = pre_accept;
1500         }
1501 }