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