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