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