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