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