]> git.meshlink.io Git - utcp/blob - utcp.c
Use the calculated RTO value to set the retransmission timer.
[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 &&
883                         ((seqdiff(hdr.ack, c->snd.una + c->sndbuf.used) > 0 &&
884                           seqdiff(hdr.ack, c->snd.nxt) > 0) // TODO: simplify this if
885                          || seqdiff(hdr.ack, c->snd.una) < 0)) {
886                 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
887                 // Ignore unacceptable RST packets.
888                 if(hdr.ctl & RST)
889                         return 0;
890                 goto reset;
891         }
892
893         // 2. Handle RST packets
894
895         if(hdr.ctl & RST) {
896                 switch(c->state) {
897                 case SYN_SENT:
898                         if(!(hdr.ctl & ACK))
899                                 return 0;
900                         // The peer has refused our connection.
901                         set_state(c, CLOSED);
902                         errno = ECONNREFUSED;
903                         if(c->recv)
904                                 c->recv(c, NULL, 0);
905                         return 0;
906                 case SYN_RECEIVED:
907                         if(hdr.ctl & ACK)
908                                 return 0;
909                         // We haven't told the application about this connection yet. Silently delete.
910                         free_connection(c);
911                         return 0;
912                 case ESTABLISHED:
913                 case FIN_WAIT_1:
914                 case FIN_WAIT_2:
915                 case CLOSE_WAIT:
916                         if(hdr.ctl & ACK)
917                                 return 0;
918                         // The peer has aborted our connection.
919                         set_state(c, CLOSED);
920                         errno = ECONNRESET;
921                         if(c->recv)
922                                 c->recv(c, NULL, 0);
923                         return 0;
924                 case CLOSING:
925                 case LAST_ACK:
926                 case TIME_WAIT:
927                         if(hdr.ctl & ACK)
928                                 return 0;
929                         // As far as the application is concerned, the connection has already been closed.
930                         // If it has called utcp_close() already, we can immediately free this connection.
931                         if(c->reapable) {
932                                 free_connection(c);
933                                 return 0;
934                         }
935                         // Otherwise, immediately move to the CLOSED state.
936                         set_state(c, CLOSED);
937                         return 0;
938                 default:
939 #ifdef UTCP_DEBUG
940                         abort();
941 #endif
942                         break;
943                 }
944         }
945
946         // 3. Advance snd.una
947
948         uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
949         prevrcvnxt = c->rcv.nxt;
950
951         if(advanced) {
952                 // RTT measurement
953                 if(c->rtt_start.tv_sec) {
954                         if(c->rtt_seq == hdr.ack) {
955                                 struct timeval now, diff;
956                                 gettimeofday(&now, NULL);
957                                 timersub(&now, &c->rtt_start, &diff);
958                                 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
959                                 c->rtt_start.tv_sec = 0;
960                         } else if(c->rtt_seq < hdr.ack) {
961                                 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
962                                 c->rtt_start.tv_sec = 0;
963                         }
964                 }
965
966                 int32_t data_acked = advanced;
967
968                 switch(c->state) {
969                         case SYN_SENT:
970                         case SYN_RECEIVED:
971                                 data_acked--;
972                                 break;
973                         // TODO: handle FIN as well.
974                         default:
975                                 break;
976                 }
977
978                 assert(data_acked >= 0);
979
980                 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
981                 assert(data_acked <= bufused);
982
983                 if(data_acked)
984                         buffer_get(&c->sndbuf, NULL, data_acked);
985
986                 // Also advance snd.nxt if possible
987                 if(seqdiff(c->snd.nxt, hdr.ack) < 0)
988                         c->snd.nxt = hdr.ack;
989
990                 c->snd.una = hdr.ack;
991
992                 c->dupack = 0;
993                 c->snd.cwnd += utcp->mtu;
994                 if(c->snd.cwnd > c->sndbuf.maxsize)
995                         c->snd.cwnd = c->sndbuf.maxsize;
996
997                 // Check if we have sent a FIN that is now ACKed.
998                 switch(c->state) {
999                 case FIN_WAIT_1:
1000                         if(c->snd.una == c->snd.last)
1001                                 set_state(c, FIN_WAIT_2);
1002                         break;
1003                 case CLOSING:
1004                         if(c->snd.una == c->snd.last) {
1005                                 gettimeofday(&c->conn_timeout, NULL);
1006                                 c->conn_timeout.tv_sec += 60;
1007                                 set_state(c, TIME_WAIT);
1008                         }
1009                         break;
1010                 default:
1011                         break;
1012                 }
1013         } else {
1014                 if(!len) {
1015                         c->dupack++;
1016                         if(c->dupack == 3) {
1017                                 debug("Triplicate ACK\n");
1018                                 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1019                                 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1020                                 //Reset the congestion window so we wait for ACKs.
1021                                 c->snd.nxt = c->snd.una;
1022                                 c->snd.cwnd = utcp->mtu;
1023                         }
1024                 }
1025         }
1026
1027         // 4. Update timers
1028
1029         if(advanced) {
1030                 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
1031                 if(c->snd.una == c->snd.last)
1032                         stop_retransmit_timer(c);
1033                 else
1034                         start_retransmit_timer(c);
1035         }
1036
1037         // 5. Process SYN stuff
1038
1039         if(hdr.ctl & SYN) {
1040                 switch(c->state) {
1041                 case SYN_SENT:
1042                         // This is a SYNACK. It should always have ACKed the SYN.
1043                         if(!advanced)
1044                                 goto reset;
1045                         c->rcv.irs = hdr.seq;
1046                         c->rcv.nxt = hdr.seq;
1047                         set_state(c, ESTABLISHED);
1048                         // TODO: notify application of this somehow.
1049                         break;
1050                 case SYN_RECEIVED:
1051                 case ESTABLISHED:
1052                 case FIN_WAIT_1:
1053                 case FIN_WAIT_2:
1054                 case CLOSE_WAIT:
1055                 case CLOSING:
1056                 case LAST_ACK:
1057                 case TIME_WAIT:
1058                         // Ehm, no. We should never receive a second SYN.
1059                         goto reset;
1060                 default:
1061 #ifdef UTCP_DEBUG
1062                         abort();
1063 #endif
1064                         return 0;
1065                 }
1066
1067                 // SYN counts as one sequence number
1068                 c->rcv.nxt++;
1069         }
1070
1071         // 6. Process new data
1072
1073         if(c->state == SYN_RECEIVED) {
1074                 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1075                 if(!advanced)
1076                         goto reset;
1077
1078                 // Are we still LISTENing?
1079                 if(utcp->accept)
1080                         utcp->accept(c, c->src);
1081
1082                 if(c->state != ESTABLISHED) {
1083                         set_state(c, CLOSED);
1084                         c->reapable = true;
1085                         goto reset;
1086                 }
1087         }
1088
1089         if(len) {
1090                 switch(c->state) {
1091                 case SYN_SENT:
1092                 case SYN_RECEIVED:
1093                         // This should never happen.
1094 #ifdef UTCP_DEBUG
1095                         abort();
1096 #endif
1097                         return 0;
1098                 case ESTABLISHED:
1099                 case FIN_WAIT_1:
1100                 case FIN_WAIT_2:
1101                         break;
1102                 case CLOSE_WAIT:
1103                 case CLOSING:
1104                 case LAST_ACK:
1105                 case TIME_WAIT:
1106                         // Ehm no, We should never receive more data after a FIN.
1107                         goto reset;
1108                 default:
1109 #ifdef UTCP_DEBUG
1110                         abort();
1111 #endif
1112                         return 0;
1113                 }
1114
1115                 handle_incoming_data(c, hdr.seq, data, len);
1116         }
1117
1118         // 7. Process FIN stuff
1119
1120         if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1121                 switch(c->state) {
1122                 case SYN_SENT:
1123                 case SYN_RECEIVED:
1124                         // This should never happen.
1125 #ifdef UTCP_DEBUG
1126                         abort();
1127 #endif
1128                         break;
1129                 case ESTABLISHED:
1130                         set_state(c, CLOSE_WAIT);
1131                         break;
1132                 case FIN_WAIT_1:
1133                         set_state(c, CLOSING);
1134                         break;
1135                 case FIN_WAIT_2:
1136                         gettimeofday(&c->conn_timeout, NULL);
1137                         c->conn_timeout.tv_sec += 60;
1138                         set_state(c, TIME_WAIT);
1139                         break;
1140                 case CLOSE_WAIT:
1141                 case CLOSING:
1142                 case LAST_ACK:
1143                 case TIME_WAIT:
1144                         // Ehm, no. We should never receive a second FIN.
1145                         goto reset;
1146                 default:
1147 #ifdef UTCP_DEBUG
1148                         abort();
1149 #endif
1150                         break;
1151                 }
1152
1153                 // FIN counts as one sequence number
1154                 c->rcv.nxt++;
1155                 len++;
1156
1157                 // Inform the application that the peer closed the connection.
1158                 if(c->recv) {
1159                         errno = 0;
1160                         c->recv(c, NULL, 0);
1161                 }
1162         }
1163
1164         // Now we send something back if:
1165         // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1166         //   -> sendatleastone = true
1167         // - or we got an ack, so we should maybe send a bit more data
1168         //   -> sendatleastone = false
1169
1170 ack:
1171         ack(c, prevrcvnxt != c->rcv.nxt);
1172         return 0;
1173
1174 reset:
1175         swap_ports(&hdr);
1176         hdr.wnd = 0;
1177         if(hdr.ctl & ACK) {
1178                 hdr.seq = hdr.ack;
1179                 hdr.ctl = RST;
1180         } else {
1181                 hdr.ack = hdr.seq + len;
1182                 hdr.seq = 0;
1183                 hdr.ctl = RST | ACK;
1184         }
1185         print_packet(utcp, "send", &hdr, sizeof hdr);
1186         utcp->send(utcp, &hdr, sizeof hdr);
1187         return 0;
1188
1189 }
1190
1191 int utcp_shutdown(struct utcp_connection *c, int dir) {
1192         debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1193         if(!c) {
1194                 errno = EFAULT;
1195                 return -1;
1196         }
1197
1198         if(c->reapable) {
1199                 debug("Error: shutdown() called on closed connection %p\n", c);
1200                 errno = EBADF;
1201                 return -1;
1202         }
1203
1204         if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1205                 errno = EINVAL;
1206                 return -1;
1207         }
1208
1209         // TCP does not have a provision for stopping incoming packets.
1210         // The best we can do is to just ignore them.
1211         if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR)
1212                 c->recv = NULL;
1213
1214         // The rest of the code deals with shutting down writes.
1215         if(dir == UTCP_SHUT_RD)
1216                 return 0;
1217
1218         switch(c->state) {
1219         case CLOSED:
1220         case LISTEN:
1221                 errno = ENOTCONN;
1222                 return -1;
1223
1224         case SYN_SENT:
1225                 set_state(c, CLOSED);
1226                 return 0;
1227
1228         case SYN_RECEIVED:
1229         case ESTABLISHED:
1230                 set_state(c, FIN_WAIT_1);
1231                 break;
1232         case FIN_WAIT_1:
1233         case FIN_WAIT_2:
1234                 return 0;
1235         case CLOSE_WAIT:
1236                 set_state(c, CLOSING);
1237                 break;
1238
1239         case CLOSING:
1240         case LAST_ACK:
1241         case TIME_WAIT:
1242                 return 0;
1243         }
1244
1245         c->snd.last++;
1246
1247         ack(c, false);
1248         return 0;
1249 }
1250
1251 int utcp_close(struct utcp_connection *c) {
1252         if(utcp_shutdown(c, SHUT_RDWR))
1253                 return -1;
1254         c->recv = NULL;
1255         c->poll = NULL;
1256         c->reapable = true;
1257         return 0;
1258 }
1259
1260 int utcp_abort(struct utcp_connection *c) {
1261         if(!c) {
1262                 errno = EFAULT;
1263                 return -1;
1264         }
1265
1266         if(c->reapable) {
1267                 debug("Error: abort() called on closed connection %p\n", c);
1268                 errno = EBADF;
1269                 return -1;
1270         }
1271
1272         c->recv = NULL;
1273         c->poll = NULL;
1274         c->reapable = true;
1275
1276         switch(c->state) {
1277         case CLOSED:
1278                 return 0;
1279         case LISTEN:
1280         case SYN_SENT:
1281         case CLOSING:
1282         case LAST_ACK:
1283         case TIME_WAIT:
1284                 set_state(c, CLOSED);
1285                 return 0;
1286
1287         case SYN_RECEIVED:
1288         case ESTABLISHED:
1289         case FIN_WAIT_1:
1290         case FIN_WAIT_2:
1291         case CLOSE_WAIT:
1292                 set_state(c, CLOSED);
1293                 break;
1294         }
1295
1296         // Send RST
1297
1298         struct hdr hdr;
1299
1300         hdr.src = c->src;
1301         hdr.dst = c->dst;
1302         hdr.seq = c->snd.nxt;
1303         hdr.ack = 0;
1304         hdr.wnd = 0;
1305         hdr.ctl = RST;
1306
1307         print_packet(c->utcp, "send", &hdr, sizeof hdr);
1308         c->utcp->send(c->utcp, &hdr, sizeof hdr);
1309         return 0;
1310 }
1311
1312 /* Handle timeouts.
1313  * One call to this function will loop through all connections,
1314  * checking if something needs to be resent or not.
1315  * The return value is the time to the next timeout in milliseconds,
1316  * or maybe a negative value if the timeout is infinite.
1317  */
1318 struct timeval utcp_timeout(struct utcp *utcp) {
1319         struct timeval now;
1320         gettimeofday(&now, NULL);
1321         struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1322
1323         for(int i = 0; i < utcp->nconnections; i++) {
1324                 struct utcp_connection *c = utcp->connections[i];
1325                 if(!c)
1326                         continue;
1327
1328                 if(c->state == CLOSED) {
1329                         if(c->reapable) {
1330                                 debug("Reaping %p\n", c);
1331                                 free_connection(c);
1332                                 i--;
1333                         }
1334                         continue;
1335                 }
1336
1337                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1338                         errno = ETIMEDOUT;
1339                         c->state = CLOSED;
1340                         if(c->recv)
1341                                 c->recv(c, NULL, 0);
1342                         continue;
1343                 }
1344
1345                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1346                         retransmit(c);
1347                 }
1348
1349                 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1350                         c->poll(c, buffer_free(&c->sndbuf));
1351
1352                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1353                         next = c->conn_timeout;
1354
1355                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1356                         next = c->rtrx_timeout;
1357         }
1358
1359         struct timeval diff;
1360         timersub(&next, &now, &diff);
1361         return diff;
1362 }
1363
1364 bool utcp_is_active(struct utcp *utcp) {
1365         if(!utcp)
1366                 return false;
1367
1368         for(int i = 0; i < utcp->nconnections; i++)
1369                 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT)
1370                         return true;
1371
1372         return false;
1373 }
1374
1375 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1376         if(!send) {
1377                 errno = EFAULT;
1378                 return NULL;
1379         }
1380
1381         struct utcp *utcp = calloc(1, sizeof *utcp);
1382         if(!utcp)
1383                 return NULL;
1384
1385         utcp->accept = accept;
1386         utcp->pre_accept = pre_accept;
1387         utcp->send = send;
1388         utcp->priv = priv;
1389         utcp->mtu = DEFAULT_MTU;
1390         utcp->timeout = DEFAULT_USER_TIMEOUT; // s
1391         utcp->rto = START_RTO; // us
1392
1393         return utcp;
1394 }
1395
1396 void utcp_exit(struct utcp *utcp) {
1397         if(!utcp)
1398                 return;
1399         for(int i = 0; i < utcp->nconnections; i++) {
1400                 if(!utcp->connections[i]->reapable)
1401                         debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1402                 buffer_exit(&utcp->connections[i]->sndbuf);
1403                 free(utcp->connections[i]);
1404         }
1405         free(utcp->connections);
1406         free(utcp);
1407 }
1408
1409 uint16_t utcp_get_mtu(struct utcp *utcp) {
1410         return utcp ? utcp->mtu : 0;
1411 }
1412
1413 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1414         // TODO: handle overhead of the header
1415         if(utcp)
1416                 utcp->mtu = mtu;
1417 }
1418
1419 int utcp_get_user_timeout(struct utcp *u) {
1420         return u ? u->timeout : 0;
1421 }
1422
1423 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1424         if(u)
1425                 u->timeout = timeout;
1426 }
1427
1428 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1429         return c ? c->sndbuf.maxsize : 0;
1430 }
1431
1432 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1433         if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1434                 return buffer_free(&c->sndbuf);
1435         else
1436                 return 0;
1437 }
1438
1439 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1440         if(!c)
1441                 return;
1442         c->sndbuf.maxsize = size;
1443         if(c->sndbuf.maxsize != size)
1444                 c->sndbuf.maxsize = -1;
1445 }
1446
1447 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1448         return c ? c->rcvbuf.maxsize : 0;
1449 }
1450
1451 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1452         if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1453                 return buffer_free(&c->rcvbuf);
1454         else
1455                 return 0;
1456 }
1457
1458 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1459         if(!c)
1460                 return;
1461         c->rcvbuf.maxsize = size;
1462         if(c->rcvbuf.maxsize != size)
1463                 c->rcvbuf.maxsize = -1;
1464 }
1465
1466 bool utcp_get_nodelay(struct utcp_connection *c) {
1467         return c ? c->nodelay : false;
1468 }
1469
1470 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1471         if(c)
1472                 c->nodelay = nodelay;
1473 }
1474
1475 bool utcp_get_keepalive(struct utcp_connection *c) {
1476         return c ? c->keepalive : false;
1477 }
1478
1479 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1480         if(c)
1481                 c->keepalive = keepalive;
1482 }
1483
1484 size_t utcp_get_outq(struct utcp_connection *c) {
1485         return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1486 }
1487
1488 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1489         if(c)
1490                 c->recv = recv;
1491 }
1492
1493 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1494         if(c)
1495                 c->poll = poll;
1496 }
1497
1498 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
1499         if(utcp) {
1500                 utcp->accept = accept;
1501                 utcp->pre_accept = pre_accept;
1502         }
1503 }