]> git.meshlink.io Git - utcp/blob - utcp.c
Measure RTT and calculate RTO.
[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 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
362         struct utcp_connection *c = allocate_connection(utcp, 0, dst);
363         if(!c)
364                 return NULL;
365
366         c->recv = recv;
367         c->priv = priv;
368
369         struct hdr hdr;
370
371         hdr.src = c->src;
372         hdr.dst = c->dst;
373         hdr.seq = c->snd.iss;
374         hdr.ack = 0;
375         hdr.wnd = c->rcv.wnd;
376         hdr.ctl = SYN;
377         hdr.aux = 0;
378
379         set_state(c, SYN_SENT);
380
381         print_packet(utcp, "send", &hdr, sizeof hdr);
382         utcp->send(utcp, &hdr, sizeof hdr);
383
384         gettimeofday(&c->conn_timeout, NULL);
385         c->conn_timeout.tv_sec += utcp->timeout;
386
387         return c;
388 }
389
390 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
391         if(c->reapable || c->state != SYN_RECEIVED) {
392                 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
393                 return;
394         }
395
396         debug("%p accepted, %p %p\n", c, recv, priv);
397         c->recv = recv;
398         c->priv = priv;
399         set_state(c, ESTABLISHED);
400 }
401
402 static void ack(struct utcp_connection *c, bool sendatleastone) {
403         int32_t left = seqdiff(c->snd.last, c->snd.nxt);
404         int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
405         debug("cwndleft = %d\n", cwndleft);
406
407         assert(left >= 0);
408
409         if(cwndleft <= 0)
410                 cwndleft = 0;
411
412         if(cwndleft < left)
413                 left = cwndleft;
414
415         if(!left && !sendatleastone)
416                 return;
417
418         struct {
419                 struct hdr hdr;
420                 char data[];
421         } *pkt;
422
423         pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
424         if(!pkt)
425                 return;
426
427         pkt->hdr.src = c->src;
428         pkt->hdr.dst = c->dst;
429         pkt->hdr.ack = c->rcv.nxt;
430         pkt->hdr.wnd = c->snd.wnd;
431         pkt->hdr.ctl = ACK;
432         pkt->hdr.aux = 0;
433
434         do {
435                 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
436                 pkt->hdr.seq = c->snd.nxt;
437
438                 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
439
440                 c->snd.nxt += seglen;
441                 left -= seglen;
442
443                 if(seglen && fin_wanted(c, c->snd.nxt)) {
444                         seglen--;
445                         pkt->hdr.ctl |= FIN;
446                 }
447
448                 if(!c->rtt_start.tv_sec) {
449                         // Start RTT measurement
450                         gettimeofday(&c->rtt_start, NULL);
451                         c->rtt_seq = pkt->hdr.seq + seglen;
452                         debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
453                 }
454
455                 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
456                 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
457         } while(left);
458
459         free(pkt);
460 }
461
462 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
463         if(c->reapable) {
464                 debug("Error: send() called on closed connection %p\n", c);
465                 errno = EBADF;
466                 return -1;
467         }
468
469         switch(c->state) {
470         case CLOSED:
471         case LISTEN:
472         case SYN_SENT:
473         case SYN_RECEIVED:
474                 debug("Error: send() called on unconnected connection %p\n", c);
475                 errno = ENOTCONN;
476                 return -1;
477         case ESTABLISHED:
478         case CLOSE_WAIT:
479                 break;
480         case FIN_WAIT_1:
481         case FIN_WAIT_2:
482         case CLOSING:
483         case LAST_ACK:
484         case TIME_WAIT:
485                 debug("Error: send() called on closing connection %p\n", c);
486                 errno = EPIPE;
487                 return -1;
488         }
489
490         // Add data to send buffer
491
492         if(!len)
493                 return 0;
494
495         if(!data) {
496                 errno = EFAULT;
497                 return -1;
498         }
499
500         len = buffer_put(&c->sndbuf, data, len);
501         if(len <= 0) {
502                 errno = EWOULDBLOCK;
503                 return 0;
504         }
505
506         c->snd.last += len;
507         ack(c, false);
508         return len;
509 }
510
511 static void swap_ports(struct hdr *hdr) {
512         uint16_t tmp = hdr->src;
513         hdr->src = hdr->dst;
514         hdr->dst = tmp;
515 }
516
517 static void retransmit(struct utcp_connection *c) {
518         if(c->state == CLOSED || c->snd.nxt == c->snd.una)
519                 return;
520
521         struct utcp *utcp = c->utcp;
522
523         struct {
524                 struct hdr hdr;
525                 char data[];
526         } *pkt;
527
528         pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
529         if(!pkt)
530                 return;
531
532         pkt->hdr.src = c->src;
533         pkt->hdr.dst = c->dst;
534
535         switch(c->state) {
536                 case SYN_SENT:
537                         // Send our SYN again
538                         pkt->hdr.seq = c->snd.iss;
539                         pkt->hdr.ack = 0;
540                         pkt->hdr.wnd = c->rcv.wnd;
541                         pkt->hdr.ctl = SYN;
542                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
543                         utcp->send(utcp, pkt, sizeof pkt->hdr);
544                         break;
545
546                 case SYN_RECEIVED:
547                         // Send SYNACK again
548                         pkt->hdr.seq = c->snd.nxt;
549                         pkt->hdr.ack = c->rcv.nxt;
550                         pkt->hdr.ctl = SYN | ACK;
551                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
552                         utcp->send(utcp, pkt, sizeof pkt->hdr);
553                         break;
554
555                 case ESTABLISHED:
556                 case FIN_WAIT_1:
557                 case CLOSE_WAIT:
558                 case CLOSING:
559                 case LAST_ACK:
560                         // Send unacked data again.
561                         pkt->hdr.seq = c->snd.una;
562                         pkt->hdr.ack = c->rcv.nxt;
563                         pkt->hdr.ctl = ACK;
564                         uint32_t len = seqdiff(c->snd.last, c->snd.una);
565                         if(len > utcp->mtu)
566                                 len = utcp->mtu;
567                         if(fin_wanted(c, c->snd.una + len)) {
568                                 len--;
569                                 pkt->hdr.ctl |= FIN;
570                         }
571                         c->snd.nxt = c->snd.una + len;
572                         c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
573                         buffer_copy(&c->sndbuf, pkt->data, 0, len);
574                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
575                         utcp->send(utcp, pkt, sizeof pkt->hdr + len);
576                         break;
577
578                 case CLOSED:
579                 case LISTEN:
580                 case TIME_WAIT:
581                 case FIN_WAIT_2:
582                         // We shouldn't need to retransmit anything in this state.
583 #ifdef UTCP_DEBUG
584                         abort();
585 #endif
586                         timerclear(&c->rtrx_timeout);
587                         break;
588         }
589
590         utcp->rto *= 2;
591         if(utcp->rto > MAX_RTO)
592                 utcp->rto = MAX_RTO;
593         c->rtt_start.tv_sec = 0; // invalidate RTT timer
594         free(pkt);
595 }
596
597 // Update receive buffer and SACK entries after consuming data.
598 static void sack_consume(struct utcp_connection *c, size_t len) {
599         debug("sack_consume %zu\n", len);
600         if(len > c->rcvbuf.used)
601                 abort();
602
603         buffer_get(&c->rcvbuf, NULL, len);
604
605         for(int i = 0; i < NSACKS && c->sacks[i].len; ) {
606                 if(len < c->sacks[i].offset) {
607                         c->sacks[i].offset -= len;
608                         i++;
609                 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
610                         c->sacks[i].offset = 0;
611                         c->sacks[i].len -= len - c->sacks[i].offset;
612                         i++;
613                 } else {
614                         if(i < NSACKS - 1) {
615                                 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof c->sacks[i]);
616                                 c->sacks[i + 1].len = 0;
617                         } else {
618                                 c->sacks[i].len = 0;
619                                 break;
620                         }
621                 }
622         }
623
624         for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
625                 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
626 }
627
628 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
629         debug("out of order packet, offset %u\n", offset);
630         // Packet loss or reordering occured. Store the data in the buffer.
631         ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
632         if(rxd < len)
633                 abort();
634
635         // Make note of where we put it.
636         for(int i = 0; i < NSACKS; i++) {
637                 if(!c->sacks[i].len) { // nothing to merge, add new entry
638                         debug("New SACK entry %d\n", i);
639                         c->sacks[i].offset = offset;
640                         c->sacks[i].len = rxd;
641                         break;
642                 } else if(offset < c->sacks[i].offset) {
643                         if(offset + rxd < c->sacks[i].offset) { // insert before
644                                 if(!c->sacks[NSACKS - 1].len) { // only if room left
645                                         debug("Insert SACK entry at %d\n", i);
646                                         memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof c->sacks[i]);
647                                         c->sacks[i].offset = offset;
648                                         c->sacks[i].len = rxd;
649                                 }
650                                 break;
651                         } else { // merge
652                                 debug("Merge with start of SACK entry at %d\n", i);
653                                 c->sacks[i].offset = offset;
654                                 break;
655                         }
656                 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
657                         if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
658                                 debug("Merge with end of SACK entry at %d\n", i);
659                                 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
660                                 // TODO: handle potential merge with next entry
661                         }
662                         break;
663                 }
664         }
665
666         for(int i = 0; i < NSACKS && c->sacks[i].len; i++)
667                 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
668 }
669
670 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
671         // Check if we can process out-of-order data now.
672         if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
673                 debug("incoming packet len %zu connected with SACK at %u\n", len, c->sacks[0].offset);
674                 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
675                 len = max(len, c->sacks[0].offset + c->sacks[0].len);
676                 data = c->rcvbuf.data;
677         }
678
679         if(c->recv) {
680                 ssize_t rxd = c->recv(c, data, len);
681                 if(rxd != len) {
682                         // TODO: handle the application not accepting all data.
683                         abort();
684                 }
685         }
686
687         if(c->rcvbuf.used)
688                 sack_consume(c, len);
689
690         c->rcv.nxt += len;
691 }
692
693
694 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
695         uint32_t offset = seqdiff(seq, c->rcv.nxt);
696         if(offset + len > c->rcvbuf.maxsize)
697                 abort();
698
699         if(offset)
700                 handle_out_of_order(c, offset, data, len);
701         else
702                 handle_in_order(c, data, len);
703 }
704
705
706 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
707         if(!utcp) {
708                 errno = EFAULT;
709                 return -1;
710         }
711
712         if(!len)
713                 return 0;
714
715         if(!data) {
716                 errno = EFAULT;
717                 return -1;
718         }
719
720         print_packet(utcp, "recv", data, len);
721
722         // Drop packets smaller than the header
723
724         struct hdr hdr;
725         if(len < sizeof hdr) {
726                 errno = EBADMSG;
727                 return -1;
728         }
729
730         // Make a copy from the potentially unaligned data to a struct hdr
731
732         memcpy(&hdr, data, sizeof hdr);
733         data += sizeof hdr;
734         len -= sizeof hdr;
735
736         // Drop packets with an unknown CTL flag
737
738         if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
739                 errno = EBADMSG;
740                 return -1;
741         }
742
743         // Try to match the packet to an existing connection
744
745         struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
746
747         // Is it for a new connection?
748
749         if(!c) {
750                 // Ignore RST packets
751
752                 if(hdr.ctl & RST)
753                         return 0;
754
755                 // Is it a SYN packet and are we LISTENing?
756
757                 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
758                         // If we don't want to accept it, send a RST back
759                         if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
760                                 len = 1;
761                                 goto reset;
762                         }
763
764                         // Try to allocate memory, otherwise send a RST back
765                         c = allocate_connection(utcp, hdr.dst, hdr.src);
766                         if(!c) {
767                                 len = 1;
768                                 goto reset;
769                         }
770
771                         // Return SYN+ACK, go to SYN_RECEIVED state
772                         c->snd.wnd = hdr.wnd;
773                         c->rcv.irs = hdr.seq;
774                         c->rcv.nxt = c->rcv.irs + 1;
775                         set_state(c, SYN_RECEIVED);
776
777                         hdr.dst = c->dst;
778                         hdr.src = c->src;
779                         hdr.ack = c->rcv.irs + 1;
780                         hdr.seq = c->snd.iss;
781                         hdr.ctl = SYN | ACK;
782                         print_packet(c->utcp, "send", &hdr, sizeof hdr);
783                         utcp->send(utcp, &hdr, sizeof hdr);
784                 } else {
785                         // No, we don't want your packets, send a RST back
786                         len = 1;
787                         goto reset;
788                 }
789
790                 return 0;
791         }
792
793         debug("%p state %s\n", c->utcp, strstate[c->state]);
794
795         // In case this is for a CLOSED connection, ignore the packet.
796         // TODO: make it so incoming packets can never match a CLOSED connection.
797
798         if(c->state == CLOSED)
799                 return 0;
800
801         // It is for an existing connection.
802
803         uint32_t prevrcvnxt = c->rcv.nxt;
804
805         // 1. Drop invalid packets.
806
807         // 1a. Drop packets that should not happen in our current state.
808
809         switch(c->state) {
810         case SYN_SENT:
811         case SYN_RECEIVED:
812         case ESTABLISHED:
813         case FIN_WAIT_1:
814         case FIN_WAIT_2:
815         case CLOSE_WAIT:
816         case CLOSING:
817         case LAST_ACK:
818         case TIME_WAIT:
819                 break;
820         default:
821 #ifdef UTCP_DEBUG
822                 abort();
823 #endif
824                 break;
825         }
826
827         // 1b. Drop packets with a sequence number not in our receive window.
828
829         bool acceptable;
830
831         if(c->state == SYN_SENT)
832                 acceptable = true;
833
834         // TODO: handle packets overlapping c->rcv.nxt.
835 #if 1
836         // Only use this when accepting out-of-order packets.
837         else if(len == 0)
838                 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
839         else
840                 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
841 #else
842         if(c->state != SYN_SENT)
843                 acceptable = hdr.seq == c->rcv.nxt;
844 #endif
845
846         if(!acceptable) {
847                 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcvbuf.maxsize);
848                 // Ignore unacceptable RST packets.
849                 if(hdr.ctl & RST)
850                         return 0;
851                 // Otherwise, send an ACK back in the hope things improve.
852                 ack(c, true);
853                 return 0;
854         }
855
856         c->snd.wnd = hdr.wnd; // TODO: move below
857
858         // 1c. Drop packets with an invalid ACK.
859         // ackno should not roll back, and it should also not be bigger than what we ever could have sent
860         // (= snd.una + c->sndbuf.used).
861
862         if(hdr.ctl & ACK &&
863                         ((seqdiff(hdr.ack, c->snd.una + c->sndbuf.used) > 0 &&
864                           seqdiff(hdr.ack, c->snd.nxt) > 0) // TODO: simplify this if
865                          || seqdiff(hdr.ack, c->snd.una) < 0)) {
866                 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
867                 // Ignore unacceptable RST packets.
868                 if(hdr.ctl & RST)
869                         return 0;
870                 goto reset;
871         }
872
873         // 2. Handle RST packets
874
875         if(hdr.ctl & RST) {
876                 switch(c->state) {
877                 case SYN_SENT:
878                         if(!(hdr.ctl & ACK))
879                                 return 0;
880                         // The peer has refused our connection.
881                         set_state(c, CLOSED);
882                         errno = ECONNREFUSED;
883                         if(c->recv)
884                                 c->recv(c, NULL, 0);
885                         return 0;
886                 case SYN_RECEIVED:
887                         if(hdr.ctl & ACK)
888                                 return 0;
889                         // We haven't told the application about this connection yet. Silently delete.
890                         free_connection(c);
891                         return 0;
892                 case ESTABLISHED:
893                 case FIN_WAIT_1:
894                 case FIN_WAIT_2:
895                 case CLOSE_WAIT:
896                         if(hdr.ctl & ACK)
897                                 return 0;
898                         // The peer has aborted our connection.
899                         set_state(c, CLOSED);
900                         errno = ECONNRESET;
901                         if(c->recv)
902                                 c->recv(c, NULL, 0);
903                         return 0;
904                 case CLOSING:
905                 case LAST_ACK:
906                 case TIME_WAIT:
907                         if(hdr.ctl & ACK)
908                                 return 0;
909                         // As far as the application is concerned, the connection has already been closed.
910                         // If it has called utcp_close() already, we can immediately free this connection.
911                         if(c->reapable) {
912                                 free_connection(c);
913                                 return 0;
914                         }
915                         // Otherwise, immediately move to the CLOSED state.
916                         set_state(c, CLOSED);
917                         return 0;
918                 default:
919 #ifdef UTCP_DEBUG
920                         abort();
921 #endif
922                         break;
923                 }
924         }
925
926         // 3. Advance snd.una
927
928         uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
929         prevrcvnxt = c->rcv.nxt;
930
931         if(advanced) {
932                 // RTT measurement
933                 if(c->rtt_start.tv_sec) {
934                         if(c->rtt_seq == hdr.ack) {
935                                 struct timeval now, diff;
936                                 gettimeofday(&now, NULL);
937                                 timersub(&now, &c->rtt_start, &diff);
938                                 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
939                                 c->rtt_start.tv_sec = 0;
940                         } else if(c->rtt_seq < hdr.ack) {
941                                 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
942                                 c->rtt_start.tv_sec = 0;
943                         }
944                 }
945
946                 int32_t data_acked = advanced;
947
948                 switch(c->state) {
949                         case SYN_SENT:
950                         case SYN_RECEIVED:
951                                 data_acked--;
952                                 break;
953                         // TODO: handle FIN as well.
954                         default:
955                                 break;
956                 }
957
958                 assert(data_acked >= 0);
959
960                 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
961                 assert(data_acked <= bufused);
962
963                 if(data_acked)
964                         buffer_get(&c->sndbuf, NULL, data_acked);
965
966                 // Also advance snd.nxt if possible
967                 if(seqdiff(c->snd.nxt, hdr.ack) < 0)
968                         c->snd.nxt = hdr.ack;
969
970                 c->snd.una = hdr.ack;
971
972                 c->dupack = 0;
973                 c->snd.cwnd += utcp->mtu;
974                 if(c->snd.cwnd > c->sndbuf.maxsize)
975                         c->snd.cwnd = c->sndbuf.maxsize;
976
977                 // Check if we have sent a FIN that is now ACKed.
978                 switch(c->state) {
979                 case FIN_WAIT_1:
980                         if(c->snd.una == c->snd.last)
981                                 set_state(c, FIN_WAIT_2);
982                         break;
983                 case CLOSING:
984                         if(c->snd.una == c->snd.last) {
985                                 gettimeofday(&c->conn_timeout, NULL);
986                                 c->conn_timeout.tv_sec += 60;
987                                 set_state(c, TIME_WAIT);
988                         }
989                         break;
990                 default:
991                         break;
992                 }
993         } else {
994                 if(!len) {
995                         c->dupack++;
996                         if(c->dupack == 3) {
997                                 debug("Triplicate ACK\n");
998                                 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
999                                 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1000                                 //Reset the congestion window so we wait for ACKs.
1001                                 c->snd.nxt = c->snd.una;
1002                                 c->snd.cwnd = utcp->mtu;
1003                         }
1004                 }
1005         }
1006
1007         // 4. Update timers
1008
1009         if(advanced) {
1010                 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
1011                 if(c->snd.una == c->snd.nxt)
1012                         timerclear(&c->rtrx_timeout);
1013         }
1014
1015         // 5. Process SYN stuff
1016
1017         if(hdr.ctl & SYN) {
1018                 switch(c->state) {
1019                 case SYN_SENT:
1020                         // This is a SYNACK. It should always have ACKed the SYN.
1021                         if(!advanced)
1022                                 goto reset;
1023                         c->rcv.irs = hdr.seq;
1024                         c->rcv.nxt = hdr.seq;
1025                         set_state(c, ESTABLISHED);
1026                         // TODO: notify application of this somehow.
1027                         break;
1028                 case SYN_RECEIVED:
1029                 case ESTABLISHED:
1030                 case FIN_WAIT_1:
1031                 case FIN_WAIT_2:
1032                 case CLOSE_WAIT:
1033                 case CLOSING:
1034                 case LAST_ACK:
1035                 case TIME_WAIT:
1036                         // Ehm, no. We should never receive a second SYN.
1037                         goto reset;
1038                 default:
1039 #ifdef UTCP_DEBUG
1040                         abort();
1041 #endif
1042                         return 0;
1043                 }
1044
1045                 // SYN counts as one sequence number
1046                 c->rcv.nxt++;
1047         }
1048
1049         // 6. Process new data
1050
1051         if(c->state == SYN_RECEIVED) {
1052                 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1053                 if(!advanced)
1054                         goto reset;
1055
1056                 // Are we still LISTENing?
1057                 if(utcp->accept)
1058                         utcp->accept(c, c->src);
1059
1060                 if(c->state != ESTABLISHED) {
1061                         set_state(c, CLOSED);
1062                         c->reapable = true;
1063                         goto reset;
1064                 }
1065         }
1066
1067         if(len) {
1068                 switch(c->state) {
1069                 case SYN_SENT:
1070                 case SYN_RECEIVED:
1071                         // This should never happen.
1072 #ifdef UTCP_DEBUG
1073                         abort();
1074 #endif
1075                         return 0;
1076                 case ESTABLISHED:
1077                 case FIN_WAIT_1:
1078                 case FIN_WAIT_2:
1079                         break;
1080                 case CLOSE_WAIT:
1081                 case CLOSING:
1082                 case LAST_ACK:
1083                 case TIME_WAIT:
1084                         // Ehm no, We should never receive more data after a FIN.
1085                         goto reset;
1086                 default:
1087 #ifdef UTCP_DEBUG
1088                         abort();
1089 #endif
1090                         return 0;
1091                 }
1092
1093                 handle_incoming_data(c, hdr.seq, data, len);
1094         }
1095
1096         // 7. Process FIN stuff
1097
1098         if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1099                 switch(c->state) {
1100                 case SYN_SENT:
1101                 case SYN_RECEIVED:
1102                         // This should never happen.
1103 #ifdef UTCP_DEBUG
1104                         abort();
1105 #endif
1106                         break;
1107                 case ESTABLISHED:
1108                         set_state(c, CLOSE_WAIT);
1109                         break;
1110                 case FIN_WAIT_1:
1111                         set_state(c, CLOSING);
1112                         break;
1113                 case FIN_WAIT_2:
1114                         gettimeofday(&c->conn_timeout, NULL);
1115                         c->conn_timeout.tv_sec += 60;
1116                         set_state(c, TIME_WAIT);
1117                         break;
1118                 case CLOSE_WAIT:
1119                 case CLOSING:
1120                 case LAST_ACK:
1121                 case TIME_WAIT:
1122                         // Ehm, no. We should never receive a second FIN.
1123                         goto reset;
1124                 default:
1125 #ifdef UTCP_DEBUG
1126                         abort();
1127 #endif
1128                         break;
1129                 }
1130
1131                 // FIN counts as one sequence number
1132                 c->rcv.nxt++;
1133                 len++;
1134
1135                 // Inform the application that the peer closed the connection.
1136                 if(c->recv) {
1137                         errno = 0;
1138                         c->recv(c, NULL, 0);
1139                 }
1140         }
1141
1142         // Now we send something back if:
1143         // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1144         //   -> sendatleastone = true
1145         // - or we got an ack, so we should maybe send a bit more data
1146         //   -> sendatleastone = false
1147
1148 ack:
1149         ack(c, prevrcvnxt != c->rcv.nxt);
1150         return 0;
1151
1152 reset:
1153         swap_ports(&hdr);
1154         hdr.wnd = 0;
1155         if(hdr.ctl & ACK) {
1156                 hdr.seq = hdr.ack;
1157                 hdr.ctl = RST;
1158         } else {
1159                 hdr.ack = hdr.seq + len;
1160                 hdr.seq = 0;
1161                 hdr.ctl = RST | ACK;
1162         }
1163         print_packet(utcp, "send", &hdr, sizeof hdr);
1164         utcp->send(utcp, &hdr, sizeof hdr);
1165         return 0;
1166
1167 }
1168
1169 int utcp_shutdown(struct utcp_connection *c, int dir) {
1170         debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1171         if(!c) {
1172                 errno = EFAULT;
1173                 return -1;
1174         }
1175
1176         if(c->reapable) {
1177                 debug("Error: shutdown() called on closed connection %p\n", c);
1178                 errno = EBADF;
1179                 return -1;
1180         }
1181
1182         if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1183                 errno = EINVAL;
1184                 return -1;
1185         }
1186
1187         // TCP does not have a provision for stopping incoming packets.
1188         // The best we can do is to just ignore them.
1189         if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR)
1190                 c->recv = NULL;
1191
1192         // The rest of the code deals with shutting down writes.
1193         if(dir == UTCP_SHUT_RD)
1194                 return 0;
1195
1196         switch(c->state) {
1197         case CLOSED:
1198         case LISTEN:
1199                 errno = ENOTCONN;
1200                 return -1;
1201
1202         case SYN_SENT:
1203                 set_state(c, CLOSED);
1204                 return 0;
1205
1206         case SYN_RECEIVED:
1207         case ESTABLISHED:
1208                 set_state(c, FIN_WAIT_1);
1209                 break;
1210         case FIN_WAIT_1:
1211         case FIN_WAIT_2:
1212                 return 0;
1213         case CLOSE_WAIT:
1214                 set_state(c, CLOSING);
1215                 break;
1216
1217         case CLOSING:
1218         case LAST_ACK:
1219         case TIME_WAIT:
1220                 return 0;
1221         }
1222
1223         c->snd.last++;
1224
1225         ack(c, false);
1226         return 0;
1227 }
1228
1229 int utcp_close(struct utcp_connection *c) {
1230         if(utcp_shutdown(c, SHUT_RDWR))
1231                 return -1;
1232         c->recv = NULL;
1233         c->poll = NULL;
1234         c->reapable = true;
1235         return 0;
1236 }
1237
1238 int utcp_abort(struct utcp_connection *c) {
1239         if(!c) {
1240                 errno = EFAULT;
1241                 return -1;
1242         }
1243
1244         if(c->reapable) {
1245                 debug("Error: abort() called on closed connection %p\n", c);
1246                 errno = EBADF;
1247                 return -1;
1248         }
1249
1250         c->recv = NULL;
1251         c->poll = NULL;
1252         c->reapable = true;
1253
1254         switch(c->state) {
1255         case CLOSED:
1256                 return 0;
1257         case LISTEN:
1258         case SYN_SENT:
1259         case CLOSING:
1260         case LAST_ACK:
1261         case TIME_WAIT:
1262                 set_state(c, CLOSED);
1263                 return 0;
1264
1265         case SYN_RECEIVED:
1266         case ESTABLISHED:
1267         case FIN_WAIT_1:
1268         case FIN_WAIT_2:
1269         case CLOSE_WAIT:
1270                 set_state(c, CLOSED);
1271                 break;
1272         }
1273
1274         // Send RST
1275
1276         struct hdr hdr;
1277
1278         hdr.src = c->src;
1279         hdr.dst = c->dst;
1280         hdr.seq = c->snd.nxt;
1281         hdr.ack = 0;
1282         hdr.wnd = 0;
1283         hdr.ctl = RST;
1284
1285         print_packet(c->utcp, "send", &hdr, sizeof hdr);
1286         c->utcp->send(c->utcp, &hdr, sizeof hdr);
1287         return 0;
1288 }
1289
1290 /* Handle timeouts.
1291  * One call to this function will loop through all connections,
1292  * checking if something needs to be resent or not.
1293  * The return value is the time to the next timeout in milliseconds,
1294  * or maybe a negative value if the timeout is infinite.
1295  */
1296 struct timeval utcp_timeout(struct utcp *utcp) {
1297         struct timeval now;
1298         gettimeofday(&now, NULL);
1299         struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1300
1301         for(int i = 0; i < utcp->nconnections; i++) {
1302                 struct utcp_connection *c = utcp->connections[i];
1303                 if(!c)
1304                         continue;
1305
1306                 if(c->state == CLOSED) {
1307                         if(c->reapable) {
1308                                 debug("Reaping %p\n", c);
1309                                 free_connection(c);
1310                                 i--;
1311                         }
1312                         continue;
1313                 }
1314
1315                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1316                         errno = ETIMEDOUT;
1317                         c->state = CLOSED;
1318                         if(c->recv)
1319                                 c->recv(c, NULL, 0);
1320                         continue;
1321                 }
1322
1323                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1324                         retransmit(c);
1325                 }
1326
1327                 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1328                         c->poll(c, buffer_free(&c->sndbuf));
1329
1330                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1331                         next = c->conn_timeout;
1332
1333                 if(c->snd.nxt != c->snd.una) {
1334                         c->rtrx_timeout = now;
1335                         c->rtrx_timeout.tv_sec++;
1336                 } else {
1337                         timerclear(&c->rtrx_timeout);
1338                 }
1339
1340                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1341                         next = c->rtrx_timeout;
1342         }
1343
1344         struct timeval diff;
1345         timersub(&next, &now, &diff);
1346         return diff;
1347 }
1348
1349 bool utcp_is_active(struct utcp *utcp) {
1350         if(!utcp)
1351                 return false;
1352
1353         for(int i = 0; i < utcp->nconnections; i++)
1354                 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT)
1355                         return true;
1356
1357         return false;
1358 }
1359
1360 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1361         if(!send) {
1362                 errno = EFAULT;
1363                 return NULL;
1364         }
1365
1366         struct utcp *utcp = calloc(1, sizeof *utcp);
1367         if(!utcp)
1368                 return NULL;
1369
1370         utcp->accept = accept;
1371         utcp->pre_accept = pre_accept;
1372         utcp->send = send;
1373         utcp->priv = priv;
1374         utcp->mtu = DEFAULT_MTU;
1375         utcp->timeout = DEFAULT_USER_TIMEOUT; // s
1376         utcp->rto = START_RTO; // us
1377
1378         return utcp;
1379 }
1380
1381 void utcp_exit(struct utcp *utcp) {
1382         if(!utcp)
1383                 return;
1384         for(int i = 0; i < utcp->nconnections; i++) {
1385                 if(!utcp->connections[i]->reapable)
1386                         debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1387                 buffer_exit(&utcp->connections[i]->sndbuf);
1388                 free(utcp->connections[i]);
1389         }
1390         free(utcp->connections);
1391         free(utcp);
1392 }
1393
1394 uint16_t utcp_get_mtu(struct utcp *utcp) {
1395         return utcp ? utcp->mtu : 0;
1396 }
1397
1398 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1399         // TODO: handle overhead of the header
1400         if(utcp)
1401                 utcp->mtu = mtu;
1402 }
1403
1404 int utcp_get_user_timeout(struct utcp *u) {
1405         return u ? u->timeout : 0;
1406 }
1407
1408 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1409         if(u)
1410                 u->timeout = timeout;
1411 }
1412
1413 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1414         return c ? c->sndbuf.maxsize : 0;
1415 }
1416
1417 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1418         if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1419                 return buffer_free(&c->sndbuf);
1420         else
1421                 return 0;
1422 }
1423
1424 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1425         if(!c)
1426                 return;
1427         c->sndbuf.maxsize = size;
1428         if(c->sndbuf.maxsize != size)
1429                 c->sndbuf.maxsize = -1;
1430 }
1431
1432 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1433         return c ? c->rcvbuf.maxsize : 0;
1434 }
1435
1436 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1437         if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1438                 return buffer_free(&c->rcvbuf);
1439         else
1440                 return 0;
1441 }
1442
1443 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1444         if(!c)
1445                 return;
1446         c->rcvbuf.maxsize = size;
1447         if(c->rcvbuf.maxsize != size)
1448                 c->rcvbuf.maxsize = -1;
1449 }
1450
1451 bool utcp_get_nodelay(struct utcp_connection *c) {
1452         return c ? c->nodelay : false;
1453 }
1454
1455 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1456         if(c)
1457                 c->nodelay = nodelay;
1458 }
1459
1460 bool utcp_get_keepalive(struct utcp_connection *c) {
1461         return c ? c->keepalive : false;
1462 }
1463
1464 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1465         if(c)
1466                 c->keepalive = keepalive;
1467 }
1468
1469 size_t utcp_get_outq(struct utcp_connection *c) {
1470         return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1471 }
1472
1473 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1474         if(c)
1475                 c->recv = recv;
1476 }
1477
1478 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1479         if(c)
1480                 c->poll = poll;
1481 }
1482
1483 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
1484         if(utcp) {
1485                 utcp->accept = accept;
1486                 utcp->pre_accept = pre_accept;
1487         }
1488 }