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