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