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