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