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