]> git.meshlink.io Git - utcp/blob - utcp.c
Allow utcp_send() before a connection has been fully established.
[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                 debug("Error: send() called on unconnected connection %p\n", c);
584                 errno = ENOTCONN;
585                 return -1;
586
587         case SYN_SENT:
588         case SYN_RECEIVED:
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
625         // Don't send anything yet if the connection has not fully established yet
626
627         if (c->state == SYN_SENT || c->state == SYN_RECEIVED)
628                 return len;
629
630         ack(c, false);
631
632         if(!is_reliable(c)) {
633                 c->snd.una = c->snd.nxt = c->snd.last;
634                 buffer_get(&c->sndbuf, NULL, c->sndbuf.used);
635         }
636
637         if(is_reliable(c) && !timerisset(&c->rtrx_timeout)) {
638                 start_retransmit_timer(c);
639         }
640
641         return len;
642 }
643
644 static void swap_ports(struct hdr *hdr) {
645         uint16_t tmp = hdr->src;
646         hdr->src = hdr->dst;
647         hdr->dst = tmp;
648 }
649
650 static void retransmit(struct utcp_connection *c) {
651         if(c->state == CLOSED || c->snd.last == c->snd.una) {
652                 debug("Retransmit() called but nothing to retransmit!\n");
653                 stop_retransmit_timer(c);
654                 return;
655         }
656
657         struct utcp *utcp = c->utcp;
658
659         struct {
660                 struct hdr hdr;
661                 uint8_t data[];
662         } *pkt;
663
664         pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
665
666         if(!pkt) {
667                 return;
668         }
669
670         pkt->hdr.src = c->src;
671         pkt->hdr.dst = c->dst;
672         pkt->hdr.wnd = c->rcv.wnd;
673         pkt->hdr.aux = 0;
674
675         switch(c->state) {
676         case SYN_SENT:
677                 // Send our SYN again
678                 pkt->hdr.seq = c->snd.iss;
679                 pkt->hdr.ack = 0;
680                 pkt->hdr.ctl = SYN;
681                 pkt->hdr.aux = 0x0101;
682                 pkt->data[0] = 1;
683                 pkt->data[1] = 0;
684                 pkt->data[2] = 0;
685                 pkt->data[3] = c->flags & 0x7;
686                 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + 4);
687                 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
688                 break;
689
690         case SYN_RECEIVED:
691                 // Send SYNACK again
692                 pkt->hdr.seq = c->snd.nxt;
693                 pkt->hdr.ack = c->rcv.nxt;
694                 pkt->hdr.ctl = SYN | ACK;
695                 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr));
696                 utcp->send(utcp, pkt, sizeof(pkt->hdr));
697                 break;
698
699         case ESTABLISHED:
700         case FIN_WAIT_1:
701         case CLOSE_WAIT:
702         case CLOSING:
703         case LAST_ACK:
704                 // Send unacked data again.
705                 pkt->hdr.seq = c->snd.una;
706                 pkt->hdr.ack = c->rcv.nxt;
707                 pkt->hdr.ctl = ACK;
708                 uint32_t len = seqdiff(c->snd.last, c->snd.una);
709
710                 if(len > utcp->mtu) {
711                         len = utcp->mtu;
712                 }
713
714                 if(fin_wanted(c, c->snd.una + len)) {
715                         len--;
716                         pkt->hdr.ctl |= FIN;
717                 }
718
719                 c->snd.nxt = c->snd.una + len;
720                 c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
721                 buffer_copy(&c->sndbuf, pkt->data, 0, len);
722                 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + len);
723                 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
724                 break;
725
726         case CLOSED:
727         case LISTEN:
728         case TIME_WAIT:
729         case FIN_WAIT_2:
730                 // We shouldn't need to retransmit anything in this state.
731 #ifdef UTCP_DEBUG
732                 abort();
733 #endif
734                 stop_retransmit_timer(c);
735                 goto cleanup;
736         }
737
738         start_retransmit_timer(c);
739         utcp->rto *= 2;
740
741         if(utcp->rto > MAX_RTO) {
742                 utcp->rto = MAX_RTO;
743         }
744
745         c->rtt_start.tv_sec = 0; // invalidate RTT timer
746
747 cleanup:
748         free(pkt);
749 }
750
751 /* Update receive buffer and SACK entries after consuming data.
752  *
753  * Situation:
754  *
755  * |.....0000..1111111111.....22222......3333|
756  * |---------------^
757  *
758  * 0..3 represent the SACK entries. The ^ indicates up to which point we want
759  * to remove data from the receive buffer. The idea is to substract "len"
760  * from the offset of all the SACK entries, and then remove/cut down entries
761  * that are shifted to before the start of the receive buffer.
762  *
763  * There are three cases:
764  * - the SACK entry is after ^, in that case just change the offset.
765  * - the SACK entry starts before and ends after ^, so we have to
766  *   change both its offset and size.
767  * - the SACK entry is completely before ^, in that case delete it.
768  */
769 static void sack_consume(struct utcp_connection *c, size_t len) {
770         debug("sack_consume %lu\n", (unsigned long)len);
771
772         if(len > c->rcvbuf.used) {
773                 debug("All SACK entries consumed");
774                 c->sacks[0].len = 0;
775                 return;
776         }
777
778         buffer_get(&c->rcvbuf, NULL, len);
779
780         for(int i = 0; i < NSACKS && c->sacks[i].len;) {
781                 if(len < c->sacks[i].offset) {
782                         c->sacks[i].offset -= len;
783                         i++;
784                 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
785                         c->sacks[i].len -= len - c->sacks[i].offset;
786                         c->sacks[i].offset = 0;
787                         i++;
788                 } else {
789                         if(i < NSACKS - 1) {
790                                 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
791                                 c->sacks[NSACKS - 1].len = 0;
792                         } else {
793                                 c->sacks[i].len = 0;
794                                 break;
795                         }
796                 }
797         }
798
799         for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
800                 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
801         }
802 }
803
804 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
805         debug("out of order packet, offset %u\n", offset);
806         // Packet loss or reordering occured. Store the data in the buffer.
807         ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
808
809         if(rxd < 0 || (size_t)rxd < len) {
810                 abort();
811         }
812
813         // Make note of where we put it.
814         for(int i = 0; i < NSACKS; i++) {
815                 if(!c->sacks[i].len) { // nothing to merge, add new entry
816                         debug("New SACK entry %d\n", i);
817                         c->sacks[i].offset = offset;
818                         c->sacks[i].len = rxd;
819                         break;
820                 } else if(offset < c->sacks[i].offset) {
821                         if(offset + rxd < c->sacks[i].offset) { // insert before
822                                 if(!c->sacks[NSACKS - 1].len) { // only if room left
823                                         debug("Insert SACK entry at %d\n", i);
824                                         memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
825                                         c->sacks[i].offset = offset;
826                                         c->sacks[i].len = rxd;
827                                 } else {
828                                         debug("SACK entries full, dropping packet\n");
829                                 }
830
831                                 break;
832                         } else { // merge
833                                 debug("Merge with start of SACK entry at %d\n", i);
834                                 c->sacks[i].offset = offset;
835                                 break;
836                         }
837                 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
838                         if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
839                                 debug("Merge with end of SACK entry at %d\n", i);
840                                 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
841                                 // TODO: handle potential merge with next entry
842                         }
843
844                         break;
845                 }
846         }
847
848         for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
849                 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
850         }
851 }
852
853 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
854         // Check if we can process out-of-order data now.
855         if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
856                 debug("incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
857                 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
858                 len = max(len, c->sacks[0].offset + c->sacks[0].len);
859                 data = c->rcvbuf.data;
860         }
861
862         if(c->recv) {
863                 ssize_t rxd = c->recv(c, data, len);
864
865                 if(rxd < 0 || (size_t)rxd != len) {
866                         // TODO: handle the application not accepting all data.
867                         abort();
868                 }
869         }
870
871         if(c->rcvbuf.used) {
872                 sack_consume(c, len);
873         }
874
875         c->rcv.nxt += len;
876 }
877
878
879 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
880         if(!is_reliable(c)) {
881                 c->recv(c, data, len);
882                 c->rcv.nxt = seq + len;
883                 return;
884         }
885
886         uint32_t offset = seqdiff(seq, c->rcv.nxt);
887
888         if(offset + len > c->rcvbuf.maxsize) {
889                 abort();
890         }
891
892         if(offset) {
893                 handle_out_of_order(c, offset, data, len);
894         } else {
895                 handle_in_order(c, data, len);
896         }
897 }
898
899
900 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
901         const uint8_t *ptr = data;
902
903         if(!utcp) {
904                 errno = EFAULT;
905                 return -1;
906         }
907
908         if(!len) {
909                 return 0;
910         }
911
912         if(!data) {
913                 errno = EFAULT;
914                 return -1;
915         }
916
917         print_packet(utcp, "recv", data, len);
918
919         // Drop packets smaller than the header
920
921         struct hdr hdr;
922
923         if(len < sizeof(hdr)) {
924                 errno = EBADMSG;
925                 return -1;
926         }
927
928         // Make a copy from the potentially unaligned data to a struct hdr
929
930         memcpy(&hdr, ptr, sizeof(hdr));
931         ptr += sizeof(hdr);
932         len -= sizeof(hdr);
933
934         // Drop packets with an unknown CTL flag
935
936         if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
937                 errno = EBADMSG;
938                 return -1;
939         }
940
941         // Check for auxiliary headers
942
943         const uint8_t *init = NULL;
944
945         uint16_t aux = hdr.aux;
946
947         while(aux) {
948                 size_t auxlen = 4 * (aux >> 8) & 0xf;
949                 uint8_t auxtype = aux & 0xff;
950
951                 if(len < auxlen) {
952                         errno = EBADMSG;
953                         return -1;
954                 }
955
956                 switch(auxtype) {
957                 case AUX_INIT:
958                         if(!(hdr.ctl & SYN) || auxlen != 4) {
959                                 errno = EBADMSG;
960                                 return -1;
961                         }
962
963                         init = ptr;
964                         break;
965
966                 default:
967                         errno = EBADMSG;
968                         return -1;
969                 }
970
971                 len -= auxlen;
972                 ptr += auxlen;
973
974                 if(!(aux & 0x800)) {
975                         break;
976                 }
977
978                 if(len < 2) {
979                         errno = EBADMSG;
980                         return -1;
981                 }
982
983                 memcpy(&aux, ptr, 2);
984                 len -= 2;
985                 ptr += 2;
986         }
987
988         // Try to match the packet to an existing connection
989
990         struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
991
992         // Is it for a new connection?
993
994         if(!c) {
995                 // Ignore RST packets
996
997                 if(hdr.ctl & RST) {
998                         return 0;
999                 }
1000
1001                 // Is it a SYN packet and are we LISTENing?
1002
1003                 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1004                         // If we don't want to accept it, send a RST back
1005                         if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
1006                                 len = 1;
1007                                 goto reset;
1008                         }
1009
1010                         // Try to allocate memory, otherwise send a RST back
1011                         c = allocate_connection(utcp, hdr.dst, hdr.src);
1012
1013                         if(!c) {
1014                                 len = 1;
1015                                 goto reset;
1016                         }
1017
1018                         // Parse auxilliary information
1019                         if(init) {
1020                                 if(init[0] < 1) {
1021                                         len = 1;
1022                                         goto reset;
1023                                 }
1024
1025                                 c->flags = init[3] & 0x7;
1026                         } else {
1027                                 c->flags = UTCP_TCP;
1028                         }
1029
1030                         // Return SYN+ACK, go to SYN_RECEIVED state
1031                         c->snd.wnd = hdr.wnd;
1032                         c->rcv.irs = hdr.seq;
1033                         c->rcv.nxt = c->rcv.irs + 1;
1034                         set_state(c, SYN_RECEIVED);
1035
1036                         struct {
1037                                 struct hdr hdr;
1038                                 uint8_t data[4];
1039                         } pkt;
1040
1041                         pkt.hdr.src = c->src;
1042                         pkt.hdr.dst = c->dst;
1043                         pkt.hdr.ack = c->rcv.irs + 1;
1044                         pkt.hdr.seq = c->snd.iss;
1045                         pkt.hdr.wnd = c->rcv.wnd;
1046                         pkt.hdr.ctl = SYN | ACK;
1047
1048                         if(init) {
1049                                 pkt.hdr.aux = 0x0101;
1050                                 pkt.data[0] = 1;
1051                                 pkt.data[1] = 0;
1052                                 pkt.data[2] = 0;
1053                                 pkt.data[3] = c->flags & 0x7;
1054                                 print_packet(c->utcp, "send", &pkt, sizeof(hdr) + 4);
1055                                 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1056                         } else {
1057                                 pkt.hdr.aux = 0;
1058                                 print_packet(c->utcp, "send", &pkt, sizeof(hdr));
1059                                 utcp->send(utcp, &pkt, sizeof(hdr));
1060                         }
1061                 } else {
1062                         // No, we don't want your packets, send a RST back
1063                         len = 1;
1064                         goto reset;
1065                 }
1066
1067                 return 0;
1068         }
1069
1070         debug("%p state %s\n", c->utcp, strstate[c->state]);
1071
1072         // In case this is for a CLOSED connection, ignore the packet.
1073         // TODO: make it so incoming packets can never match a CLOSED connection.
1074
1075         if(c->state == CLOSED) {
1076                 debug("Got packet for closed connection\n");
1077                 return 0;
1078         }
1079
1080         // It is for an existing connection.
1081
1082         uint32_t prevrcvnxt = c->rcv.nxt;
1083
1084         // 1. Drop invalid packets.
1085
1086         // 1a. Drop packets that should not happen in our current state.
1087
1088         switch(c->state) {
1089         case SYN_SENT:
1090         case SYN_RECEIVED:
1091         case ESTABLISHED:
1092         case FIN_WAIT_1:
1093         case FIN_WAIT_2:
1094         case CLOSE_WAIT:
1095         case CLOSING:
1096         case LAST_ACK:
1097         case TIME_WAIT:
1098                 break;
1099
1100         default:
1101 #ifdef UTCP_DEBUG
1102                 abort();
1103 #endif
1104                 break;
1105         }
1106
1107         // 1b. Drop packets with a sequence number not in our receive window.
1108
1109         bool acceptable;
1110
1111         if(c->state == SYN_SENT) {
1112                 acceptable = true;
1113         } else if(len == 0) {
1114                 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1115         } else {
1116                 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1117
1118                 // cut already accepted front overlapping
1119                 if(rcv_offset < 0) {
1120                         acceptable = len > (size_t) - rcv_offset;
1121
1122                         if(acceptable) {
1123                                 ptr -= rcv_offset;
1124                                 len += rcv_offset;
1125                                 hdr.seq -= rcv_offset;
1126                         }
1127                 } else {
1128                         acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1129                 }
1130         }
1131
1132         if(!acceptable) {
1133                 debug("Packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1134
1135                 // Ignore unacceptable RST packets.
1136                 if(hdr.ctl & RST) {
1137                         return 0;
1138                 }
1139
1140                 // Otherwise, continue processing.
1141                 len = 0;
1142         }
1143
1144         c->snd.wnd = hdr.wnd; // TODO: move below
1145
1146         // 1c. Drop packets with an invalid ACK.
1147         // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1148         // (= snd.una + c->sndbuf.used).
1149
1150         if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
1151                 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1152
1153                 // Ignore unacceptable RST packets.
1154                 if(hdr.ctl & RST) {
1155                         return 0;
1156                 }
1157
1158                 goto reset;
1159         }
1160
1161         // 2. Handle RST packets
1162
1163         if(hdr.ctl & RST) {
1164                 switch(c->state) {
1165                 case SYN_SENT:
1166                         if(!(hdr.ctl & ACK)) {
1167                                 return 0;
1168                         }
1169
1170                         // The peer has refused our connection.
1171                         set_state(c, CLOSED);
1172                         errno = ECONNREFUSED;
1173
1174                         if(c->recv) {
1175                                 c->recv(c, NULL, 0);
1176                         }
1177
1178                         return 0;
1179
1180                 case SYN_RECEIVED:
1181                         if(hdr.ctl & ACK) {
1182                                 return 0;
1183                         }
1184
1185                         // We haven't told the application about this connection yet. Silently delete.
1186                         free_connection(c);
1187                         return 0;
1188
1189                 case ESTABLISHED:
1190                 case FIN_WAIT_1:
1191                 case FIN_WAIT_2:
1192                 case CLOSE_WAIT:
1193                         if(hdr.ctl & ACK) {
1194                                 return 0;
1195                         }
1196
1197                         // The peer has aborted our connection.
1198                         set_state(c, CLOSED);
1199                         errno = ECONNRESET;
1200
1201                         if(c->recv) {
1202                                 c->recv(c, NULL, 0);
1203                         }
1204
1205                         return 0;
1206
1207                 case CLOSING:
1208                 case LAST_ACK:
1209                 case TIME_WAIT:
1210                         if(hdr.ctl & ACK) {
1211                                 return 0;
1212                         }
1213
1214                         // As far as the application is concerned, the connection has already been closed.
1215                         // If it has called utcp_close() already, we can immediately free this connection.
1216                         if(c->reapable) {
1217                                 free_connection(c);
1218                                 return 0;
1219                         }
1220
1221                         // Otherwise, immediately move to the CLOSED state.
1222                         set_state(c, CLOSED);
1223                         return 0;
1224
1225                 default:
1226 #ifdef UTCP_DEBUG
1227                         abort();
1228 #endif
1229                         break;
1230                 }
1231         }
1232
1233         uint32_t advanced;
1234
1235         if(!(hdr.ctl & ACK)) {
1236                 advanced = 0;
1237                 goto skip_ack;
1238         }
1239
1240         // 3. Advance snd.una
1241
1242         advanced = seqdiff(hdr.ack, c->snd.una);
1243         prevrcvnxt = c->rcv.nxt;
1244
1245         if(advanced) {
1246                 // RTT measurement
1247                 if(c->rtt_start.tv_sec) {
1248                         if(c->rtt_seq == hdr.ack) {
1249                                 struct timeval now, diff;
1250                                 gettimeofday(&now, NULL);
1251                                 timersub(&now, &c->rtt_start, &diff);
1252                                 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
1253                                 c->rtt_start.tv_sec = 0;
1254                         } else if(c->rtt_seq < hdr.ack) {
1255                                 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1256                                 c->rtt_start.tv_sec = 0;
1257                         }
1258                 }
1259
1260                 int32_t data_acked = advanced;
1261
1262                 switch(c->state) {
1263                 case SYN_SENT:
1264                 case SYN_RECEIVED:
1265                         data_acked--;
1266                         break;
1267
1268                 // TODO: handle FIN as well.
1269                 default:
1270                         break;
1271                 }
1272
1273                 assert(data_acked >= 0);
1274
1275                 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1276                 assert(data_acked <= bufused);
1277
1278                 if(data_acked) {
1279                         buffer_get(&c->sndbuf, NULL, data_acked);
1280                 }
1281
1282                 // Also advance snd.nxt if possible
1283                 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1284                         c->snd.nxt = hdr.ack;
1285                 }
1286
1287                 c->snd.una = hdr.ack;
1288
1289                 c->dupack = 0;
1290                 c->snd.cwnd += utcp->mtu;
1291
1292                 if(c->snd.cwnd > c->sndbuf.maxsize) {
1293                         c->snd.cwnd = c->sndbuf.maxsize;
1294                 }
1295
1296                 // Check if we have sent a FIN that is now ACKed.
1297                 switch(c->state) {
1298                 case FIN_WAIT_1:
1299                         if(c->snd.una == c->snd.last) {
1300                                 set_state(c, FIN_WAIT_2);
1301                         }
1302
1303                         break;
1304
1305                 case CLOSING:
1306                         if(c->snd.una == c->snd.last) {
1307                                 gettimeofday(&c->conn_timeout, NULL);
1308                                 c->conn_timeout.tv_sec += 60;
1309                                 set_state(c, TIME_WAIT);
1310                         }
1311
1312                         break;
1313
1314                 default:
1315                         break;
1316                 }
1317         } else {
1318                 if(!len && is_reliable(c)) {
1319                         c->dupack++;
1320
1321                         if(c->dupack == 3) {
1322                                 debug("Triplicate ACK\n");
1323                                 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1324                                 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1325                                 //Reset the congestion window so we wait for ACKs.
1326                                 c->snd.nxt = c->snd.una;
1327                                 c->snd.cwnd = utcp->mtu;
1328                                 start_retransmit_timer(c);
1329                         }
1330                 }
1331         }
1332
1333         // 4. Update timers
1334
1335         if(advanced) {
1336                 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
1337
1338                 if(c->snd.una == c->snd.last) {
1339                         stop_retransmit_timer(c);
1340                 } else if(is_reliable(c)) {
1341                         start_retransmit_timer(c);
1342                 }
1343         }
1344
1345 skip_ack:
1346         // 5. Process SYN stuff
1347
1348         if(hdr.ctl & SYN) {
1349                 switch(c->state) {
1350                 case SYN_SENT:
1351
1352                         // This is a SYNACK. It should always have ACKed the SYN.
1353                         if(!advanced) {
1354                                 goto reset;
1355                         }
1356
1357                         c->rcv.irs = hdr.seq;
1358                         c->rcv.nxt = hdr.seq;
1359                         if(c->shut_wr) {
1360                                 c->snd.last++;
1361                                 set_state(c, FIN_WAIT_1);
1362                         } else {
1363                                 set_state(c, ESTABLISHED);
1364                         }
1365                         // TODO: notify application of this somehow.
1366                         break;
1367
1368                 case SYN_RECEIVED:
1369                 case ESTABLISHED:
1370                 case FIN_WAIT_1:
1371                 case FIN_WAIT_2:
1372                 case CLOSE_WAIT:
1373                 case CLOSING:
1374                 case LAST_ACK:
1375                 case TIME_WAIT:
1376                         // Ehm, no. We should never receive a second SYN.
1377                         return 0;
1378
1379                 default:
1380 #ifdef UTCP_DEBUG
1381                         abort();
1382 #endif
1383                         return 0;
1384                 }
1385
1386                 // SYN counts as one sequence number
1387                 c->rcv.nxt++;
1388         }
1389
1390         // 6. Process new data
1391
1392         if(c->state == SYN_RECEIVED) {
1393                 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1394                 if(!advanced) {
1395                         goto reset;
1396                 }
1397
1398                 // Are we still LISTENing?
1399                 if(utcp->accept) {
1400                         utcp->accept(c, c->src);
1401                 }
1402
1403                 if(c->state != ESTABLISHED) {
1404                         set_state(c, CLOSED);
1405                         c->reapable = true;
1406                         goto reset;
1407                 }
1408         }
1409
1410         if(len) {
1411                 switch(c->state) {
1412                 case SYN_SENT:
1413                 case SYN_RECEIVED:
1414                         // This should never happen.
1415 #ifdef UTCP_DEBUG
1416                         abort();
1417 #endif
1418                         return 0;
1419
1420                 case ESTABLISHED:
1421                 case FIN_WAIT_1:
1422                 case FIN_WAIT_2:
1423                         break;
1424
1425                 case CLOSE_WAIT:
1426                 case CLOSING:
1427                 case LAST_ACK:
1428                 case TIME_WAIT:
1429                         // Ehm no, We should never receive more data after a FIN.
1430                         goto reset;
1431
1432                 default:
1433 #ifdef UTCP_DEBUG
1434                         abort();
1435 #endif
1436                         return 0;
1437                 }
1438
1439                 handle_incoming_data(c, hdr.seq, ptr, len);
1440         }
1441
1442         // 7. Process FIN stuff
1443
1444         if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1445                 switch(c->state) {
1446                 case SYN_SENT:
1447                 case SYN_RECEIVED:
1448                         // This should never happen.
1449 #ifdef UTCP_DEBUG
1450                         abort();
1451 #endif
1452                         break;
1453
1454                 case ESTABLISHED:
1455                         set_state(c, CLOSE_WAIT);
1456                         break;
1457
1458                 case FIN_WAIT_1:
1459                         set_state(c, CLOSING);
1460                         break;
1461
1462                 case FIN_WAIT_2:
1463                         gettimeofday(&c->conn_timeout, NULL);
1464                         c->conn_timeout.tv_sec += 60;
1465                         set_state(c, TIME_WAIT);
1466                         break;
1467
1468                 case CLOSE_WAIT:
1469                 case CLOSING:
1470                 case LAST_ACK:
1471                 case TIME_WAIT:
1472                         // Ehm, no. We should never receive a second FIN.
1473                         goto reset;
1474
1475                 default:
1476 #ifdef UTCP_DEBUG
1477                         abort();
1478 #endif
1479                         break;
1480                 }
1481
1482                 // FIN counts as one sequence number
1483                 c->rcv.nxt++;
1484                 len++;
1485
1486                 // Inform the application that the peer closed the connection.
1487                 if(c->recv) {
1488                         errno = 0;
1489                         c->recv(c, NULL, 0);
1490                 }
1491         }
1492
1493         // Now we send something back if:
1494         // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1495         //   -> sendatleastone = true
1496         // - or we got an ack, so we should maybe send a bit more data
1497         //   -> sendatleastone = false
1498
1499         ack(c, len || prevrcvnxt != c->rcv.nxt);
1500         return 0;
1501
1502 reset:
1503         swap_ports(&hdr);
1504         hdr.wnd = 0;
1505         hdr.aux = 0;
1506
1507         if(hdr.ctl & ACK) {
1508                 hdr.seq = hdr.ack;
1509                 hdr.ctl = RST;
1510         } else {
1511                 hdr.ack = hdr.seq + len;
1512                 hdr.seq = 0;
1513                 hdr.ctl = RST | ACK;
1514         }
1515
1516         print_packet(utcp, "send", &hdr, sizeof(hdr));
1517         utcp->send(utcp, &hdr, sizeof(hdr));
1518         return 0;
1519
1520 }
1521
1522 int utcp_shutdown(struct utcp_connection *c, int dir) {
1523         debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1524
1525         if(!c) {
1526                 errno = EFAULT;
1527                 return -1;
1528         }
1529
1530         if(c->reapable) {
1531                 debug("Error: shutdown() called on closed connection %p\n", c);
1532                 errno = EBADF;
1533                 return -1;
1534         }
1535
1536         if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1537                 errno = EINVAL;
1538                 return -1;
1539         }
1540
1541         // TCP does not have a provision for stopping incoming packets.
1542         // The best we can do is to just ignore them.
1543         if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1544                 c->recv = NULL;
1545         }
1546
1547         // The rest of the code deals with shutting down writes.
1548         if(dir == UTCP_SHUT_RD) {
1549                 return 0;
1550         }
1551
1552         // Only process shutting down writes once.
1553         if (c->shut_wr)
1554                 return 0;
1555
1556         c->shut_wr = true;
1557
1558         switch(c->state) {
1559         case CLOSED:
1560         case LISTEN:
1561                 errno = ENOTCONN;
1562                 return -1;
1563
1564         case SYN_SENT:
1565                 return 0;
1566
1567         case SYN_RECEIVED:
1568         case ESTABLISHED:
1569                 set_state(c, FIN_WAIT_1);
1570                 break;
1571
1572         case FIN_WAIT_1:
1573         case FIN_WAIT_2:
1574                 return 0;
1575
1576         case CLOSE_WAIT:
1577                 set_state(c, CLOSING);
1578                 break;
1579
1580         case CLOSING:
1581         case LAST_ACK:
1582         case TIME_WAIT:
1583                 return 0;
1584         }
1585
1586         c->snd.last++;
1587
1588         ack(c, false);
1589
1590         if(!timerisset(&c->rtrx_timeout)) {
1591                 start_retransmit_timer(c);
1592         }
1593
1594         return 0;
1595 }
1596
1597 int utcp_close(struct utcp_connection *c) {
1598         if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
1599                 return -1;
1600         }
1601
1602         c->recv = NULL;
1603         c->poll = NULL;
1604         c->reapable = true;
1605         return 0;
1606 }
1607
1608 int utcp_abort(struct utcp_connection *c) {
1609         if(!c) {
1610                 errno = EFAULT;
1611                 return -1;
1612         }
1613
1614         if(c->reapable) {
1615                 debug("Error: abort() called on closed connection %p\n", c);
1616                 errno = EBADF;
1617                 return -1;
1618         }
1619
1620         c->recv = NULL;
1621         c->poll = NULL;
1622         c->reapable = true;
1623
1624         switch(c->state) {
1625         case CLOSED:
1626                 return 0;
1627
1628         case LISTEN:
1629         case SYN_SENT:
1630         case CLOSING:
1631         case LAST_ACK:
1632         case TIME_WAIT:
1633                 set_state(c, CLOSED);
1634                 return 0;
1635
1636         case SYN_RECEIVED:
1637         case ESTABLISHED:
1638         case FIN_WAIT_1:
1639         case FIN_WAIT_2:
1640         case CLOSE_WAIT:
1641                 set_state(c, CLOSED);
1642                 break;
1643         }
1644
1645         // Send RST
1646
1647         struct hdr hdr;
1648
1649         hdr.src = c->src;
1650         hdr.dst = c->dst;
1651         hdr.seq = c->snd.nxt;
1652         hdr.ack = 0;
1653         hdr.wnd = 0;
1654         hdr.ctl = RST;
1655
1656         print_packet(c->utcp, "send", &hdr, sizeof(hdr));
1657         c->utcp->send(c->utcp, &hdr, sizeof(hdr));
1658         return 0;
1659 }
1660
1661 /* Handle timeouts.
1662  * One call to this function will loop through all connections,
1663  * checking if something needs to be resent or not.
1664  * The return value is the time to the next timeout in milliseconds,
1665  * or maybe a negative value if the timeout is infinite.
1666  */
1667 struct timeval utcp_timeout(struct utcp *utcp) {
1668         struct timeval now;
1669         gettimeofday(&now, NULL);
1670         struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1671
1672         for(int i = 0; i < utcp->nconnections; i++) {
1673                 struct utcp_connection *c = utcp->connections[i];
1674
1675                 if(!c) {
1676                         continue;
1677                 }
1678
1679                 // delete connections that have been utcp_close()d.
1680                 if(c->state == CLOSED) {
1681                         if(c->reapable) {
1682                                 debug("Reaping %p\n", c);
1683                                 free_connection(c);
1684                                 i--;
1685                         }
1686
1687                         continue;
1688                 }
1689
1690                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1691                         errno = ETIMEDOUT;
1692                         c->state = CLOSED;
1693
1694                         if(c->recv) {
1695                                 c->recv(c, NULL, 0);
1696                         }
1697
1698                         continue;
1699                 }
1700
1701                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1702                         debug("retransmit()\n");
1703                         retransmit(c);
1704                 }
1705
1706                 if(c->poll) {
1707                         if((c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1708                                 uint32_t len =  buffer_free(&c->sndbuf);
1709
1710                                 if(len) {
1711                                         c->poll(c, len);
1712                                 }
1713                         } else if(c->state == CLOSED) {
1714                                 c->poll(c, 0);
1715                         }
1716                 }
1717
1718                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <)) {
1719                         next = c->conn_timeout;
1720                 }
1721
1722                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <)) {
1723                         next = c->rtrx_timeout;
1724                 }
1725         }
1726
1727         struct timeval diff;
1728
1729         timersub(&next, &now, &diff);
1730
1731         return diff;
1732 }
1733
1734 bool utcp_is_active(struct utcp *utcp) {
1735         if(!utcp) {
1736                 return false;
1737         }
1738
1739         for(int i = 0; i < utcp->nconnections; i++)
1740                 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
1741                         return true;
1742                 }
1743
1744         return false;
1745 }
1746
1747 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1748         if(!send) {
1749                 errno = EFAULT;
1750                 return NULL;
1751         }
1752
1753         struct utcp *utcp = calloc(1, sizeof(*utcp));
1754
1755         if(!utcp) {
1756                 return NULL;
1757         }
1758
1759         utcp->accept = accept;
1760         utcp->pre_accept = pre_accept;
1761         utcp->send = send;
1762         utcp->priv = priv;
1763         utcp->mtu = DEFAULT_MTU;
1764         utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
1765         utcp->rto = START_RTO; // usec
1766
1767         return utcp;
1768 }
1769
1770 void utcp_exit(struct utcp *utcp) {
1771         if(!utcp) {
1772                 return;
1773         }
1774
1775         for(int i = 0; i < utcp->nconnections; i++) {
1776                 struct utcp_connection *c = utcp->connections[i];
1777
1778                 if(!c->reapable)
1779                         if(c->recv) {
1780                                 c->recv(c, NULL, 0);
1781                         }
1782
1783                 buffer_exit(&c->rcvbuf);
1784                 buffer_exit(&c->sndbuf);
1785                 free(c);
1786         }
1787
1788         free(utcp->connections);
1789         free(utcp);
1790 }
1791
1792 uint16_t utcp_get_mtu(struct utcp *utcp) {
1793         return utcp ? utcp->mtu : 0;
1794 }
1795
1796 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1797         // TODO: handle overhead of the header
1798         if(utcp) {
1799                 utcp->mtu = mtu;
1800         }
1801 }
1802
1803 void utcp_reset_timers(struct utcp *utcp) {
1804         if(!utcp) {
1805                 return;
1806         }
1807
1808         struct timeval now, then;
1809
1810         gettimeofday(&now, NULL);
1811
1812         then = now;
1813
1814         then.tv_sec += utcp->timeout;
1815
1816         for(int i = 0; i < utcp->nconnections; i++) {
1817                 utcp->connections[i]->rtrx_timeout = now;
1818                 utcp->connections[i]->conn_timeout = then;
1819                 utcp->connections[i]->rtt_start.tv_sec = 0;
1820         }
1821
1822         if(utcp->rto > START_RTO) {
1823                 utcp->rto = START_RTO;
1824         }
1825 }
1826
1827 int utcp_get_user_timeout(struct utcp *u) {
1828         return u ? u->timeout : 0;
1829 }
1830
1831 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1832         if(u) {
1833                 u->timeout = timeout;
1834         }
1835 }
1836
1837 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1838         return c ? c->sndbuf.maxsize : 0;
1839 }
1840
1841 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1842         if (!c)
1843                 return 0;
1844
1845         switch(c->state) {
1846         case SYN_SENT:
1847         case SYN_RECEIVED:
1848         case ESTABLISHED:
1849         case CLOSE_WAIT:
1850                 return buffer_free(&c->sndbuf);
1851
1852         default:
1853                 return 0;
1854         }
1855 }
1856
1857 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1858         if(!c) {
1859                 return;
1860         }
1861
1862         c->sndbuf.maxsize = size;
1863
1864         if(c->sndbuf.maxsize != size) {
1865                 c->sndbuf.maxsize = -1;
1866         }
1867 }
1868
1869 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1870         return c ? c->rcvbuf.maxsize : 0;
1871 }
1872
1873 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1874         if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1875                 return buffer_free(&c->rcvbuf);
1876         } else {
1877                 return 0;
1878         }
1879 }
1880
1881 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1882         if(!c) {
1883                 return;
1884         }
1885
1886         c->rcvbuf.maxsize = size;
1887
1888         if(c->rcvbuf.maxsize != size) {
1889                 c->rcvbuf.maxsize = -1;
1890         }
1891 }
1892
1893 bool utcp_get_nodelay(struct utcp_connection *c) {
1894         return c ? c->nodelay : false;
1895 }
1896
1897 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1898         if(c) {
1899                 c->nodelay = nodelay;
1900         }
1901 }
1902
1903 bool utcp_get_keepalive(struct utcp_connection *c) {
1904         return c ? c->keepalive : false;
1905 }
1906
1907 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1908         if(c) {
1909                 c->keepalive = keepalive;
1910         }
1911 }
1912
1913 size_t utcp_get_outq(struct utcp_connection *c) {
1914         return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1915 }
1916
1917 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1918         if(c) {
1919                 c->recv = recv;
1920         }
1921 }
1922
1923 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1924         if(c) {
1925                 c->poll = poll;
1926         }
1927 }
1928
1929 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
1930         if(utcp) {
1931                 utcp->accept = accept;
1932                 utcp->pre_accept = pre_accept;
1933         }
1934 }