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